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"
89 #define SHARED_EXT ".so"
92 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
93 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
94 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
96 /* predefined values for static readonly fields without needed to run the .cctor */
97 typedef struct _ReadOnlyValue ReadOnlyValue;
98 struct _ReadOnlyValue {
101 int type; /* to be used later for typechecking to prevent user errors */
110 static ReadOnlyValue *readonly_values = NULL;
112 typedef struct MonoAotOptions {
115 gboolean write_symbols;
116 gboolean metadata_only;
117 gboolean bind_to_runtime_version;
120 gboolean static_link;
125 gboolean log_generics;
126 gboolean direct_pinvoke;
127 gboolean direct_icalls;
130 int nrgctx_trampolines;
131 int nimt_trampolines;
132 gboolean print_skipped_methods;
140 typedef struct MonoAotStats {
141 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
142 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
143 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
144 int got_slots, offsets_size;
145 int got_slot_types [MONO_PATCH_INFO_NONE];
146 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
147 int jit_time, gen_time, link_time;
150 typedef struct MonoAotCompile {
153 GHashTable *method_indexes;
154 GHashTable *method_depth;
157 GHashTable *patch_to_plt_entry;
158 GHashTable *plt_offset_to_entry;
159 GHashTable *patch_to_got_offset;
160 GHashTable **patch_to_got_offset_by_type;
161 GPtrArray *got_patches;
162 GHashTable *image_hash;
163 GHashTable *method_to_cfg;
164 GHashTable *token_info_hash;
165 GHashTable *method_to_pinvoke_import;
166 GPtrArray *extra_methods;
167 GPtrArray *image_table;
169 GPtrArray *method_order;
170 GHashTable *export_names;
171 /* Maps MonoClass* -> blob offset */
172 GHashTable *klass_blob_hash;
173 /* Maps MonoMethod* -> blob offset */
174 GHashTable *method_blob_hash;
175 guint32 *plt_got_info_offsets;
176 guint32 got_offset, plt_offset, plt_got_offset_base;
177 guint32 final_got_size;
178 /* Number of GOT entries reserved for trampolines */
179 guint32 num_trampoline_got_entries;
181 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
182 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
183 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
185 MonoAotOptions aot_opts;
189 MonoMemPool *mempool;
192 char *static_linking_symbol;
193 CRITICAL_SECTION mutex;
194 gboolean use_bin_writer;
196 MonoDwarfWriter *dwarf;
200 GHashTable *unwind_info_offsets;
201 GPtrArray *unwind_ops;
202 guint32 unwind_info_offset;
203 char *got_symbol_base;
206 GHashTable *method_label_hash;
207 const char *temp_prefix;
208 const char *llvm_label_prefix;
209 guint32 label_generator;
211 MonoAotFileFlags flags;
212 MonoDynamicStream blob;
213 MonoClass **typespec_classes;
216 char *assembly_name_sym;
217 GHashTable *plt_entry_debug_sym_cache;
218 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
219 GHashTable *ginst_hash;
224 char *symbol, *llvm_symbol, *debug_sym;
226 gboolean jit_used, llvm_used;
229 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
230 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
232 /* This points to the current acfg in LLVM mode */
233 static MonoAotCompile *llvm_acfg;
235 #ifdef HAVE_ARRAY_ELEM_INIT
236 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
237 #define MSGSTRFIELD1(line) str##line
238 static const struct msgstr_t {
239 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
240 #include "patch-info.h"
243 #define PATCH_INFO(a,b) b,
244 #include "patch-info.h"
247 static const gint16 opidx [] = {
248 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
249 #include "patch-info.h"
253 static G_GNUC_UNUSED const char*
254 get_patch_name (int info)
256 return (const char*)&opstr + opidx [info];
260 #define PATCH_INFO(a,b) b,
261 static const char* const
262 patch_types [MONO_PATCH_INFO_NUM + 1] = {
263 #include "patch-info.h"
267 static G_GNUC_UNUSED const char*
268 get_patch_name (int info)
270 return patch_types [info];
276 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
278 /* Wrappers around the image writer functions */
281 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
283 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
287 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
289 img_writer_emit_push_section (acfg->w, section_name, subsection);
293 emit_pop_section (MonoAotCompile *acfg)
295 img_writer_emit_pop_section (acfg->w);
299 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
301 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
305 emit_label (MonoAotCompile *acfg, const char *name)
307 img_writer_emit_label (acfg->w, name);
311 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
313 img_writer_emit_bytes (acfg->w, buf, size);
317 emit_string (MonoAotCompile *acfg, const char *value)
319 img_writer_emit_string (acfg->w, value);
323 emit_line (MonoAotCompile *acfg)
325 img_writer_emit_line (acfg->w);
329 emit_alignment (MonoAotCompile *acfg, int size)
331 img_writer_emit_alignment (acfg->w, size);
335 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
337 img_writer_emit_pointer_unaligned (acfg->w, target);
341 emit_pointer (MonoAotCompile *acfg, const char *target)
343 img_writer_emit_pointer (acfg->w, target);
347 emit_int16 (MonoAotCompile *acfg, int value)
349 img_writer_emit_int16 (acfg->w, value);
353 emit_int32 (MonoAotCompile *acfg, int value)
355 img_writer_emit_int32 (acfg->w, value);
359 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
361 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
365 emit_zero_bytes (MonoAotCompile *acfg, int num)
367 img_writer_emit_zero_bytes (acfg->w, num);
371 emit_byte (MonoAotCompile *acfg, guint8 val)
373 img_writer_emit_byte (acfg->w, val);
376 #ifdef __native_client_codegen__
378 emit_nacl_call_alignment (MonoAotCompile *acfg)
380 img_writer_emit_nacl_call_alignment (acfg->w);
384 static G_GNUC_UNUSED void
385 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
387 img_writer_emit_global (acfg->w, name, func);
391 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
393 if (acfg->aot_opts.no_dlsym) {
394 g_ptr_array_add (acfg->globals, g_strdup (name));
395 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
397 img_writer_emit_global (acfg->w, name, func);
402 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
404 img_writer_emit_symbol_size (acfg->w, name, end_label);
408 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
410 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
412 /* On apple, all symbols need to be aligned to avoid warnings from ld */
413 emit_alignment (acfg, 4);
415 img_writer_emit_label (acfg->w, name);
416 img_writer_emit_string (acfg->w, value);
419 static G_GNUC_UNUSED void
420 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
423 guint8 b = value & 0x7f;
425 if (value != 0) /* more bytes to come */
431 static G_GNUC_UNUSED void
432 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
435 gboolean negative = (value < 0);
442 /* the following is unnecessary if the
443 * implementation of >>= uses an arithmetic rather
444 * than logical shift for a signed left operand
448 value |= - ((gint64)1 <<(size - 7));
449 /* sign bit of byte is second high order bit (0x40) */
450 if ((value == 0 && !(byte & 0x40)) ||
451 (value == -1 && (byte & 0x40)))
455 emit_byte (acfg, byte);
459 static G_GNUC_UNUSED void
460 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
465 guint8 b = value & 0x7f;
467 if (value != 0) /* more bytes to come */
475 static G_GNUC_UNUSED void
476 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
479 gboolean negative = (value < 0);
487 /* the following is unnecessary if the
488 * implementation of >>= uses an arithmetic rather
489 * than logical shift for a signed left operand
493 value |= - (1 <<(size - 7));
494 /* sign bit of byte is second high order bit (0x40) */
495 if ((value == 0 && !(byte & 0x40)) ||
496 (value == -1 && (byte & 0x40)))
506 /* ARCHITECTURE SPECIFIC CODE */
508 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
509 #define EMIT_DWARF_INFO 1
512 #if defined(TARGET_ARM)
513 #define AOT_FUNC_ALIGNMENT 4
515 #define AOT_FUNC_ALIGNMENT 16
517 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
518 #undef AOT_FUNC_ALIGNMENT
519 #define AOT_FUNC_ALIGNMENT 32
522 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
523 #define PPC_LD_OP "ld"
524 #define PPC_LDX_OP "ldx"
526 #define PPC_LD_OP "lwz"
527 #define PPC_LDX_OP "lwzx"
531 #define AOT_TARGET_STR "AMD64"
536 #define AOT_TARGET_STR "ARM (MACH)"
538 #define AOT_TARGET_STR "ARM (!MACH)"
542 #ifdef TARGET_POWERPC64
543 #ifdef __mono_ilp32__
544 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
546 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
549 #ifdef TARGET_POWERPC
550 #ifdef __mono_ilp32__
551 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
553 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
560 #define AOT_TARGET_STR "X86 (WIN32)"
561 #elif defined(__native_client_codegen__)
562 #define AOT_TARGET_STR "X86 (native client codegen)"
564 #define AOT_TARGET_STR "X86 (!native client codegen)"
568 #ifndef AOT_TARGET_STR
569 #define AOT_TARGET_STR ""
573 arch_init (MonoAotCompile *acfg)
575 acfg->llc_args = g_string_new ("");
576 acfg->as_args = g_string_new ("");
579 * The prefix LLVM likes to put in front of symbol names on darwin.
580 * The mach-os specs require this for globals, but LLVM puts them in front of all
581 * symbols. We need to handle this, since we need to refer to LLVM generated
584 acfg->llvm_label_prefix = "";
587 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
588 g_string_append (acfg->llc_args, "-mattr=+v6");
591 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
592 g_string_append (acfg->as_args, " -mfpu=vfp3");
594 g_string_append (acfg->llc_args, " -soft-float");
597 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
598 acfg->thumb_mixed = TRUE;
600 if (acfg->aot_opts.mtriple)
601 mono_arch_set_target (acfg->aot_opts.mtriple);
605 acfg->llvm_label_prefix = "_";
606 acfg->need_no_dead_strip = TRUE;
609 #if defined(__linux__) && !defined(TARGET_ARM)
610 acfg->need_pt_gnu_stack = TRUE;
615 * arch_emit_direct_call:
617 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
621 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
623 #if defined(TARGET_X86) || defined(TARGET_AMD64)
624 /* Need to make sure this is exactly 5 bytes long */
625 if (FALSE && !acfg->use_bin_writer) {
626 img_writer_emit_unset_mode (acfg->w);
627 fprintf (acfg->fp, "call %s\n", target);
629 emit_byte (acfg, '\xe8');
630 emit_symbol_diff (acfg, target, ".", -4);
633 #elif defined(TARGET_ARM)
634 if (acfg->use_bin_writer) {
641 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
642 emit_bytes (acfg, buf, 4);
644 img_writer_emit_unset_mode (acfg->w);
645 fprintf (acfg->fp, "bl %s\n", target);
648 #elif defined(TARGET_POWERPC)
649 if (acfg->use_bin_writer) {
650 g_assert_not_reached ();
652 img_writer_emit_unset_mode (acfg->w);
653 fprintf (acfg->fp, "bl %s\n", target);
657 g_assert_not_reached ();
663 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
665 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
666 * in in the 2. slot of every GOT, and require every method to place the GOT
667 * address in r30, even when it doesn't access the GOT otherwise. This way,
668 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
673 * PPC64 uses function descriptors which greatly complicate all code, since
674 * these are used very inconsistently in the runtime. Some functions like
675 * mono_compile_method () return ftn descriptors, while others like the
676 * trampoline creation functions do not.
677 * We assume that all GOT slots contain function descriptors, and create
678 * descriptors in aot-runtime.c when needed.
679 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
680 * from function descriptors, we could do the same, but it would require
681 * rewriting all the ppc/aot code to handle function descriptors properly.
682 * So instead, we use the same approach as on PPC32.
683 * This is a horrible mess, but fixing it would probably lead to an even bigger
689 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
692 #ifdef MONO_ARCH_AOT_SUPPORTED
694 * arch_emit_got_offset:
696 * The memory pointed to by CODE should hold native code for computing the GOT
697 * address. Emit this code while patching it with the offset between code and
698 * the GOT. CODE_SIZE is set to the number of bytes emitted.
701 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
703 #if defined(TARGET_POWERPC64)
704 g_assert (!acfg->use_bin_writer);
705 img_writer_emit_unset_mode (acfg->w);
707 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
708 * unsupported relocations. So we store the got address into the .Lgot_addr
709 * symbol which is in the text segment, compute its address, and load it.
711 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
712 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
713 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
714 fprintf (acfg->fp, "add 30, 30, 0\n");
715 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
716 acfg->label_generator ++;
718 #elif defined(TARGET_POWERPC)
719 g_assert (!acfg->use_bin_writer);
720 img_writer_emit_unset_mode (acfg->w);
721 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
722 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
723 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
724 acfg->label_generator ++;
727 guint32 offset = mono_arch_get_patch_offset (code);
728 emit_bytes (acfg, code, offset);
729 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
731 *code_size = offset + 4;
736 * arch_emit_got_access:
738 * The memory pointed to by CODE should hold native code for loading a GOT
739 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
740 * CODE_SIZE is set to the number of bytes emitted.
743 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
745 /* Emit beginning of instruction */
746 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
748 /* Emit the offset */
750 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
751 *code_size = mono_arch_get_patch_offset (code) + 4;
752 #elif defined(TARGET_X86)
753 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
754 *code_size = mono_arch_get_patch_offset (code) + 4;
755 #elif defined(TARGET_ARM)
756 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
757 *code_size = mono_arch_get_patch_offset (code) + 4;
758 #elif defined(TARGET_POWERPC)
764 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
765 g_assert (code - buf == 8);
766 emit_bytes (acfg, buf, code - buf);
767 *code_size = code - buf;
770 g_assert_not_reached ();
777 * arch_emit_plt_entry:
779 * Emit code for the PLT entry with index INDEX.
782 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
784 #if defined(TARGET_X86)
785 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
786 #if defined(__default_codegen__)
787 /* jmp *<offset>(%ebx) */
788 emit_byte (acfg, 0xff);
789 emit_byte (acfg, 0xa3);
790 emit_int32 (acfg, offset);
791 /* Used by mono_aot_get_plt_info_offset */
792 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
793 #elif defined(__native_client_codegen__)
794 const guint8 kSizeOfNaClJmp = 11;
795 guint8 bytes[kSizeOfNaClJmp];
796 guint8 *pbytes = &bytes[0];
798 x86_jump_membase32 (pbytes, X86_EBX, offset);
799 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
800 /* four bytes of data, used by mono_arch_patch_plt_entry */
801 /* For Native Client, make this work with data embedded in push. */
802 emit_byte (acfg, 0x68); /* hide data in a push */
803 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
804 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
805 #endif /*__native_client_codegen__*/
806 #elif defined(TARGET_AMD64)
807 #if defined(__default_codegen__)
809 * We can't emit jumps because they are 32 bits only so they can't be patched.
810 * So we make indirect calls through GOT entries which are patched by the AOT
811 * loader to point to .Lpd entries.
813 /* jmpq *<offset>(%rip) */
814 emit_byte (acfg, '\xff');
815 emit_byte (acfg, '\x25');
816 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
817 /* Used by mono_aot_get_plt_info_offset */
818 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
819 #elif defined(__native_client_codegen__)
821 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
822 guint8 *code = buf_aligned;
824 /* mov <OFFSET>(%rip), %r11d */
825 emit_byte (acfg, '\x45');
826 emit_byte (acfg, '\x8b');
827 emit_byte (acfg, '\x1d');
828 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
830 amd64_jump_reg (code, AMD64_R11);
831 /* This should be constant for the plt patch */
832 g_assert ((size_t)(code-buf_aligned) == 10);
833 emit_bytes (acfg, buf_aligned, code - buf_aligned);
835 /* Hide data in a push imm32 so it passes validation */
836 emit_byte (acfg, 0x68); /* push */
837 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
838 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
839 #endif /*__native_client_codegen__*/
840 #elif defined(TARGET_ARM)
845 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
846 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
847 emit_bytes (acfg, buf, code - buf);
848 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
849 /* Used by mono_aot_get_plt_info_offset */
850 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
851 #elif defined(TARGET_POWERPC)
852 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
854 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
855 g_assert (!acfg->use_bin_writer);
856 img_writer_emit_unset_mode (acfg->w);
857 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
858 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
859 fprintf (acfg->fp, "add 11, 11, 30\n");
860 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
861 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
862 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
863 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
865 fprintf (acfg->fp, "mtctr 11\n");
866 fprintf (acfg->fp, "bctr\n");
867 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
869 g_assert_not_reached ();
874 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
876 #if defined(TARGET_ARM)
878 /* LLVM calls the PLT entries using bl, so emit a stub */
879 /* FIXME: Too much overhead on every call */
880 fprintf (acfg->fp, ".thumb_func\n");
881 fprintf (acfg->fp, "bx pc\n");
882 fprintf (acfg->fp, "nop\n");
883 fprintf (acfg->fp, ".arm\n");
885 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
886 /* The caller already transitioned to thumb */
887 /* The code below should be 12 bytes long */
888 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
889 /* thumb can't encode ld pc, [pc, ip] */
890 fprintf (acfg->fp, "add ip, pc, ip\n");
891 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
892 fprintf (acfg->fp, "bx ip\n");
893 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
894 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
896 g_assert_not_reached ();
901 * arch_emit_specific_trampoline:
903 * Emit code for a specific trampoline. OFFSET is the offset of the first of
904 * two GOT slots which contain the generic trampoline address and the trampoline
905 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
908 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
911 * The trampolines created here are variations of the specific
912 * trampolines created in mono_arch_create_specific_trampoline (). The
914 * - the generic trampoline address is taken from a got slot.
915 * - the offset of the got slot where the trampoline argument is stored
916 * is embedded in the instruction stream, and the generic trampoline
917 * can load the argument by loading the offset, adding it to the
918 * address of the trampoline to get the address of the got slot, and
919 * loading the argument from there.
920 * - all the trampolines should be of the same length.
922 #if defined(TARGET_AMD64)
923 #if defined(__default_codegen__)
924 /* This should be exactly 16 bytes long */
926 /* call *<offset>(%rip) */
927 emit_byte (acfg, '\x41');
928 emit_byte (acfg, '\xff');
929 emit_byte (acfg, '\x15');
930 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
931 /* This should be relative to the start of the trampoline */
932 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
933 emit_zero_bytes (acfg, 5);
934 #elif defined(__native_client_codegen__)
936 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
937 guint8 *code = buf_aligned;
942 /* Emit this call in 'code' so we can find out how long it is. */
943 amd64_call_reg (code, AMD64_R11);
944 call_start = mono_arch_nacl_skip_nops (buf_aligned);
945 call_len = code - call_start;
947 /* The tramp_size is twice the NaCl alignment because it starts with */
948 /* a call which needs to be aligned to the end of the boundary. */
949 *tramp_size = kNaClAlignment*2;
951 /* Emit nops to align call site below which is 7 bytes plus */
952 /* the length of the call sequence emitted above. */
953 /* Note: this requires the specific trampoline starts on a */
954 /* kNaclAlignedment aligned address, which it does because */
955 /* it's its own function that is aligned. */
957 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
958 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
959 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
961 /* The trampoline is stored at the offset'th pointer, the -4 is */
962 /* present because RIP relative addressing starts at the end of */
963 /* the current instruction, while the label "." is relative to */
964 /* the beginning of the current asm location, which in this case */
965 /* is not the mov instruction, but the offset itself, due to the */
966 /* way the bytes and ints are emitted here. */
967 got_offset = (offset * sizeof(gpointer)) - 4;
969 /* mov <OFFSET>(%rip), %r11d */
970 emit_byte (acfg, '\x45');
971 emit_byte (acfg, '\x8b');
972 emit_byte (acfg, '\x1d');
973 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
976 emit_bytes (acfg, call_start, call_len);
978 /* The arg is stored at the offset+1 pointer, relative to beginning */
979 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
980 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
982 /* We can't emit this data directly, hide in a "push imm32" */
983 emit_byte (acfg, '\x68'); /* push */
984 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
985 emit_alignment (acfg, kNaClAlignment);
986 #endif /*__native_client_codegen__*/
987 #elif defined(TARGET_ARM)
991 /* This should be exactly 20 bytes long */
994 ARM_PUSH (code, 0x5fff);
995 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
996 /* Load the value from the GOT */
997 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
999 ARM_BLX_REG (code, ARMREG_R1);
1001 g_assert (code - buf == 16);
1004 emit_bytes (acfg, buf, code - buf);
1006 * Only one offset is needed, since the second one would be equal to the
1009 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1010 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1011 #elif defined(TARGET_POWERPC)
1018 g_assert (!acfg->use_bin_writer);
1021 * PPC has no ip relative addressing, so we need to compute the address
1022 * of the mscorlib got. That is slow and complex, so instead, we store it
1023 * in the second got slot of every aot image. The caller already computed
1024 * the address of its got and placed it into r30.
1026 img_writer_emit_unset_mode (acfg->w);
1027 /* Load mscorlib got address */
1028 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1029 /* Load generic trampoline address */
1030 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1031 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1032 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1033 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1034 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1036 fprintf (acfg->fp, "mtctr 11\n");
1037 /* Load trampoline argument */
1038 /* On ppc, we pass it normally to the generic trampoline */
1039 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1040 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1041 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1042 /* Branch to generic trampoline */
1043 fprintf (acfg->fp, "bctr\n");
1045 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1046 *tramp_size = 10 * 4;
1048 *tramp_size = 9 * 4;
1050 #elif defined(TARGET_X86)
1054 /* Similar to the PPC code above */
1056 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1058 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1059 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1060 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1064 /* Load mscorlib got address */
1065 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1066 /* Push trampoline argument */
1067 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1068 /* Load generic trampoline address */
1069 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1070 /* Branch to generic trampoline */
1071 x86_jump_reg (code, X86_ECX);
1073 #ifdef __native_client_codegen__
1075 /* emit nops to next 32 byte alignment */
1076 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1077 while (code < (buf + a)) x86_nop(code);
1080 emit_bytes (acfg, buf, code - buf);
1082 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1083 g_assert (code - buf == *tramp_size);
1085 g_assert_not_reached ();
1090 * arch_emit_unbox_trampoline:
1092 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1093 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1096 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1098 #if defined(TARGET_AMD64)
1103 this_reg = mono_arch_get_this_arg_reg (NULL);
1105 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1107 emit_bytes (acfg, buf, code - buf);
1109 emit_byte (acfg, '\xe9');
1110 emit_symbol_diff (acfg, call_target, ".", -4);
1111 #elif defined(TARGET_X86)
1118 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1120 emit_bytes (acfg, buf, code - buf);
1123 emit_byte (acfg, '\xe9');
1124 emit_symbol_diff (acfg, call_target, ".", -4);
1125 #elif defined(TARGET_ARM)
1129 if (acfg->thumb_mixed && cfg->compile_llvm) {
1130 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1131 fprintf (acfg->fp, "b %s\n", call_target);
1132 fprintf (acfg->fp, ".arm\n");
1138 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1140 emit_bytes (acfg, buf, code - buf);
1141 /* jump to method */
1142 if (acfg->use_bin_writer) {
1149 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1150 emit_bytes (acfg, buf, 4);
1152 if (acfg->thumb_mixed && cfg->compile_llvm)
1153 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1155 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1157 #elif defined(TARGET_POWERPC)
1160 g_assert (!acfg->use_bin_writer);
1162 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1163 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1165 g_assert_not_reached ();
1170 * arch_emit_static_rgctx_trampoline:
1172 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1173 * two GOT slots which contain the rgctx argument, and the method to jump to.
1174 * TRAMP_SIZE is set to the size of the emitted trampoline.
1175 * These kinds of trampolines cannot be enumerated statically, since there could
1176 * be one trampoline per method instantiation, so we emit the same code for all
1177 * trampolines, and parameterize them using two GOT slots.
1180 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1182 #if defined(TARGET_AMD64)
1183 #if defined(__default_codegen__)
1184 /* This should be exactly 13 bytes long */
1187 /* mov <OFFSET>(%rip), %r10 */
1188 emit_byte (acfg, '\x4d');
1189 emit_byte (acfg, '\x8b');
1190 emit_byte (acfg, '\x15');
1191 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1193 /* jmp *<offset>(%rip) */
1194 emit_byte (acfg, '\xff');
1195 emit_byte (acfg, '\x25');
1196 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1197 #elif defined(__native_client_codegen__)
1199 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1200 guint8 *code = buf_aligned;
1202 /* mov <OFFSET>(%rip), %r10d */
1203 emit_byte (acfg, '\x45');
1204 emit_byte (acfg, '\x8b');
1205 emit_byte (acfg, '\x15');
1206 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1208 /* mov <OFFSET>(%rip), %r11d */
1209 emit_byte (acfg, '\x45');
1210 emit_byte (acfg, '\x8b');
1211 emit_byte (acfg, '\x1d');
1212 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1215 amd64_jump_reg (code, AMD64_R11);
1216 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1218 emit_alignment (acfg, kNaClAlignment);
1219 *tramp_size = kNaClAlignment;
1220 #endif /*__native_client_codegen__*/
1222 #elif defined(TARGET_ARM)
1226 /* This should be exactly 24 bytes long */
1229 /* Load rgctx value */
1230 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1231 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1232 /* Load branch addr + branch */
1233 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1234 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1236 g_assert (code - buf == 16);
1239 emit_bytes (acfg, buf, code - buf);
1240 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1241 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1242 #elif defined(TARGET_POWERPC)
1249 g_assert (!acfg->use_bin_writer);
1252 * PPC has no ip relative addressing, so we need to compute the address
1253 * of the mscorlib got. That is slow and complex, so instead, we store it
1254 * in the second got slot of every aot image. The caller already computed
1255 * the address of its got and placed it into r30.
1257 img_writer_emit_unset_mode (acfg->w);
1258 /* Load mscorlib got address */
1259 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1261 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1262 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1263 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1264 /* Load target address */
1265 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1266 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1267 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1268 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1269 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1270 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1272 fprintf (acfg->fp, "mtctr 11\n");
1273 /* Branch to the target address */
1274 fprintf (acfg->fp, "bctr\n");
1276 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1277 *tramp_size = 11 * 4;
1279 *tramp_size = 9 * 4;
1282 #elif defined(TARGET_X86)
1286 /* Similar to the PPC code above */
1288 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1291 /* Load mscorlib got address */
1292 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1294 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1295 /* Branch to the target address */
1296 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1298 #ifdef __native_client_codegen__
1300 /* emit nops to next 32 byte alignment */
1301 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1302 while (code < (buf + a)) x86_nop(code);
1306 emit_bytes (acfg, buf, code - buf);
1308 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1309 g_assert (code - buf == *tramp_size);
1311 g_assert_not_reached ();
1316 * arch_emit_imt_thunk:
1318 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1319 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1320 * key is the IMT key, and ptr holds the address of a memory location holding
1321 * the address to branch to if the IMT arg matches the key. The array is
1322 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1324 * TRAMP_SIZE is set to the size of the emitted trampoline.
1327 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1329 #if defined(TARGET_AMD64)
1331 #if defined(__native_client_codegen__)
1334 guint8 *labels [16];
1336 guint8 *mov_buf_ptr = mov_buf;
1338 const int kSizeOfMove = 7;
1339 #if defined(__default_codegen__)
1340 code = buf = g_malloc (256);
1341 #elif defined(__native_client_codegen__)
1342 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1343 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1344 /* The RIP relative move below is emitted first */
1349 /* FIXME: Optimize this, i.e. use binary search etc. */
1350 /* Maybe move the body into a separate function (slower, but much smaller) */
1352 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1355 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1357 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1360 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1362 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1365 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1366 amd64_jump_code (code, labels [0]);
1369 mono_amd64_patch (labels [2], code);
1370 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1371 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1374 mono_amd64_patch (labels [1], code);
1375 /* Load fail tramp */
1376 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1377 /* Check if there is a fail tramp */
1378 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1380 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1381 /* Jump to fail tramp */
1382 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1385 mono_amd64_patch (labels [3], code);
1386 x86_breakpoint (code);
1388 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1389 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1390 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1391 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1392 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1393 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1395 emit_bytes (acfg, buf, code - buf);
1397 *tramp_size = code - buf + kSizeOfMove;
1398 #if defined(__native_client_codegen__)
1399 /* The tramp will be padded to the next kNaClAlignment bundle. */
1400 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1403 #if defined(__default_codegen__)
1405 #elif defined(__native_client_codegen__)
1409 #elif defined(TARGET_X86)
1411 #ifdef __native_client_codegen__
1414 guint8 *labels [16];
1416 #if defined(__default_codegen__)
1417 code = buf = g_malloc (256);
1418 #elif defined(__native_client_codegen__)
1419 buf_alloc = g_malloc (256 + kNaClAlignment);
1420 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1423 /* Allocate a temporary stack slot */
1424 x86_push_reg (code, X86_EAX);
1426 x86_push_reg (code, X86_EAX);
1428 /* Load mscorlib got address */
1429 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1431 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1434 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1436 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1439 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1441 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1444 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1445 x86_jump_code (code, labels [0]);
1448 mono_x86_patch (labels [2], code);
1449 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1450 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1451 /* Save the target address to the temporary stack location */
1452 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1454 x86_pop_reg (code, X86_EAX);
1455 /* Jump to the target address */
1459 mono_x86_patch (labels [1], code);
1460 /* Load fail tramp */
1461 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1462 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1464 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1465 /* Jump to fail tramp */
1466 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1467 x86_pop_reg (code, X86_EAX);
1471 mono_x86_patch (labels [3], code);
1472 x86_breakpoint (code);
1474 #ifdef __native_client_codegen__
1476 /* emit nops to next 32 byte alignment */
1477 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1478 while (code < (buf + a)) x86_nop(code);
1481 emit_bytes (acfg, buf, code - buf);
1483 *tramp_size = code - buf;
1485 #if defined(__default_codegen__)
1487 #elif defined(__native_client_codegen__)
1491 #elif defined(TARGET_ARM)
1493 guint8 *code, *code2, *labels [16];
1497 /* The IMT method is in v5 */
1499 /* Need at least two free registers, plus a slot for storing the pc */
1500 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1502 /* Load the parameter from the GOT */
1503 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1504 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1507 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1508 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1510 ARM_B_COND (code, ARMCOND_EQ, 0);
1512 /* End-of-loop check */
1513 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1515 ARM_B_COND (code, ARMCOND_EQ, 0);
1518 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1521 arm_patch (labels [4], labels [1]);
1524 arm_patch (labels [2], code);
1525 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1526 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1527 /* Save it to the third stack slot */
1528 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1529 /* Restore the registers and branch */
1530 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1533 arm_patch (labels [3], code);
1534 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1535 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1536 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1540 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1542 emit_bytes (acfg, buf, code - buf);
1543 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1545 *tramp_size = code - buf + 4;
1546 #elif defined(TARGET_POWERPC)
1548 guint8 *code, *labels [16];
1552 /* Load the mscorlib got address */
1553 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1554 /* Load the parameter from the GOT */
1555 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1556 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1558 /* Load and check key */
1560 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1561 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1563 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1565 /* End-of-loop check */
1566 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1568 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1571 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1574 mono_ppc_patch (labels [4], labels [1]);
1577 mono_ppc_patch (labels [2], code);
1578 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1579 /* r11 now contains the value of the vtable slot */
1580 /* this is not a function descriptor on ppc64 */
1581 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1582 ppc_mtctr (code, ppc_r11);
1583 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1586 mono_ppc_patch (labels [3], code);
1590 *tramp_size = code - buf;
1592 emit_bytes (acfg, buf, code - buf);
1594 g_assert_not_reached ();
1599 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1601 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1602 /* Based on code generated by gcc */
1603 img_writer_emit_unset_mode (acfg->w);
1606 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1607 ".section .ctors,\"aw\",@progbits\n"
1611 ".section .opd,\"aw\"\n"
1614 ".long .%s,.TOC.@tocbase32\n"
1617 ".type .%s,@function\n"
1619 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1621 ".section .ctors,\"aw\",@progbits\n"
1625 ".section .opd,\"aw\"\n"
1628 ".long .%1$s,.TOC.@tocbase32\n"
1629 ".size %1$s,.-%1$s\n"
1631 ".type .%1$s,@function\n"
1633 ".%1$s:\n", symbol);
1644 "lis 3, .Lglobals@h\n"
1645 "ori 3, 3, .Lglobals@l\n"
1646 "bl .mono_aot_register_module\n"
1654 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1656 ".size .%s,.-.%s\n", symbol, symbol);
1659 ".size .%1$s,.-.%1$s\n", symbol);
1665 /* END OF ARCH SPECIFIC CODE */
1668 mono_get_field_token (MonoClassField *field)
1670 MonoClass *klass = field->parent;
1673 for (i = 0; i < klass->field.count; ++i) {
1674 if (field == &klass->fields [i])
1675 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1678 g_assert_not_reached ();
1683 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1687 //printf ("ENCODE: %d 0x%x.\n", value, value);
1690 * Same encoding as the one used in the metadata, extended to handle values
1691 * greater than 0x1fffffff.
1693 if ((value >= 0) && (value <= 127))
1695 else if ((value >= 0) && (value <= 16383)) {
1696 p [0] = 0x80 | (value >> 8);
1697 p [1] = value & 0xff;
1699 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1700 p [0] = (value >> 24) | 0xc0;
1701 p [1] = (value >> 16) & 0xff;
1702 p [2] = (value >> 8) & 0xff;
1703 p [3] = value & 0xff;
1708 p [1] = (value >> 24) & 0xff;
1709 p [2] = (value >> 16) & 0xff;
1710 p [3] = (value >> 8) & 0xff;
1711 p [4] = value & 0xff;
1719 stream_init (MonoDynamicStream *sh)
1722 sh->alloc_size = 4096;
1723 sh->data = g_malloc (4096);
1725 /* So offsets are > 0 */
1731 make_room_in_stream (MonoDynamicStream *stream, int size)
1733 if (size <= stream->alloc_size)
1736 while (stream->alloc_size <= size) {
1737 if (stream->alloc_size < 4096)
1738 stream->alloc_size = 4096;
1740 stream->alloc_size *= 2;
1743 stream->data = g_realloc (stream->data, stream->alloc_size);
1747 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1751 make_room_in_stream (stream, stream->index + len);
1752 memcpy (stream->data + stream->index, data, len);
1753 idx = stream->index;
1754 stream->index += len;
1761 * Add data to the binary blob inside the aot image. Returns the offset inside the
1762 * blob where the data was stored.
1765 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1767 if (acfg->blob.alloc_size == 0)
1768 stream_init (&acfg->blob);
1770 return add_stream_data (&acfg->blob, (char*)data, data_len);
1774 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1779 if (acfg->blob.alloc_size == 0)
1780 stream_init (&acfg->blob);
1782 count = acfg->blob.index % align;
1784 /* we assume the stream data will be aligned */
1786 add_stream_data (&acfg->blob, buf, 4 - count);
1788 return add_stream_data (&acfg->blob, (char*)data, data_len);
1792 * emit_offset_table:
1794 * Emit a table of increasing offsets in a compact form using differential encoding.
1795 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1796 * group size, the more compact the table becomes, but the slower it becomes to compute
1797 * a given entry. Returns the size of the table.
1800 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1802 gint32 current_offset;
1803 int i, buf_size, ngroups, index_entry_size;
1805 guint32 *index_offsets;
1807 ngroups = (noffsets + (group_size - 1)) / group_size;
1809 index_offsets = g_new0 (guint32, ngroups);
1811 buf_size = noffsets * 4;
1812 p = buf = g_malloc0 (buf_size);
1815 for (i = 0; i < noffsets; ++i) {
1816 //printf ("D: %d -> %d\n", i, offsets [i]);
1817 if ((i % group_size) == 0) {
1818 index_offsets [i / group_size] = p - buf;
1819 /* Emit the full value for these entries */
1820 encode_value (offsets [i], p, &p);
1822 /* The offsets are allowed to be non-increasing */
1823 //g_assert (offsets [i] >= current_offset);
1824 encode_value (offsets [i] - current_offset, p, &p);
1826 current_offset = offsets [i];
1829 if (ngroups && index_offsets [ngroups - 1] < 65000)
1830 index_entry_size = 2;
1832 index_entry_size = 4;
1834 /* Emit the header */
1835 emit_int32 (acfg, noffsets);
1836 emit_int32 (acfg, group_size);
1837 emit_int32 (acfg, ngroups);
1838 emit_int32 (acfg, index_entry_size);
1840 /* Emit the index */
1841 for (i = 0; i < ngroups; ++i) {
1842 if (index_entry_size == 2)
1843 emit_int16 (acfg, index_offsets [i]);
1845 emit_int32 (acfg, index_offsets [i]);
1849 emit_bytes (acfg, buf, p - buf);
1851 return (int)(p - buf) + (ngroups * 4);
1855 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1859 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1863 index = g_hash_table_size (cfg->image_hash);
1864 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1865 g_ptr_array_add (cfg->image_table, image);
1871 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1874 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1876 /* FIXME: Search referenced images as well */
1877 if (!acfg->typespec_classes) {
1878 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1879 for (i = 0; i < len; ++i) {
1880 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1883 for (i = 0; i < len; ++i) {
1884 if (acfg->typespec_classes [i] == klass)
1889 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1895 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1898 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1901 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1904 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1907 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1912 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1916 if (klass->generic_class) {
1918 g_assert (klass->type_token);
1920 /* Find a typespec for a class if possible */
1921 token = find_typespec_for_class (acfg, klass);
1923 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1924 encode_value (token, p, &p);
1926 MonoClass *gclass = klass->generic_class->container_class;
1927 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1928 static int count = 0;
1931 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1932 encode_klass_ref (acfg, gclass, p, &p);
1933 encode_ginst (acfg, inst, p, &p);
1937 } else if (klass->type_token) {
1938 int iindex = get_image_index (acfg, klass->image);
1940 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1942 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1943 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1945 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1946 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1947 encode_value (get_image_index (acfg, klass->image), p, &p);
1949 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1950 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1951 MonoGenericParam *par = klass->byval_arg.data.generic_param;
1953 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1954 encode_value (klass->byval_arg.type, p, &p);
1955 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1957 encode_value (container ? 1 : 0, p, &p);
1959 encode_value (container->is_method, p, &p);
1960 g_assert (par->serial == 0);
1961 if (container->is_method)
1962 encode_method_ref (acfg, container->owner.method, p, &p);
1964 encode_klass_ref (acfg, container->owner.klass, p, &p);
1966 encode_value (par->serial, p, &p);
1968 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1969 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1970 encode_type (acfg, &klass->byval_arg, p, &p);
1973 g_assert (klass->rank > 0);
1974 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1975 encode_value (klass->rank, p, &p);
1976 encode_klass_ref (acfg, klass->element_class, p, &p);
1984 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1985 * standard metadata encoding.
1988 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1990 gboolean shared = FALSE;
1993 * The encoding of generic instances is large so emit them only once.
1995 if (klass->generic_class) {
1997 g_assert (klass->type_token);
1999 /* Find a typespec for a class if possible */
2000 token = find_typespec_for_class (acfg, klass);
2003 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2008 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2012 buf2 = g_malloc (1024);
2015 encode_klass_ref_inner (acfg, klass, p, &p);
2016 g_assert (p - buf2 < 1024);
2018 offset = add_to_blob (acfg, buf2, p - buf2);
2021 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2027 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2028 encode_value (offset, p, &p);
2033 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2037 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2039 guint32 token = mono_get_field_token (field);
2042 encode_klass_ref (cfg, field->parent, p, &p);
2043 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2044 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2049 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2054 encode_value (inst->type_argc, p, &p);
2055 for (i = 0; i < inst->type_argc; ++i)
2056 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2061 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2064 MonoGenericInst *inst;
2066 inst = context->class_inst;
2068 g_assert (inst->type_argc);
2069 encode_ginst (acfg, inst, p, &p);
2071 encode_value (0, p, &p);
2073 inst = context->method_inst;
2075 g_assert (inst->type_argc);
2076 encode_ginst (acfg, inst, p, &p);
2078 encode_value (0, p, &p);
2084 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2088 g_assert (t->num_mods == 0);
2089 /* t->attrs can be ignored */
2090 //g_assert (t->attrs == 0);
2093 *p = MONO_TYPE_PINNED;
2097 *p = MONO_TYPE_BYREF;
2105 case MONO_TYPE_VOID:
2106 case MONO_TYPE_BOOLEAN:
2107 case MONO_TYPE_CHAR:
2120 case MONO_TYPE_STRING:
2121 case MONO_TYPE_OBJECT:
2122 case MONO_TYPE_TYPEDBYREF:
2124 case MONO_TYPE_VALUETYPE:
2125 case MONO_TYPE_CLASS:
2126 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2128 case MONO_TYPE_SZARRAY:
2129 encode_klass_ref (acfg, t->data.klass, p, &p);
2132 encode_type (acfg, t->data.type, p, &p);
2134 case MONO_TYPE_GENERICINST: {
2135 MonoClass *gclass = t->data.generic_class->container_class;
2136 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2138 encode_klass_ref (acfg, gclass, p, &p);
2139 encode_ginst (acfg, inst, p, &p);
2142 case MONO_TYPE_ARRAY: {
2143 MonoArrayType *array = t->data.array;
2146 encode_klass_ref (acfg, array->eklass, p, &p);
2147 encode_value (array->rank, p, &p);
2148 encode_value (array->numsizes, p, &p);
2149 for (i = 0; i < array->numsizes; ++i)
2150 encode_value (array->sizes [i], p, &p);
2151 encode_value (array->numlobounds, p, &p);
2152 for (i = 0; i < array->numlobounds; ++i)
2153 encode_value (array->lobounds [i], p, &p);
2157 g_assert_not_reached ();
2164 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2170 /* Similar to the metadata encoding */
2171 if (sig->generic_param_count)
2175 if (sig->explicit_this)
2177 flags |= (sig->call_convention & 0x0F);
2181 if (sig->generic_param_count)
2182 encode_value (sig->generic_param_count, p, &p);
2183 encode_value (sig->param_count, p, &p);
2185 encode_type (acfg, sig->ret, p, &p);
2186 for (i = 0; i < sig->param_count; ++i) {
2187 if (sig->sentinelpos == i) {
2188 *p = MONO_TYPE_SENTINEL;
2191 encode_type (acfg, sig->params [i], p, &p);
2197 #define MAX_IMAGE_INDEX 250
2200 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2202 guint32 image_index = get_image_index (acfg, method->klass->image);
2203 guint32 token = method->token;
2204 MonoJumpInfoToken *ji;
2208 * The encoding for most methods is as follows:
2209 * - image index encoded as a leb128
2210 * - token index encoded as a leb128
2211 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2212 * types of method encodings.
2215 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2217 /* Mark methods which can't use aot trampolines because they need the further
2218 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2220 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2221 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2222 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2224 if (method->wrapper_type) {
2225 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2227 encode_value (method->wrapper_type, p, &p);
2229 switch (method->wrapper_type) {
2230 case MONO_WRAPPER_REMOTING_INVOKE:
2231 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2232 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2235 m = mono_marshal_method_from_wrapper (method);
2237 encode_method_ref (acfg, m, p, &p);
2240 case MONO_WRAPPER_PROXY_ISINST:
2241 case MONO_WRAPPER_LDFLD:
2242 case MONO_WRAPPER_LDFLDA:
2243 case MONO_WRAPPER_STFLD:
2244 case MONO_WRAPPER_ISINST: {
2245 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2246 encode_klass_ref (acfg, proxy_class, p, &p);
2249 case MONO_WRAPPER_LDFLD_REMOTE:
2250 case MONO_WRAPPER_STFLD_REMOTE:
2252 case MONO_WRAPPER_ALLOC: {
2253 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2255 /* The GC name is saved once in MonoAotFileInfo */
2256 g_assert (info->alloc_type != -1);
2257 encode_value (info->alloc_type, p, &p);
2260 case MONO_WRAPPER_WRITE_BARRIER:
2262 case MONO_WRAPPER_STELEMREF: {
2263 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2266 encode_value (info->subtype, p, &p);
2267 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2268 encode_value (info->d.virtual_stelemref.kind, p, &p);
2271 case MONO_WRAPPER_UNKNOWN: {
2272 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2275 encode_value (info->subtype, p, &p);
2276 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2277 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2278 encode_klass_ref (acfg, method->klass, p, &p);
2279 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2280 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2283 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2284 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2287 encode_value (info->subtype, p, &p);
2288 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2289 strcpy ((char*)p, method->name);
2290 p += strlen (method->name) + 1;
2291 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2292 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2294 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2295 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2299 case MONO_WRAPPER_SYNCHRONIZED: {
2302 m = mono_marshal_method_from_wrapper (method);
2304 g_assert (m != method);
2305 encode_method_ref (acfg, m, p, &p);
2308 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2309 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2312 encode_value (info->subtype, p, &p);
2314 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2315 encode_value (info->d.element_addr.rank, p, &p);
2316 encode_value (info->d.element_addr.elem_size, p, &p);
2317 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2318 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2320 g_assert_not_reached ();
2324 case MONO_WRAPPER_CASTCLASS: {
2325 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2328 encode_value (info->subtype, p, &p);
2331 case MONO_WRAPPER_RUNTIME_INVOKE: {
2332 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2335 encode_value (info->subtype, p, &p);
2336 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2337 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2339 MonoMethodSignature *sig;
2341 encode_value (0, p, &p);
2343 sig = mono_method_signature (method);
2344 encode_signature (acfg, sig, p, &p);
2348 case MONO_WRAPPER_DELEGATE_INVOKE:
2349 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2350 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2351 MonoMethodSignature *sig = mono_method_signature (method);
2352 encode_signature (acfg, sig, p, &p);
2355 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2356 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2359 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2360 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2364 g_assert_not_reached ();
2366 } else if (mono_method_signature (method)->is_inflated) {
2368 * This is a generic method, find the original token which referenced it and
2370 * Obtain the token from information recorded by the JIT.
2372 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2374 image_index = get_image_index (acfg, ji->image);
2375 g_assert (image_index < MAX_IMAGE_INDEX);
2378 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2379 encode_value (image_index, p, &p);
2380 encode_value (token, p, &p);
2382 MonoMethod *declaring;
2383 MonoGenericContext *context = mono_method_get_context (method);
2385 g_assert (method->is_inflated);
2386 declaring = ((MonoMethodInflated*)method)->declaring;
2389 * This might be a non-generic method of a generic instance, which
2390 * doesn't have a token since the reference is generated by the JIT
2391 * like Nullable:Box/Unbox, or by generic sharing.
2394 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2395 /* Encode the klass */
2396 encode_klass_ref (acfg, method->klass, p, &p);
2397 /* Encode the method */
2398 image_index = get_image_index (acfg, method->klass->image);
2399 g_assert (image_index < MAX_IMAGE_INDEX);
2400 g_assert (declaring->token);
2401 token = declaring->token;
2402 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2403 encode_value (image_index, p, &p);
2404 encode_value (token, p, &p);
2405 encode_generic_context (acfg, context, p, &p);
2407 } else if (token == 0) {
2408 /* This might be a method of a constructed type like int[,].Set */
2409 /* Obtain the token from information recorded by the JIT */
2410 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2412 image_index = get_image_index (acfg, ji->image);
2413 g_assert (image_index < MAX_IMAGE_INDEX);
2416 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2417 encode_value (image_index, p, &p);
2418 encode_value (token, p, &p);
2421 g_assert (method->klass->rank);
2423 /* Encode directly */
2424 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2425 encode_klass_ref (acfg, method->klass, p, &p);
2426 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2427 encode_value (0, p, &p);
2428 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2429 encode_value (1, p, &p);
2430 else if (!strcmp (method->name, "Get"))
2431 encode_value (2, p, &p);
2432 else if (!strcmp (method->name, "Address"))
2433 encode_value (3, p, &p);
2434 else if (!strcmp (method->name, "Set"))
2435 encode_value (4, p, &p);
2437 g_assert_not_reached ();
2440 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2441 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2447 compare_patches (gconstpointer a, gconstpointer b)
2451 i = (*(MonoJumpInfo**)a)->ip.i;
2452 j = (*(MonoJumpInfo**)b)->ip.i;
2463 static G_GNUC_UNUSED char*
2464 patch_to_string (MonoJumpInfo *patch_info)
2468 str = g_string_new ("");
2470 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2472 switch (patch_info->type) {
2473 case MONO_PATCH_INFO_VTABLE:
2474 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2479 g_string_append_printf (str, ")");
2480 return g_string_free (str, FALSE);
2486 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2489 static inline gboolean
2490 is_plt_patch (MonoJumpInfo *patch_info)
2492 switch (patch_info->type) {
2493 case MONO_PATCH_INFO_METHOD:
2494 case MONO_PATCH_INFO_INTERNAL_METHOD:
2495 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2496 case MONO_PATCH_INFO_ICALL_ADDR:
2497 case MONO_PATCH_INFO_CLASS_INIT:
2498 case MONO_PATCH_INFO_RGCTX_FETCH:
2499 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2500 case MONO_PATCH_INFO_MONITOR_ENTER:
2501 case MONO_PATCH_INFO_MONITOR_EXIT:
2502 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2512 * Return the symbol identifying the plt entry PLT_OFFSET.
2515 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2519 * The Apple linker reorganizes object files, so it doesn't like branches to local
2520 * labels, since those have no relocations.
2522 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2524 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2531 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2533 static MonoPltEntry*
2534 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2538 if (!is_plt_patch (patch_info))
2541 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2543 // FIXME: This breaks the calculation of final_got_size
2544 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2546 * Allocate a separate PLT slot for each such patch, since some plt
2547 * entries will refer to the method itself, and some will refer to the
2554 MonoJumpInfo *new_ji;
2556 g_assert (!acfg->final_got_size);
2558 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2560 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2561 res->plt_offset = acfg->plt_offset;
2563 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2564 if (acfg->aot_opts.write_symbols)
2565 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2567 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2569 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2571 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2573 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2575 acfg->plt_offset ++;
2584 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2585 * JI could be found if it exists, otherwise allocates a new one.
2588 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2592 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2594 return got_offset - 1;
2596 got_offset = acfg->got_offset;
2597 acfg->got_offset ++;
2599 if (acfg->final_got_size)
2600 g_assert (got_offset < acfg->final_got_size);
2602 acfg->stats.got_slots ++;
2603 acfg->stats.got_slot_types [ji->type] ++;
2605 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2606 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2607 g_ptr_array_add (acfg->got_patches, ji);
2612 /* Add a method to the list of methods which need to be emitted */
2614 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2617 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2618 g_ptr_array_add (acfg->methods, method);
2619 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2620 acfg->nmethods = acfg->methods->len + 1;
2623 if (method->wrapper_type || extra)
2624 g_ptr_array_add (acfg->extra_methods, method);
2628 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2630 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2638 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2642 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2646 index = acfg->method_index;
2647 add_method_with_index (acfg, method, index, extra);
2649 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2651 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2653 acfg->method_index ++;
2659 add_method (MonoAotCompile *acfg, MonoMethod *method)
2661 return add_method_full (acfg, method, FALSE, 0);
2665 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2667 add_method_full (acfg, method, TRUE, 0);
2671 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2673 if (acfg->aot_opts.log_generics)
2674 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2676 add_method_full (acfg, method, TRUE, depth);
2680 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2682 MonoAotCompile *acfg = user_data;
2683 MonoJitICallInfo *callinfo = value;
2684 MonoMethod *wrapper;
2690 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2691 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2694 add_method (acfg, wrapper);
2698 get_runtime_invoke_sig (MonoMethodSignature *sig)
2700 MonoMethodBuilder *mb;
2703 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2704 m = mono_mb_create_method (mb, sig, 16);
2705 return mono_marshal_get_runtime_invoke (m, FALSE);
2709 can_marshal_struct (MonoClass *klass)
2711 MonoClassField *field;
2712 gboolean can_marshal = TRUE;
2713 gpointer iter = NULL;
2715 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2718 /* Only allow a few field types to avoid asserts in the marshalling code */
2719 while ((field = mono_class_get_fields (klass, &iter))) {
2720 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2723 switch (field->type->type) {
2728 case MONO_TYPE_BOOLEAN:
2731 case MONO_TYPE_CHAR:
2739 case MONO_TYPE_STRING:
2741 case MONO_TYPE_VALUETYPE:
2742 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2743 can_marshal = FALSE;
2746 can_marshal = FALSE;
2752 /* Its hard to compute whenever these can be marshalled or not */
2753 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
2760 add_wrappers (MonoAotCompile *acfg)
2762 MonoMethod *method, *m;
2764 MonoMethodSignature *sig, *csig;
2768 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2769 * so there is only one wrapper of a given type, or inlining their contents into their
2774 * FIXME: This depends on the fact that different wrappers have different
2778 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2780 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2781 gboolean skip = FALSE;
2783 method = mono_get_method (acfg->image, token, NULL);
2785 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2786 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2787 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2790 if (method->is_generic || method->klass->generic_container)
2793 /* Skip methods which can not be handled by get_runtime_invoke () */
2794 sig = mono_method_signature (method);
2797 if ((sig->ret->type == MONO_TYPE_PTR) ||
2798 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2801 for (j = 0; j < sig->param_count; j++) {
2802 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2806 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2807 if (!method->klass->contextbound) {
2808 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2809 gboolean has_nullable = FALSE;
2811 for (j = 0; j < sig->param_count; j++) {
2812 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2813 has_nullable = TRUE;
2816 if (info && !has_nullable) {
2817 /* Supported by the dynamic runtime-invoke wrapper */
2825 //printf ("%s\n", mono_method_full_name (method, TRUE));
2826 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2830 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2831 #ifdef MONO_ARCH_HAVE_TLS_GET
2832 MonoMethodDesc *desc;
2833 MonoMethod *orig_method;
2837 /* Runtime invoke wrappers */
2839 /* void runtime-invoke () [.cctor] */
2840 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2841 csig->ret = &mono_defaults.void_class->byval_arg;
2842 add_method (acfg, get_runtime_invoke_sig (csig));
2844 /* void runtime-invoke () [Finalize] */
2845 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2847 csig->ret = &mono_defaults.void_class->byval_arg;
2848 add_method (acfg, get_runtime_invoke_sig (csig));
2850 /* void runtime-invoke (string) [exception ctor] */
2851 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2853 csig->ret = &mono_defaults.void_class->byval_arg;
2854 csig->params [0] = &mono_defaults.string_class->byval_arg;
2855 add_method (acfg, get_runtime_invoke_sig (csig));
2857 /* void runtime-invoke (string, string) [exception ctor] */
2858 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2860 csig->ret = &mono_defaults.void_class->byval_arg;
2861 csig->params [0] = &mono_defaults.string_class->byval_arg;
2862 csig->params [1] = &mono_defaults.string_class->byval_arg;
2863 add_method (acfg, get_runtime_invoke_sig (csig));
2865 /* string runtime-invoke () [Exception.ToString ()] */
2866 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2868 csig->ret = &mono_defaults.string_class->byval_arg;
2869 add_method (acfg, get_runtime_invoke_sig (csig));
2871 /* void runtime-invoke (string, Exception) [exception ctor] */
2872 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2874 csig->ret = &mono_defaults.void_class->byval_arg;
2875 csig->params [0] = &mono_defaults.string_class->byval_arg;
2876 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2877 add_method (acfg, get_runtime_invoke_sig (csig));
2879 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2880 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2882 csig->ret = &(mono_class_from_name (
2883 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2884 csig->params [0] = &mono_defaults.string_class->byval_arg;
2885 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2886 add_method (acfg, get_runtime_invoke_sig (csig));
2888 /* runtime-invoke used by finalizers */
2889 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2891 /* This is used by mono_runtime_capture_context () */
2892 method = mono_get_context_capture_method ();
2894 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2896 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2897 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2900 /* JIT icall wrappers */
2901 /* FIXME: locking */
2902 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2905 add_method (acfg, mono_marshal_get_stelemref ());
2907 #ifdef MONO_ARCH_HAVE_TLS_GET
2908 /* Managed Allocators */
2909 nallocators = mono_gc_get_managed_allocator_types ();
2910 for (i = 0; i < nallocators; ++i) {
2911 m = mono_gc_get_managed_allocator_by_type (i);
2913 add_method (acfg, m);
2916 /* Monitor Enter/Exit */
2917 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2918 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2919 /* This is a v4 method */
2921 method = mono_monitor_get_fast_path (orig_method);
2923 add_method (acfg, method);
2925 mono_method_desc_free (desc);
2927 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2928 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2929 g_assert (orig_method);
2930 mono_method_desc_free (desc);
2931 method = mono_monitor_get_fast_path (orig_method);
2933 add_method (acfg, method);
2936 /* Stelemref wrappers */
2937 /* There is only a constant number of these, iterating over all types should handle them all */
2938 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2941 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2942 klass = mono_class_get (acfg->image, token);
2944 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2946 mono_loader_clear_error ();
2949 /* castclass_with_check wrapper */
2950 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2951 /* isinst_with_check wrapper */
2952 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2954 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2956 MonoMethodDesc *desc;
2959 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2960 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2961 mono_method_desc_free (desc);
2963 m = mono_monitor_get_fast_path (m);
2965 add_method (acfg, m);
2972 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2973 * we use the original method instead at runtime.
2974 * Since full-aot doesn't support remoting, this is not a problem.
2977 /* remoting-invoke wrappers */
2978 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2979 MonoMethodSignature *sig;
2981 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2982 method = mono_get_method (acfg->image, token, NULL);
2984 sig = mono_method_signature (method);
2986 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2987 m = mono_marshal_get_remoting_invoke_with_check (method);
2989 add_method (acfg, m);
2994 /* delegate-invoke wrappers */
2995 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2997 MonoCustomAttrInfo *cattr;
2999 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3000 klass = mono_class_get (acfg->image, token);
3003 mono_loader_clear_error ();
3007 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
3008 method = mono_get_delegate_invoke (klass);
3010 m = mono_marshal_get_delegate_invoke (method, NULL);
3012 add_method (acfg, m);
3014 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3016 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3018 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3020 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3022 cattr = mono_custom_attrs_from_class (klass);
3027 for (j = 0; j < cattr->num_attrs; ++j)
3028 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3030 if (j < cattr->num_attrs)
3031 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3036 /* Synchronized wrappers */
3037 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3038 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3039 method = mono_get_method (acfg->image, token, NULL);
3041 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3042 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3045 /* pinvoke wrappers */
3046 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3048 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3050 method = mono_get_method (acfg->image, token, NULL);
3052 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3053 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3054 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3058 /* native-to-managed wrappers */
3059 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3061 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3062 MonoCustomAttrInfo *cattr;
3065 method = mono_get_method (acfg->image, token, NULL);
3068 * Only generate native-to-managed wrappers for methods which have an
3069 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3070 * name to avoid defining a new assembly to contain it.
3072 cattr = mono_custom_attrs_from_method (method);
3075 for (j = 0; j < cattr->num_attrs; ++j)
3076 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3078 if (j < cattr->num_attrs) {
3079 MonoCustomAttrEntry *e = &cattr->attrs [j];
3080 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3081 const char *p = (const char*)e->data;
3083 int slen, num_named, named_type, data_type;
3087 char *export_name = NULL;
3088 MonoMethod *wrapper;
3090 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3091 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3092 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3093 mono_method_full_name (method, TRUE));
3097 g_assert (sig->param_count == 1);
3098 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3101 * Decode the cattr manually since we can't create objects
3102 * during aot compilation.
3108 /* From load_cattr_value () in reflection.c */
3109 slen = mono_metadata_decode_value (p, &p);
3110 n = g_memdup (p, slen + 1);
3112 t = mono_reflection_type_from_name (n, acfg->image);
3116 klass = mono_class_from_mono_type (t);
3117 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3121 num_named = read16 (p);
3124 g_assert (num_named < 2);
3125 if (num_named == 1) {
3128 MonoType *prop_type;
3130 /* parse ExportSymbol attribute */
3132 named_type = *named;
3137 name_len = mono_metadata_decode_blob_size (named, &named);
3138 name = g_malloc (name_len + 1);
3139 memcpy (name, named, name_len);
3140 name [name_len] = 0;
3143 g_assert (named_type == 0x54);
3144 g_assert (!strcmp (name, "ExportSymbol"));
3146 prop_type = &mono_defaults.string_class->byval_arg;
3148 /* load_cattr_value (), string case */
3149 g_assert (*named != (char)0xff);
3150 slen = mono_metadata_decode_value (named, &named);
3151 export_name = g_malloc (slen + 1);
3152 memcpy (export_name, named, slen);
3153 export_name [slen] = 0;
3157 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3158 add_method (acfg, wrapper);
3160 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3164 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3165 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3166 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3170 /* StructureToPtr/PtrToStructure wrappers */
3171 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3174 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3175 klass = mono_class_get (acfg->image, token);
3178 mono_loader_clear_error ();
3182 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3183 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3184 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3190 has_type_vars (MonoClass *klass)
3192 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3195 return has_type_vars (klass->element_class);
3196 if (klass->generic_class) {
3197 MonoGenericContext *context = &klass->generic_class->context;
3198 if (context->class_inst) {
3201 for (i = 0; i < context->class_inst->type_argc; ++i)
3202 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3210 method_has_type_vars (MonoMethod *method)
3212 if (has_type_vars (method->klass))
3215 if (method->is_inflated) {
3216 MonoGenericContext *context = mono_method_get_context (method);
3217 if (context->method_inst) {
3220 for (i = 0; i < context->method_inst->type_argc; ++i)
3221 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3228 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3231 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3233 /* This might lead to a huge code blowup so only do it if neccesary */
3234 if (!acfg->aot_opts.full_aot && !force)
3237 add_generic_class_with_depth (acfg, klass, 0, ref);
3241 check_type_depth (MonoType *t, int depth)
3249 case MONO_TYPE_GENERICINST: {
3250 MonoGenericClass *gklass = t->data.generic_class;
3251 MonoGenericInst *ginst = gklass->context.class_inst;
3254 for (i = 0; i < ginst->type_argc; ++i) {
3255 if (check_type_depth (ginst->type_argv [i], depth + 1))
3269 * add_generic_class:
3271 * Add all methods of a generic class.
3274 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3277 MonoClassField *field;
3280 if (!acfg->ginst_hash)
3281 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3283 mono_class_init (klass);
3285 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3288 if (has_type_vars (klass))
3291 if (!klass->generic_class && !klass->rank)
3294 if (!acfg->ginst_hash)
3295 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3297 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3300 if (check_type_depth (&klass->byval_arg, 0))
3303 if (acfg->aot_opts.log_generics)
3304 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3306 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3309 while ((method = mono_class_get_methods (klass, &iter))) {
3310 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3314 if (method->is_generic)
3319 * FIXME: Instances which are referenced by these methods are not added,
3320 * for example Array.Resize<int> for List<int>.Add ().
3322 add_extra_method_with_depth (acfg, method, depth + 1);
3326 while ((field = mono_class_get_fields (klass, &iter))) {
3327 if (field->type->type == MONO_TYPE_GENERICINST)
3328 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3331 if (klass->delegate) {
3332 method = mono_get_delegate_invoke (klass);
3334 method = mono_marshal_get_delegate_invoke (method, NULL);
3336 if (acfg->aot_opts.log_generics)
3337 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3339 add_method (acfg, method);
3342 /* Add superclasses */
3344 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3347 * For ICollection<T>, add instances of the helper methods
3348 * in Array, since a T[] could be cast to ICollection<T>.
3350 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3351 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3352 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3353 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3357 if (!strcmp (klass->name, "IEnumerator`1"))
3358 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3360 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3362 /* Add the T[]/InternalEnumerator class */
3363 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3367 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3368 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3372 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3373 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3377 while ((method = mono_class_get_methods (array_class, &iter))) {
3378 if (strstr (method->name, name_prefix)) {
3379 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3381 add_extra_method_with_depth (acfg, m, depth);
3385 g_free (name_prefix);
3388 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3389 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3390 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3391 MonoClass *icomparable, *gcomparer;
3392 MonoGenericContext ctx;
3393 MonoType *args [16];
3395 memset (&ctx, 0, sizeof (ctx));
3397 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3398 g_assert (icomparable);
3399 args [0] = &tclass->byval_arg;
3400 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3402 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3403 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3404 g_assert (gcomparer);
3405 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3409 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3410 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3411 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3412 MonoClass *iface, *gcomparer;
3413 MonoGenericContext ctx;
3414 MonoType *args [16];
3416 memset (&ctx, 0, sizeof (ctx));
3418 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3420 args [0] = &tclass->byval_arg;
3421 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3423 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3424 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3425 g_assert (gcomparer);
3426 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3432 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3435 MonoGenericContext ctx;
3436 MonoType *args [16];
3438 memset (&ctx, 0, sizeof (ctx));
3440 for (i = 0; i < ninsts; ++i) {
3441 args [0] = insts [i];
3442 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3443 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3448 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3450 MonoMethodHeader *header;
3451 MonoMethodSignature *sig;
3454 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3456 sig = mono_method_signature (method);
3459 for (j = 0; j < sig->param_count; ++j)
3460 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3461 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3464 header = mono_method_get_header (method);
3467 for (j = 0; j < header->num_locals; ++j)
3468 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3469 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3474 * add_generic_instances:
3476 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3479 add_generic_instances (MonoAotCompile *acfg)
3484 MonoGenericContext *context;
3486 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3487 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3488 method = mono_get_method (acfg->image, token, NULL);
3493 if (method->klass->image != acfg->image)
3496 context = mono_method_get_context (method);
3498 if (context && ((context->class_inst && context->class_inst->is_open)))
3502 * For open methods, create an instantiation which can be passed to the JIT.
3503 * FIXME: Handle class_inst as well.
3505 if (context && context->method_inst && context->method_inst->is_open) {
3506 MonoGenericContext shared_context;
3507 MonoGenericInst *inst;
3508 MonoType **type_argv;
3510 MonoMethod *declaring_method;
3511 gboolean supported = TRUE;
3513 /* Check that the context doesn't contain open constructed types */
3514 if (context->class_inst) {
3515 inst = context->class_inst;
3516 for (i = 0; i < inst->type_argc; ++i) {
3517 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)
3519 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3523 if (context->method_inst) {
3524 inst = context->method_inst;
3525 for (i = 0; i < inst->type_argc; ++i) {
3526 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)
3528 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3536 memset (&shared_context, 0, sizeof (MonoGenericContext));
3538 inst = context->class_inst;
3540 type_argv = g_new0 (MonoType*, inst->type_argc);
3541 for (i = 0; i < inst->type_argc; ++i) {
3542 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)
3543 type_argv [i] = &mono_defaults.object_class->byval_arg;
3545 type_argv [i] = inst->type_argv [i];
3548 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3552 inst = context->method_inst;
3554 type_argv = g_new0 (MonoType*, inst->type_argc);
3555 for (i = 0; i < inst->type_argc; ++i) {
3556 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)
3557 type_argv [i] = &mono_defaults.object_class->byval_arg;
3559 type_argv [i] = inst->type_argv [i];
3562 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3566 if (method->is_generic || method->klass->generic_container)
3567 declaring_method = method;
3569 declaring_method = mono_method_get_declaring_generic_method (method);
3571 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3575 * If the method is fully sharable, it was already added in place of its
3576 * generic definition.
3578 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3582 * FIXME: Partially shared methods are not shared here, so we end up with
3583 * many identical methods.
3585 add_extra_method (acfg, method);
3588 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3591 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3593 klass = mono_class_get (acfg->image, token);
3594 if (!klass || klass->rank) {
3595 mono_loader_clear_error ();
3599 add_generic_class (acfg, klass, FALSE, "typespec");
3602 /* Add types of args/locals */
3603 for (i = 0; i < acfg->methods->len; ++i) {
3604 method = g_ptr_array_index (acfg->methods, i);
3605 add_types_from_method_header (acfg, method);
3608 if (acfg->image == mono_defaults.corlib) {
3610 MonoType *insts [256];
3613 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3614 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3615 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3616 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3617 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3618 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3619 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3620 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3621 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3622 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3623 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3624 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3626 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3627 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3629 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3630 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3632 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3634 /* Add instances of the array generic interfaces for primitive types */
3635 /* This will add instances of the InternalArray_ helper methods in Array too */
3636 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3638 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3639 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3641 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3642 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3644 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3647 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3648 * used for all instances of GetGenericValueImpl by the AOT runtime.
3651 MonoGenericContext ctx;
3652 MonoType *args [16];
3653 MonoMethod *get_method;
3654 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3656 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3659 memset (&ctx, 0, sizeof (ctx));
3660 args [0] = &mono_defaults.object_class->byval_arg;
3661 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3662 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3666 /* Same for CompareExchange<T>/Exchange<T> */
3668 MonoGenericContext ctx;
3669 MonoType *args [16];
3671 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3672 gpointer iter = NULL;
3674 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3675 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3676 memset (&ctx, 0, sizeof (ctx));
3677 args [0] = &mono_defaults.object_class->byval_arg;
3678 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3679 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3687 * is_direct_callable:
3689 * Return whenever the method identified by JI is directly callable without
3690 * going through the PLT.
3693 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3695 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3696 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3698 gboolean direct_callable = TRUE;
3700 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3701 direct_callable = FALSE;
3702 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3703 // FIXME: Maybe call the wrapper directly ?
3704 direct_callable = FALSE;
3706 if (acfg->aot_opts.soft_debug) {
3707 /* Disable this so all calls go through load_method (), see the
3708 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
3709 * mono_debugger_agent_init ().
3711 direct_callable = FALSE;
3714 if (direct_callable)
3717 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3718 if (acfg->aot_opts.direct_pinvoke)
3720 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3721 if (acfg->aot_opts.direct_icalls)
3730 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3732 MonoImage *image = method->klass->image;
3733 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3734 MonoTableInfo *tables = image->tables;
3735 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3736 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3737 guint32 im_cols [MONO_IMPLMAP_SIZE];
3740 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3744 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3747 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3749 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3752 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3754 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3760 * emit_and_reloc_code:
3762 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3763 * is true, calls are made through the GOT too. This is used for emitting trampolines
3764 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3765 * since trampolines are needed to make PTL work.
3768 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3770 int i, pindex, start_index, method_index;
3772 MonoJumpInfo *patch_info;
3773 MonoMethodHeader *header;
3774 gboolean skip, direct_call;
3776 char direct_call_target [1024];
3777 const char *direct_pinvoke;
3780 header = mono_method_get_header (method);
3782 method_index = get_method_index (acfg, method);
3785 /* Collect and sort relocations */
3786 patches = g_ptr_array_new ();
3787 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3788 g_ptr_array_add (patches, patch_info);
3789 g_ptr_array_sort (patches, compare_patches);
3792 for (i = 0; i < code_len; i++) {
3794 for (pindex = start_index; pindex < patches->len; ++pindex) {
3795 patch_info = g_ptr_array_index (patches, pindex);
3796 if (patch_info->ip.i >= i)
3800 #ifdef MONO_ARCH_AOT_SUPPORTED
3802 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3803 start_index = pindex;
3805 switch (patch_info->type) {
3806 case MONO_PATCH_INFO_NONE:
3808 case MONO_PATCH_INFO_GOT_OFFSET: {
3811 arch_emit_got_offset (acfg, code + i, &code_size);
3814 patch_info->type = MONO_PATCH_INFO_NONE;
3819 * If this patch is a call, try emitting a direct call instead of
3820 * through a PLT entry. This is possible if the called method is in
3821 * the same assembly and requires no initialization.
3823 direct_call = FALSE;
3824 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3825 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3826 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3827 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3829 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3830 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3833 acfg->stats.all_calls ++;
3834 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3835 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3836 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
3837 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
3839 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3840 if (direct_pinvoke) {
3842 #if defined(TARGET_MACH)
3848 g_assert (strlen (direct_pinvoke) < 1000);
3849 sprintf (direct_call_target, "%s%s", prefix, direct_pinvoke);
3855 patch_info->type = MONO_PATCH_INFO_NONE;
3856 acfg->stats.direct_calls ++;
3859 if (!got_only && !direct_call) {
3860 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3862 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3864 sprintf (direct_call_target, "%s", plt_entry->symbol);
3866 /* Nullify the patch */
3867 patch_info->type = MONO_PATCH_INFO_NONE;
3868 plt_entry->jit_used = TRUE;
3875 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3880 got_slot = get_got_offset (acfg, patch_info);
3882 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3889 #endif /* MONO_ARCH_AOT_SUPPORTED */
3892 /* Find next patch */
3894 for (pindex = start_index; pindex < patches->len; ++pindex) {
3895 patch_info = g_ptr_array_index (patches, pindex);
3896 if (patch_info->ip.i >= i)
3900 /* Try to emit multiple bytes at once */
3901 if (pindex < patches->len && patch_info->ip.i > i) {
3902 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3903 i = patch_info->ip.i - 1;
3905 emit_bytes (acfg, code + i, 1);
3914 * Modify SYMBOL so it only includes characters permissible in symbols.
3917 sanitize_symbol (char *symbol)
3919 int i, len = strlen (symbol);
3921 for (i = 0; i < len; ++i)
3922 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3927 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3929 char *name1, *name2, *cached;
3930 int i, j, len, count;
3932 name1 = mono_method_full_name (method, TRUE);
3933 len = strlen (name1);
3934 name2 = malloc (strlen (prefix) + len + 16);
3935 memcpy (name2, prefix, strlen (prefix));
3936 j = strlen (prefix);
3937 for (i = 0; i < len; ++i) {
3938 if (isalnum (name1 [i])) {
3939 name2 [j ++] = name1 [i];
3940 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3942 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3945 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3954 while (g_hash_table_lookup (cache, name2)) {
3955 sprintf (name2 + j, "_%d", count);
3959 cached = g_strdup (name2);
3960 g_hash_table_insert (cache, cached, cached);
3966 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3971 char *debug_sym = NULL;
3973 int func_alignment = AOT_FUNC_ALIGNMENT;
3974 MonoMethodHeader *header;
3977 method = cfg->orig_method;
3978 code = cfg->native_code;
3979 header = cfg->header;
3981 method_index = get_method_index (acfg, method);
3983 /* Make the labels local */
3984 sprintf (symbol, "%s", cfg->asm_symbol);
3986 emit_section_change (acfg, ".text", 0);
3987 emit_alignment (acfg, func_alignment);
3988 emit_label (acfg, symbol);
3990 if (acfg->aot_opts.write_symbols) {
3992 * Write a C style symbol for every method, this has two uses:
3993 * - it works on platforms where the dwarf debugging info is not
3995 * - it allows the setting of breakpoints of aot-ed methods.
3997 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3999 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
4000 if (acfg->need_no_dead_strip)
4001 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4002 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4003 emit_label (acfg, debug_sym);
4006 export_name = g_hash_table_lookup (acfg->export_names, method);
4008 /* Emit a global symbol for the method */
4009 emit_global_inner (acfg, export_name, TRUE);
4010 emit_label (acfg, export_name);
4013 if (cfg->verbose_level > 0)
4014 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
4016 acfg->stats.code_size += cfg->code_len;
4018 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4020 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
4024 if (acfg->aot_opts.write_symbols) {
4025 emit_symbol_size (acfg, debug_sym, ".");
4029 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
4030 emit_label (acfg, symbol);
4036 * Encode PATCH_INFO into its disk representation.
4039 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4043 switch (patch_info->type) {
4044 case MONO_PATCH_INFO_NONE:
4046 case MONO_PATCH_INFO_IMAGE:
4047 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4049 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4050 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4051 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4053 case MONO_PATCH_INFO_METHOD_REL:
4054 encode_value ((gint)patch_info->data.offset, p, &p);
4056 case MONO_PATCH_INFO_SWITCH: {
4057 gpointer *table = (gpointer *)patch_info->data.table->table;
4060 encode_value (patch_info->data.table->table_size, p, &p);
4061 for (k = 0; k < patch_info->data.table->table_size; k++)
4062 encode_value ((int)(gssize)table [k], p, &p);
4065 case MONO_PATCH_INFO_METHODCONST:
4066 case MONO_PATCH_INFO_METHOD:
4067 case MONO_PATCH_INFO_METHOD_JUMP:
4068 case MONO_PATCH_INFO_ICALL_ADDR:
4069 case MONO_PATCH_INFO_METHOD_RGCTX:
4070 encode_method_ref (acfg, patch_info->data.method, p, &p);
4072 case MONO_PATCH_INFO_INTERNAL_METHOD:
4073 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4074 guint32 len = strlen (patch_info->data.name);
4076 encode_value (len, p, &p);
4078 memcpy (p, patch_info->data.name, len);
4083 case MONO_PATCH_INFO_LDSTR: {
4084 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4085 guint32 token = patch_info->data.token->token;
4086 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4087 encode_value (image_index, p, &p);
4088 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4091 case MONO_PATCH_INFO_RVA:
4092 case MONO_PATCH_INFO_DECLSEC:
4093 case MONO_PATCH_INFO_LDTOKEN:
4094 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4095 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4096 encode_value (patch_info->data.token->token, p, &p);
4097 encode_value (patch_info->data.token->has_context, p, &p);
4098 if (patch_info->data.token->has_context)
4099 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4101 case MONO_PATCH_INFO_EXC_NAME: {
4102 MonoClass *ex_class;
4105 mono_class_from_name (mono_defaults.exception_class->image,
4106 "System", patch_info->data.target);
4107 g_assert (ex_class);
4108 encode_klass_ref (acfg, ex_class, p, &p);
4111 case MONO_PATCH_INFO_R4:
4112 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4114 case MONO_PATCH_INFO_R8:
4115 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4116 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4118 case MONO_PATCH_INFO_VTABLE:
4119 case MONO_PATCH_INFO_CLASS:
4120 case MONO_PATCH_INFO_IID:
4121 case MONO_PATCH_INFO_ADJUSTED_IID:
4122 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4124 case MONO_PATCH_INFO_CLASS_INIT:
4125 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4126 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4128 case MONO_PATCH_INFO_FIELD:
4129 case MONO_PATCH_INFO_SFLDA:
4130 encode_field_info (acfg, patch_info->data.field, p, &p);
4132 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4134 case MONO_PATCH_INFO_RGCTX_FETCH: {
4135 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4140 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4141 * reference the same method, so encode the method only once.
4143 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4145 buf2 = g_malloc (1024);
4148 encode_method_ref (acfg, entry->method, p2, &p2);
4149 g_assert (p2 - buf2 < 1024);
4151 offset = add_to_blob (acfg, buf2, p2 - buf2);
4154 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4159 encode_value (offset, p, &p);
4160 g_assert (entry->info_type < 256);
4161 g_assert (entry->data->type < 256);
4162 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4163 encode_patch (acfg, entry->data, p, &p);
4166 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4167 case MONO_PATCH_INFO_MONITOR_ENTER:
4168 case MONO_PATCH_INFO_MONITOR_EXIT:
4169 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4171 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4172 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4173 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4175 case MONO_PATCH_INFO_SIGNATURE:
4176 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4179 g_warning ("unable to handle jump info %d", patch_info->type);
4180 g_assert_not_reached ();
4187 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4190 guint32 pindex, offset;
4191 MonoJumpInfo *patch_info;
4193 encode_value (n_patches, p, &p);
4195 for (pindex = 0; pindex < patches->len; ++pindex) {
4196 patch_info = g_ptr_array_index (patches, pindex);
4198 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4202 offset = get_got_offset (acfg, patch_info);
4203 encode_value (offset, p, &p);
4210 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4214 int pindex, buf_size, n_patches;
4216 MonoJumpInfo *patch_info;
4217 MonoMethodHeader *header;
4218 guint32 method_index;
4220 guint32 first_got_offset;
4222 method = cfg->orig_method;
4223 header = mono_method_get_header (method);
4225 method_index = get_method_index (acfg, method);
4227 /* Sort relocations */
4228 patches = g_ptr_array_new ();
4229 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4230 g_ptr_array_add (patches, patch_info);
4231 g_ptr_array_sort (patches, compare_patches);
4233 first_got_offset = acfg->cfgs [method_index]->got_offset;
4235 /**********************/
4236 /* Encode method info */
4237 /**********************/
4239 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4240 p = buf = g_malloc (buf_size);
4242 if (mono_class_get_cctor (method->klass))
4243 encode_klass_ref (acfg, method->klass, p, &p);
4245 /* Not needed when loading the method */
4246 encode_value (0, p, &p);
4249 if (cfg->opt & MONO_OPT_SHARED) {
4250 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4251 for (l = cfg->ldstr_list; l; l = l->next) {
4252 encode_value ((long)l->data, p, &p);
4256 /* Used only in shared mode */
4257 g_assert (!cfg->ldstr_list);
4260 for (pindex = 0; pindex < patches->len; ++pindex) {
4261 patch_info = g_ptr_array_index (patches, pindex);
4263 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4264 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4265 patch_info->type = MONO_PATCH_INFO_NONE;
4270 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4271 /* Stored in a GOT slot initialized at module load time */
4272 patch_info->type = MONO_PATCH_INFO_NONE;
4276 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4277 /* Stored in a GOT slot initialized at module load time */
4278 patch_info->type = MONO_PATCH_INFO_NONE;
4282 if (is_plt_patch (patch_info)) {
4283 /* Calls are made through the PLT */
4284 patch_info->type = MONO_PATCH_INFO_NONE;
4292 g_assert (cfg->has_got_slots);
4294 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4296 acfg->stats.info_size += p - buf;
4298 g_assert (p - buf < buf_size);
4300 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4305 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4307 guint32 cache_index;
4310 /* Reuse the unwind module to canonize and store unwind info entries */
4311 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4313 /* Use +/- 1 to distinguish 0s from missing entries */
4314 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4322 * It would be easier to use assembler symbols, but the caller needs an
4325 offset = acfg->unwind_info_offset;
4326 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4327 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4330 encode_value (encoded_len, p, &p);
4332 acfg->unwind_info_offset += encoded_len + (p - buf);
4338 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4341 int i, k, buf_size, method_index;
4342 guint32 debug_info_size;
4344 MonoMethodHeader *header;
4345 guint8 *p, *buf, *debug_info;
4346 MonoJitInfo *jinfo = cfg->jit_info;
4348 gboolean use_unwind_ops = FALSE;
4349 MonoSeqPointInfo *seq_points;
4351 method = cfg->orig_method;
4352 code = cfg->native_code;
4353 header = cfg->header;
4355 method_index = get_method_index (acfg, method);
4357 if (!acfg->aot_opts.nodebug) {
4358 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4361 debug_info_size = 0;
4364 seq_points = cfg->seq_point_info;
4366 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4367 p = buf = g_malloc (buf_size);
4369 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4370 use_unwind_ops = cfg->unwind_ops != NULL;
4373 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);
4375 encode_value (flags, p, &p);
4377 if (use_unwind_ops) {
4378 guint32 encoded_len;
4382 * This is a duplicate of the data in the .debug_frame section, but that
4383 * section cannot be accessed using the dl interface.
4385 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4386 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4389 encode_value (jinfo->used_regs, p, &p);
4392 /*Encode the number of holes before the number of clauses to make decoding easier*/
4393 if (jinfo->has_try_block_holes) {
4394 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4395 encode_value (table->num_holes, p, &p);
4398 /* Exception table */
4399 if (cfg->compile_llvm) {
4401 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4402 * since the information is only available to llc. Instead, we let llc save the data
4403 * into the LSDA, and read it from there at runtime.
4405 /* The assembly might be CIL stripped so emit the data ourselves */
4406 if (header->num_clauses)
4407 encode_value (header->num_clauses, p, &p);
4409 for (k = 0; k < header->num_clauses; ++k) {
4410 MonoExceptionClause *clause;
4412 clause = &header->clauses [k];
4414 encode_value (clause->flags, p, &p);
4415 if (clause->data.catch_class) {
4416 encode_value (1, p, &p);
4417 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4419 encode_value (0, p, &p);
4422 /* Emit a list of nesting clauses */
4423 for (i = 0; i < header->num_clauses; ++i) {
4425 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4427 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4429 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4430 encode_value (i, p, &p);
4432 encode_value (-1, p, &p);
4435 if (jinfo->num_clauses)
4436 encode_value (jinfo->num_clauses, p, &p);
4438 for (k = 0; k < jinfo->num_clauses; ++k) {
4439 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4441 encode_value (ei->flags, p, &p);
4442 encode_value (ei->exvar_offset, p, &p);
4444 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4445 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4447 if (ei->data.catch_class) {
4448 encode_value (1, p, &p);
4449 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4451 encode_value (0, p, &p);
4455 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4456 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4457 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4461 if (jinfo->has_generic_jit_info) {
4462 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4466 encode_value (gi->nlocs, p, &p);
4468 for (i = 0; i < gi->nlocs; ++i) {
4469 MonoDwarfLocListEntry *entry = &gi->locations [i];
4471 encode_value (entry->is_reg ? 1 : 0, p, &p);
4472 encode_value (entry->reg, p, &p);
4474 encode_value (entry->offset, p, &p);
4476 g_assert (entry->from == 0);
4478 encode_value (entry->from, p, &p);
4479 encode_value (entry->to, p, &p);
4482 if (!cfg->compile_llvm) {
4483 encode_value (gi->has_this ? 1 : 0, p, &p);
4484 encode_value (gi->this_reg, p, &p);
4485 encode_value (gi->this_offset, p, &p);
4490 * Need to encode jinfo->method too, since it is not equal to 'method'
4491 * when using generic sharing.
4493 encode_method_ref (acfg, jinfo->method, p, &p);
4496 if (jinfo->has_try_block_holes) {
4497 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4498 for (i = 0; i < table->num_holes; ++i) {
4499 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4500 encode_value (hole->clause, p, &p);
4501 encode_value (hole->length, p, &p);
4502 encode_value (hole->offset, p, &p);
4506 if (jinfo->has_arch_eh_info) {
4507 MonoArchEHJitInfo *eh_info;
4509 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4510 encode_value (eh_info->stack_size, p, &p);
4514 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4516 encode_value (seq_points->len, p, &p);
4517 last_il_offset = last_native_offset = 0;
4518 for (i = 0; i < seq_points->len; ++i) {
4519 SeqPoint *sp = &seq_points->seq_points [i];
4520 il_offset = sp->il_offset;
4521 native_offset = sp->native_offset;
4522 encode_value (il_offset - last_il_offset, p, &p);
4523 encode_value (native_offset - last_native_offset, p, &p);
4524 last_il_offset = il_offset;
4525 last_native_offset = native_offset;
4527 encode_value (sp->next_len, p, &p);
4528 for (j = 0; j < sp->next_len; ++j)
4529 encode_value (sp->next [j], p, &p);
4533 g_assert (debug_info_size < buf_size);
4535 encode_value (debug_info_size, p, &p);
4536 if (debug_info_size) {
4537 memcpy (p, debug_info, debug_info_size);
4538 p += debug_info_size;
4539 g_free (debug_info);
4544 encode_value (cfg->gc_map_size, p, &p);
4545 /* The GC map requires 4 bytes of alignment */
4546 while ((gsize)p % 4)
4548 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4549 p += cfg->gc_map_size;
4552 acfg->stats.ex_info_size += p - buf;
4554 g_assert (p - buf < buf_size);
4557 /* The GC Map requires 4 byte alignment */
4558 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4563 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4565 MonoClass *klass = mono_class_get (acfg->image, token);
4567 int i, buf_size, res;
4568 gboolean no_special_static, cant_encode;
4569 gpointer iter = NULL;
4572 mono_loader_clear_error ();
4576 p = buf = g_malloc (buf_size);
4578 /* Mark as unusable */
4579 encode_value (-1, p, &p);
4581 res = add_to_blob (acfg, buf, p - buf);
4587 buf_size = 10240 + (klass->vtable_size * 16);
4588 p = buf = g_malloc (buf_size);
4592 mono_class_init (klass);
4594 mono_class_get_nested_types (klass, &iter);
4595 g_assert (klass->nested_classes_inited);
4597 mono_class_setup_vtable (klass);
4600 * Emit all the information which is required for creating vtables so
4601 * the runtime does not need to create the MonoMethod structures which
4602 * take up a lot of space.
4605 no_special_static = !mono_class_has_special_static_fields (klass);
4607 /* Check whenever we have enough info to encode the vtable */
4608 cant_encode = FALSE;
4609 for (i = 0; i < klass->vtable_size; ++i) {
4610 MonoMethod *cm = klass->vtable [i];
4612 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4616 mono_class_has_finalizer (klass);
4618 if (klass->generic_container || cant_encode) {
4619 encode_value (-1, p, &p);
4621 encode_value (klass->vtable_size, p, &p);
4622 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);
4623 if (klass->has_cctor)
4624 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4625 if (klass->has_finalize)
4626 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4628 encode_value (klass->instance_size, p, &p);
4629 encode_value (mono_class_data_size (klass), p, &p);
4630 encode_value (klass->packing_size, p, &p);
4631 encode_value (klass->min_align, p, &p);
4633 for (i = 0; i < klass->vtable_size; ++i) {
4634 MonoMethod *cm = klass->vtable [i];
4637 encode_method_ref (acfg, cm, p, &p);
4639 encode_value (0, p, &p);
4643 acfg->stats.class_info_size += p - buf;
4645 g_assert (p - buf < buf_size);
4646 res = add_to_blob (acfg, buf, p - buf);
4653 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4655 char *debug_sym = NULL;
4658 case MONO_PATCH_INFO_METHOD:
4659 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4661 case MONO_PATCH_INFO_INTERNAL_METHOD:
4662 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4664 case MONO_PATCH_INFO_CLASS_INIT:
4665 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4666 sanitize_symbol (debug_sym);
4668 case MONO_PATCH_INFO_RGCTX_FETCH:
4669 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4671 case MONO_PATCH_INFO_ICALL_ADDR: {
4672 char *s = get_debug_sym (ji->data.method, "", cache);
4674 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4678 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4679 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4681 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4682 debug_sym = g_strdup_printf ("plt__generic_class_init");
4692 * Calls made from AOTed code are routed through a table of jumps similar to the
4693 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4694 * control to the AOT runtime through a trampoline.
4697 emit_plt (MonoAotCompile *acfg)
4703 sprintf (symbol, "plt");
4705 emit_section_change (acfg, ".text", 0);
4706 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4707 emit_label (acfg, symbol);
4708 emit_label (acfg, acfg->plt_symbol);
4710 for (i = 0; i < acfg->plt_offset; ++i) {
4711 char *debug_sym = NULL;
4712 MonoPltEntry *plt_entry = NULL;
4717 * The first plt entry is unused.
4721 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4726 * If the target is directly callable, alias the plt symbol to point to
4728 * FIXME: Use this to simplify emit_and_reloc_code ().
4729 * FIXME: Avoid the got slot.
4730 * FIXME: Add support to the binary writer.
4732 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4733 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4736 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4737 /* LLVM calls the PLT entries using bl, so emit a stub */
4738 fprintf (acfg->fp, "\n.thumb_func\n");
4739 emit_label (acfg, plt_entry->llvm_symbol);
4740 fprintf (acfg->fp, "bx pc\n");
4741 fprintf (acfg->fp, "nop\n");
4742 fprintf (acfg->fp, ".arm\n");
4743 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4745 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4752 debug_sym = plt_entry->debug_sym;
4754 if (acfg->thumb_mixed && !plt_entry->jit_used)
4755 /* Emit only a thumb version */
4758 if (!acfg->thumb_mixed)
4759 emit_label (acfg, plt_entry->llvm_symbol);
4762 if (acfg->need_no_dead_strip)
4763 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4764 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4765 emit_label (acfg, debug_sym);
4768 emit_label (acfg, plt_entry->symbol);
4770 arch_emit_plt_entry (acfg, i);
4773 emit_symbol_size (acfg, debug_sym, ".");
4776 if (acfg->thumb_mixed) {
4777 /* Make sure the ARM symbols don't alias the thumb ones */
4778 emit_zero_bytes (acfg, 16);
4781 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4784 for (i = 0; i < acfg->plt_offset; ++i) {
4785 char *debug_sym = NULL;
4786 MonoPltEntry *plt_entry = NULL;
4792 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4795 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4798 /* Skip plt entries not actually called by LLVM code */
4799 if (!plt_entry->llvm_used)
4802 if (acfg->aot_opts.write_symbols) {
4803 if (plt_entry->debug_sym)
4804 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4808 #if defined(TARGET_MACH)
4809 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4810 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4812 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4813 emit_label (acfg, debug_sym);
4815 fprintf (acfg->fp, "\n.thumb_func\n");
4817 emit_label (acfg, plt_entry->llvm_symbol);
4819 arch_emit_llvm_plt_entry (acfg, i);
4822 emit_symbol_size (acfg, debug_sym, ".");
4828 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4830 sprintf (symbol, "plt_end");
4831 emit_label (acfg, symbol);
4834 static G_GNUC_UNUSED void
4835 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4837 char start_symbol [256];
4839 guint32 buf_size, info_offset;
4840 MonoJumpInfo *patch_info;
4851 code_size = info->code_size;
4853 unwind_ops = info->unwind_ops;
4855 #ifdef __native_client_codegen__
4856 mono_nacl_fix_patches (code, ji);
4861 sprintf (start_symbol, "%s", name);
4863 emit_section_change (acfg, ".text", 0);
4864 emit_global (acfg, start_symbol, TRUE);
4865 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4866 emit_label (acfg, start_symbol);
4868 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4869 emit_label (acfg, symbol);
4872 * The code should access everything through the GOT, so we pass
4875 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4877 emit_symbol_size (acfg, start_symbol, ".");
4881 /* Sort relocations */
4882 patches = g_ptr_array_new ();
4883 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4884 if (patch_info->type != MONO_PATCH_INFO_NONE)
4885 g_ptr_array_add (patches, patch_info);
4886 g_ptr_array_sort (patches, compare_patches);
4888 buf_size = patches->len * 128 + 128;
4889 buf = g_malloc (buf_size);
4892 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4893 g_assert (p - buf < buf_size);
4895 sprintf (symbol, "%s_p", name);
4897 info_offset = add_to_blob (acfg, buf, p - buf);
4899 emit_section_change (acfg, RODATA_SECT, 0);
4900 emit_global (acfg, symbol, FALSE);
4901 emit_label (acfg, symbol);
4903 emit_int32 (acfg, info_offset);
4905 /* Emit debug info */
4909 sprintf (symbol, "%s", name);
4910 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4913 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4918 emit_trampolines (MonoAotCompile *acfg)
4921 char end_symbol [256];
4922 int i, tramp_got_offset;
4923 MonoAotTrampoline ntype;
4924 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4928 if (!acfg->aot_opts.full_aot)
4931 g_assert (acfg->image->assembly);
4933 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4934 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4935 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4936 MonoTrampInfo *info;
4939 * Emit the generic trampolines.
4941 * We could save some code by treating the generic trampolines as a wrapper
4942 * method, but that approach has its own complexities, so we choose the simpler
4945 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4946 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4947 emit_trampoline (acfg, acfg->got_offset, info);
4950 mono_arch_get_nullified_class_init_trampoline (&info);
4951 emit_trampoline (acfg, acfg->got_offset, info);
4952 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4953 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4954 emit_trampoline (acfg, acfg->got_offset, info);
4955 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4956 emit_trampoline (acfg, acfg->got_offset, info);
4959 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4960 emit_trampoline (acfg, acfg->got_offset, info);
4962 /* Emit the exception related code pieces */
4963 mono_arch_get_restore_context (&info, TRUE);
4964 emit_trampoline (acfg, acfg->got_offset, info);
4965 mono_arch_get_call_filter (&info, TRUE);
4966 emit_trampoline (acfg, acfg->got_offset, info);
4967 mono_arch_get_throw_exception (&info, TRUE);
4968 emit_trampoline (acfg, acfg->got_offset, info);
4969 mono_arch_get_rethrow_exception (&info, TRUE);
4970 emit_trampoline (acfg, acfg->got_offset, info);
4971 mono_arch_get_throw_corlib_exception (&info, TRUE);
4972 emit_trampoline (acfg, acfg->got_offset, info);
4974 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4976 GSList *l = mono_arch_get_trampolines (TRUE);
4979 MonoTrampInfo *info = l->data;
4981 emit_trampoline (acfg, acfg->got_offset, info);
4987 for (i = 0; i < 128; ++i) {
4990 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4991 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4992 emit_trampoline (acfg, acfg->got_offset, info);
4994 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4995 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4996 emit_trampoline (acfg, acfg->got_offset, info);
5002 /* delegate_invoke_impl trampolines */
5003 l = mono_arch_get_delegate_invoke_impls ();
5005 MonoTrampInfo *info = l->data;
5007 emit_trampoline (acfg, acfg->got_offset, info);
5012 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5014 /* Emit trampolines which are numerous */
5017 * These include the following:
5018 * - specific trampolines
5019 * - static rgctx invoke trampolines
5021 * These trampolines have the same code, they are parameterized by GOT
5023 * They are defined in this file, in the arch_... routines instead of
5024 * in tramp-<ARCH>.c, since it is easier to do it this way.
5028 * When running in aot-only mode, we can't create specific trampolines at
5029 * runtime, so we create a few, and save them in the AOT file.
5030 * Normal trampolines embed their argument as a literal inside the
5031 * trampoline code, we can't do that here, so instead we embed an offset
5032 * which needs to be added to the trampoline address to get the address of
5033 * the GOT slot which contains the argument value.
5034 * The generated trampolines jump to the generic trampolines using another
5035 * GOT slot, which will be setup by the AOT loader to point to the
5036 * generic trampoline code of the given type.
5040 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5044 emit_section_change (acfg, ".text", 0);
5046 tramp_got_offset = acfg->got_offset;
5048 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5050 case MONO_AOT_TRAMP_SPECIFIC:
5051 sprintf (symbol, "specific_trampolines");
5053 case MONO_AOT_TRAMP_STATIC_RGCTX:
5054 sprintf (symbol, "static_rgctx_trampolines");
5056 case MONO_AOT_TRAMP_IMT_THUNK:
5057 sprintf (symbol, "imt_thunks");
5060 g_assert_not_reached ();
5063 sprintf (end_symbol, "%s_e", symbol);
5065 if (acfg->aot_opts.write_symbols)
5066 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5068 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5069 emit_label (acfg, symbol);
5071 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5073 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5077 case MONO_AOT_TRAMP_SPECIFIC:
5078 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5079 tramp_got_offset += 2;
5081 case MONO_AOT_TRAMP_STATIC_RGCTX:
5082 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5083 tramp_got_offset += 2;
5085 case MONO_AOT_TRAMP_IMT_THUNK:
5086 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5087 tramp_got_offset += 1;
5090 g_assert_not_reached ();
5092 #ifdef __native_client_codegen__
5093 /* align to avoid 32-byte boundary crossings */
5094 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5097 if (!acfg->trampoline_size [ntype]) {
5098 g_assert (tramp_size);
5099 acfg->trampoline_size [ntype] = tramp_size;
5103 emit_label (acfg, end_symbol);
5106 /* Reserve some entries at the end of the GOT for our use */
5107 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5110 acfg->got_offset += acfg->num_trampoline_got_entries;
5114 str_begins_with (const char *str1, const char *str2)
5116 int len = strlen (str2);
5117 return strncmp (str1, str2, len) == 0;
5121 mono_aot_readonly_field_override (MonoClassField *field)
5124 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5125 char *p = rdv->name;
5127 len = strlen (field->parent->name_space);
5128 if (strncmp (p, field->parent->name_space, len))
5133 len = strlen (field->parent->name);
5134 if (strncmp (p, field->parent->name, len))
5139 if (strcmp (p, field->name))
5141 switch (rdv->type) {
5143 return &rdv->value.i1;
5145 return &rdv->value.i2;
5147 return &rdv->value.i4;
5156 add_readonly_value (MonoAotOptions *opts, const char *val)
5161 /* the format of val is:
5162 * namespace.typename.fieldname=type/value
5163 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5165 fval = strrchr (val, '/');
5167 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5170 tval = strrchr (val, '=');
5172 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5175 rdv = g_new0 (ReadOnlyValue, 1);
5176 rdv->name = g_malloc0 (tval - val + 1);
5177 memcpy (rdv->name, val, tval - val);
5180 if (strncmp (tval, "i1", 2) == 0) {
5181 rdv->value.i1 = atoi (fval);
5182 rdv->type = MONO_TYPE_I1;
5183 } else if (strncmp (tval, "i2", 2) == 0) {
5184 rdv->value.i2 = atoi (fval);
5185 rdv->type = MONO_TYPE_I2;
5186 } else if (strncmp (tval, "i4", 2) == 0) {
5187 rdv->value.i4 = atoi (fval);
5188 rdv->type = MONO_TYPE_I4;
5190 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5193 rdv->next = readonly_values;
5194 readonly_values = rdv;
5198 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5200 gchar **args, **ptr;
5202 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5203 for (ptr = args; ptr && *ptr; ptr ++) {
5204 const char *arg = *ptr;
5206 if (str_begins_with (arg, "outfile=")) {
5207 opts->outfile = g_strdup (arg + strlen ("outfile="));
5208 } else if (str_begins_with (arg, "save-temps")) {
5209 opts->save_temps = TRUE;
5210 } else if (str_begins_with (arg, "keep-temps")) {
5211 opts->save_temps = TRUE;
5212 } else if (str_begins_with (arg, "write-symbols")) {
5213 opts->write_symbols = TRUE;
5214 } else if (str_begins_with (arg, "no-write-symbols")) {
5215 opts->write_symbols = FALSE;
5216 } else if (str_begins_with (arg, "metadata-only")) {
5217 opts->metadata_only = TRUE;
5218 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5219 opts->bind_to_runtime_version = TRUE;
5220 } else if (str_begins_with (arg, "full")) {
5221 opts->full_aot = TRUE;
5222 } else if (str_begins_with (arg, "threads=")) {
5223 opts->nthreads = atoi (arg + strlen ("threads="));
5224 } else if (str_begins_with (arg, "static")) {
5225 opts->static_link = TRUE;
5226 opts->no_dlsym = TRUE;
5227 } else if (str_begins_with (arg, "asmonly")) {
5228 opts->asm_only = TRUE;
5229 } else if (str_begins_with (arg, "asmwriter")) {
5230 opts->asm_writer = TRUE;
5231 } else if (str_begins_with (arg, "nodebug")) {
5232 opts->nodebug = TRUE;
5233 } else if (str_begins_with (arg, "ntrampolines=")) {
5234 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5235 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5236 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5237 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5238 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5239 } else if (str_begins_with (arg, "autoreg")) {
5240 opts->autoreg = TRUE;
5241 } else if (str_begins_with (arg, "tool-prefix=")) {
5242 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5243 } else if (str_begins_with (arg, "soft-debug")) {
5244 opts->soft_debug = TRUE;
5245 } else if (str_begins_with (arg, "direct-pinvoke")) {
5246 opts->direct_pinvoke = TRUE;
5247 } else if (str_begins_with (arg, "direct-icalls")) {
5248 opts->direct_icalls = TRUE;
5249 } else if (str_begins_with (arg, "print-skipped")) {
5250 opts->print_skipped_methods = TRUE;
5251 } else if (str_begins_with (arg, "stats")) {
5253 } else if (str_begins_with (arg, "log-generics")) {
5254 opts->log_generics = TRUE;
5255 } else if (str_begins_with (arg, "mtriple=")) {
5256 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5257 } else if (str_begins_with (arg, "llvm-path=")) {
5258 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5259 } else if (str_begins_with (arg, "readonly-value=")) {
5260 add_readonly_value (opts, arg + strlen ("readonly-value="));
5261 } else if (str_begins_with (arg, "info")) {
5262 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5264 } else if (str_begins_with (arg, "gc-maps")) {
5265 mini_gc_enable_gc_maps_for_aot ();
5266 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5267 printf ("Supported options for --aot:\n");
5268 printf (" outfile=\n");
5269 printf (" save-temps\n");
5270 printf (" keep-temps\n");
5271 printf (" write-symbols\n");
5272 printf (" metadata-only\n");
5273 printf (" bind-to-runtime-version\n");
5275 printf (" threads=\n");
5276 printf (" static\n");
5277 printf (" asmonly\n");
5278 printf (" asmwriter\n");
5279 printf (" nodebug\n");
5280 printf (" ntrampolines=\n");
5281 printf (" nrgctx-trampolines=\n");
5282 printf (" nimt-trampolines=\n");
5283 printf (" autoreg\n");
5284 printf (" tool-prefix=\n");
5285 printf (" readonly-value=\n");
5286 printf (" soft-debug\n");
5287 printf (" gc-maps\n");
5288 printf (" print-skipped\n");
5289 printf (" stats\n");
5291 printf (" help/?\n");
5294 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5303 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5305 MonoMethod *method = (MonoMethod*)key;
5306 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5307 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5308 MonoAotCompile *acfg = user_data;
5310 new_ji->image = ji->image;
5311 new_ji->token = ji->token;
5312 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5316 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5318 if (klass->type_token)
5320 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5323 return can_encode_class (acfg, klass->element_class);
5328 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5330 switch (patch_info->type) {
5331 case MONO_PATCH_INFO_METHOD:
5332 case MONO_PATCH_INFO_METHODCONST: {
5333 MonoMethod *method = patch_info->data.method;
5335 if (method->wrapper_type) {
5336 switch (method->wrapper_type) {
5337 case MONO_WRAPPER_NONE:
5338 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5339 case MONO_WRAPPER_XDOMAIN_INVOKE:
5340 case MONO_WRAPPER_STFLD:
5341 case MONO_WRAPPER_LDFLD:
5342 case MONO_WRAPPER_LDFLDA:
5343 case MONO_WRAPPER_LDFLD_REMOTE:
5344 case MONO_WRAPPER_STFLD_REMOTE:
5345 case MONO_WRAPPER_STELEMREF:
5346 case MONO_WRAPPER_ISINST:
5347 case MONO_WRAPPER_PROXY_ISINST:
5348 case MONO_WRAPPER_ALLOC:
5349 case MONO_WRAPPER_REMOTING_INVOKE:
5350 case MONO_WRAPPER_UNKNOWN:
5351 case MONO_WRAPPER_WRITE_BARRIER:
5353 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5354 case MONO_WRAPPER_CASTCLASS: {
5355 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5364 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5368 if (!method->token) {
5369 /* The method is part of a constructed type like Int[,].Set (). */
5370 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5371 if (method->klass->rank)
5379 case MONO_PATCH_INFO_VTABLE:
5380 case MONO_PATCH_INFO_CLASS_INIT:
5381 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5382 case MONO_PATCH_INFO_CLASS:
5383 case MONO_PATCH_INFO_IID:
5384 case MONO_PATCH_INFO_ADJUSTED_IID:
5385 if (!can_encode_class (acfg, patch_info->data.klass)) {
5386 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5390 case MONO_PATCH_INFO_RGCTX_FETCH: {
5391 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5393 if (!can_encode_patch (acfg, entry->data))
5407 * AOT compile a given method.
5408 * This function might be called by multiple threads, so it must be thread-safe.
5411 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5414 MonoJumpInfo *patch_info;
5417 MonoMethod *wrapped;
5419 if (acfg->aot_opts.metadata_only)
5422 mono_acfg_lock (acfg);
5423 index = get_method_index (acfg, method);
5424 mono_acfg_unlock (acfg);
5426 /* fixme: maybe we can also precompile wrapper methods */
5427 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5428 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5429 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5430 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5434 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5437 wrapped = mono_marshal_method_from_wrapper (method);
5438 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5439 // FIXME: The wrapper should be generic too, but it is not
5442 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5445 InterlockedIncrement (&acfg->stats.mcount);
5448 if (method->is_generic || method->klass->generic_container) {
5449 InterlockedIncrement (&acfg->stats.genericcount);
5454 //acfg->aot_opts.print_skipped_methods = TRUE;
5457 * Since these methods are the only ones which are compiled with
5458 * AOT support, and they are not used by runtime startup/shutdown code,
5459 * the runtime will not see AOT methods during AOT compilation,so it
5460 * does not need to support them by creating a fake GOT etc.
5462 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5463 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5464 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5465 InterlockedIncrement (&acfg->stats.genericcount);
5468 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5469 if (acfg->aot_opts.print_skipped_methods)
5470 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5471 /* Let the exception happen at runtime */
5475 if (cfg->disable_aot) {
5476 if (acfg->aot_opts.print_skipped_methods)
5477 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5478 InterlockedIncrement (&acfg->stats.ocount);
5479 mono_destroy_compile (cfg);
5483 /* Nullify patches which need no aot processing */
5484 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5485 switch (patch_info->type) {
5486 case MONO_PATCH_INFO_LABEL:
5487 case MONO_PATCH_INFO_BB:
5488 patch_info->type = MONO_PATCH_INFO_NONE;
5495 /* Collect method->token associations from the cfg */
5496 mono_acfg_lock (acfg);
5497 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5498 mono_acfg_unlock (acfg);
5501 * Check for absolute addresses.
5504 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5505 switch (patch_info->type) {
5506 case MONO_PATCH_INFO_ABS:
5507 /* unable to handle this */
5516 if (acfg->aot_opts.print_skipped_methods)
5517 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5518 InterlockedIncrement (&acfg->stats.abscount);
5519 mono_destroy_compile (cfg);
5523 /* Lock for the rest of the code */
5524 mono_acfg_lock (acfg);
5527 * Check for methods/klasses we can't encode.
5530 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5531 if (!can_encode_patch (acfg, patch_info))
5536 if (acfg->aot_opts.print_skipped_methods)
5537 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5538 acfg->stats.ocount++;
5539 mono_destroy_compile (cfg);
5540 mono_acfg_unlock (acfg);
5544 /* Adds generic instances referenced by this method */
5546 * The depth is used to avoid infinite loops when generic virtual recursion is
5549 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5551 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5552 switch (patch_info->type) {
5553 case MONO_PATCH_INFO_METHOD: {
5554 MonoMethod *m = patch_info->data.method;
5555 if (m->is_inflated) {
5556 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5557 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5558 !method_has_type_vars (m)) {
5559 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5560 if (acfg->aot_opts.full_aot)
5561 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5563 add_extra_method_with_depth (acfg, m, depth + 1);
5564 add_types_from_method_header (acfg, m);
5567 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5569 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5570 add_extra_method_with_depth (acfg, m, depth + 1);
5573 case MONO_PATCH_INFO_VTABLE: {
5574 MonoClass *klass = patch_info->data.klass;
5576 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5577 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5580 case MONO_PATCH_INFO_SFLDA: {
5581 MonoClass *klass = patch_info->data.field->parent;
5583 /* The .cctor needs to run at runtime. */
5584 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5585 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5594 /* Determine whenever the method has GOT slots */
5595 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5596 switch (patch_info->type) {
5597 case MONO_PATCH_INFO_GOT_OFFSET:
5598 case MONO_PATCH_INFO_NONE:
5599 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5601 case MONO_PATCH_INFO_IMAGE:
5602 /* The assembly is stored in GOT slot 0 */
5603 if (patch_info->data.image != acfg->image)
5604 cfg->has_got_slots = TRUE;
5607 if (!is_plt_patch (patch_info))
5608 cfg->has_got_slots = TRUE;
5613 if (!cfg->has_got_slots)
5614 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5617 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5619 /* Make a copy of the patch info which is in the mempool */
5621 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5623 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5624 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5627 patches = new_patch_info;
5629 patches_end->next = new_patch_info;
5630 patches_end = new_patch_info;
5632 cfg->patch_info = patches;
5634 /* Make a copy of the unwind info */
5636 GSList *l, *unwind_ops;
5640 for (l = cfg->unwind_ops; l; l = l->next) {
5641 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5642 memcpy (op, l->data, sizeof (MonoUnwindOp));
5643 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5645 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5647 /* Make a copy of the argument/local info */
5649 MonoInst **args, **locals;
5650 MonoMethodSignature *sig;
5651 MonoMethodHeader *header;
5654 sig = mono_method_signature (method);
5655 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5656 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5657 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5658 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5662 header = mono_method_get_header (method);
5663 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5664 for (i = 0; i < header->num_locals; ++i) {
5665 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5666 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5668 cfg->locals = locals;
5671 /* Free some fields used by cfg to conserve memory */
5672 mono_mempool_destroy (cfg->mempool);
5673 cfg->mempool = NULL;
5674 g_free (cfg->varinfo);
5675 cfg->varinfo = NULL;
5679 mono_regstate_free (cfg->rs);
5683 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5685 while (index >= acfg->cfgs_size) {
5686 MonoCompile **new_cfgs;
5689 new_size = acfg->cfgs_size * 2;
5690 new_cfgs = g_new0 (MonoCompile*, new_size);
5691 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5692 g_free (acfg->cfgs);
5693 acfg->cfgs = new_cfgs;
5694 acfg->cfgs_size = new_size;
5696 acfg->cfgs [index] = cfg;
5698 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5701 if (cfg->orig_method->wrapper_type)
5702 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5705 mono_acfg_unlock (acfg);
5707 InterlockedIncrement (&acfg->stats.ccount);
5711 compile_thread_main (gpointer *user_data)
5713 MonoDomain *domain = user_data [0];
5714 MonoAotCompile *acfg = user_data [1];
5715 GPtrArray *methods = user_data [2];
5718 mono_thread_attach (domain);
5720 for (i = 0; i < methods->len; ++i)
5721 compile_method (acfg, g_ptr_array_index (methods, i));
5725 load_profile_files (MonoAotCompile *acfg)
5729 int file_index, res, method_index, i;
5732 GList *unordered, *l;
5737 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5739 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5744 infile = fopen (tmp, "r");
5747 printf ("Using profile data file '%s'\n", tmp);
5752 res = fscanf (infile, "%32s\n", ver);
5753 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5754 printf ("Profile file has wrong version or invalid.\n");
5761 MonoMethodDesc *desc;
5764 if (fgets (name, 1023, infile) == NULL)
5767 /* Kill the newline */
5768 if (strlen (name) > 0)
5769 name [strlen (name) - 1] = '\0';
5771 desc = mono_method_desc_new (name, TRUE);
5773 method = mono_method_desc_search_in_image (desc, acfg->image);
5775 if (method && mono_method_get_token (method)) {
5776 token = mono_method_get_token (method);
5777 method_index = mono_metadata_token_index (token) - 1;
5780 for (i = 0; i < acfg->method_order->len; ++i) {
5781 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5787 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5789 //printf ("No method found matching '%s'.\n", name);
5795 /* Add missing methods */
5797 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5799 for (i = 0; i < acfg->method_order->len; ++i) {
5800 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5806 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5808 unordered = g_list_reverse (unordered);
5809 for (l = unordered; l; l = l->next)
5810 g_ptr_array_add (acfg->method_order, l->data);
5813 /* Used by the LLVM backend */
5815 mono_aot_get_got_offset (MonoJumpInfo *ji)
5817 return get_got_offset (llvm_acfg, ji);
5821 mono_aot_get_method_name (MonoCompile *cfg)
5823 if (llvm_acfg->aot_opts.static_link)
5824 /* Include the assembly name too to avoid duplicate symbol errors */
5825 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5827 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5831 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5833 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5834 MonoPltEntry *plt_entry;
5837 ji->data.target = data;
5839 if (!can_encode_patch (llvm_acfg, ji))
5842 plt_entry = get_plt_entry (llvm_acfg, ji);
5843 plt_entry->llvm_used = TRUE;
5845 #if defined(TARGET_MACH)
5846 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5848 return g_strdup_printf (plt_entry->llvm_symbol);
5853 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5857 mono_acfg_lock (llvm_acfg);
5858 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5859 mono_acfg_unlock (llvm_acfg);
5869 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5873 emit_llvm_file (MonoAotCompile *acfg)
5875 char *command, *opts;
5877 MonoJumpInfo *patch_info;
5880 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5884 /* Compute the final size of the got */
5885 for (i = 0; i < acfg->nmethods; ++i) {
5886 if (acfg->cfgs [i]) {
5887 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5888 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5889 if (!is_plt_patch (patch_info))
5890 get_got_offset (acfg, patch_info);
5892 get_plt_entry (acfg, patch_info);
5898 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5900 if (acfg->aot_opts.full_aot) {
5904 * Need to add the got entries used by the trampolines.
5905 * This is only a conservative approximation.
5907 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5908 /* For the generic + rgctx trampolines */
5909 acfg->final_got_size += 200;
5910 /* For the specific trampolines */
5911 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5912 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5917 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5920 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5921 * a lot of time, and doesn't seem to save much space.
5922 * The following optimizations cannot be enabled:
5924 * - 'jump-threading' changes our blockaddress references to int constants.
5925 * - 'basiccg' fails because it contains:
5926 * if (CS && !isa<IntrinsicInst>(II)) {
5927 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5928 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5929 * The opt list below was produced by taking the output of:
5930 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5931 * then removing tailcallelim + the global opts, and adding a second gvn.
5933 opts = g_strdup ("-instcombine -simplifycfg");
5934 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");
5936 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5937 printf ("Executing opt: %s\n", command);
5938 if (system (command) != 0) {
5944 if (!acfg->llc_args)
5945 acfg->llc_args = g_string_new ("");
5947 /* Verbose asm slows down llc greatly */
5948 g_string_append (acfg->llc_args, " -asm-verbose=false");
5950 if (acfg->aot_opts.mtriple)
5951 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5953 if (llvm_acfg->aot_opts.static_link)
5954 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5956 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5957 unlink (acfg->tmpfname);
5959 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5961 printf ("Executing llc: %s\n", command);
5963 if (system (command) != 0) {
5970 emit_code (MonoAotCompile *acfg)
5972 int oindex, i, prev_index;
5974 char end_symbol [256];
5976 #if defined(TARGET_POWERPC64)
5977 sprintf (symbol, ".Lgot_addr");
5978 emit_section_change (acfg, ".text", 0);
5979 emit_alignment (acfg, 8);
5980 emit_label (acfg, symbol);
5981 emit_pointer (acfg, acfg->got_symbol);
5985 * This global symbol is used to compute the address of each method using the
5986 * code_offsets array. It is also used to compute the memory ranges occupied by
5987 * AOT code, so it must be equal to the address of the first emitted method.
5989 sprintf (symbol, "methods");
5990 emit_section_change (acfg, ".text", 0);
5991 emit_alignment (acfg, 8);
5993 for (i = 0; i < acfg->nmethods; ++i) {
5994 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5995 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5999 if (i == acfg->nmethods)
6000 /* No LLVM compiled methods */
6001 emit_label (acfg, symbol);
6003 emit_label (acfg, symbol);
6007 * Emit some padding so the local symbol for the first method doesn't have the
6008 * same address as 'methods'.
6010 #if defined(__default_codegen__)
6011 emit_zero_bytes (acfg, 16);
6012 #elif defined(__native_client_codegen__)
6014 const int kPaddingSize = 16;
6015 guint8 pad_buffer[kPaddingSize];
6016 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6017 emit_bytes (acfg, pad_buffer, kPaddingSize);
6021 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6025 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6027 cfg = acfg->cfgs [i];
6032 method = cfg->orig_method;
6034 /* Emit unbox trampoline */
6035 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6036 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6038 emit_section_change (acfg, ".text", 0);
6039 #ifdef __native_client_codegen__
6040 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6043 if (acfg->thumb_mixed && cfg->compile_llvm)
6044 fprintf (acfg->fp, "\n.thumb_func\n");
6046 emit_label (acfg, symbol);
6048 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6051 if (cfg->compile_llvm)
6052 acfg->stats.llvm_count ++;
6054 emit_method_code (acfg, cfg);
6057 sprintf (symbol, "methods_end");
6058 emit_section_change (acfg, ".text", 0);
6059 emit_alignment (acfg, 8);
6060 emit_label (acfg, symbol);
6063 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6064 * from optimizing them away, since it doesn't see that code_offsets references them.
6065 * JITted methods don't need this since they are referenced using assembler local
6067 * FIXME: This is why write-symbols doesn't work on OSX ?
6069 if (acfg->llvm && acfg->need_no_dead_strip) {
6070 fprintf (acfg->fp, "\n");
6071 for (i = 0; i < acfg->nmethods; ++i) {
6072 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6073 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6077 sprintf (symbol, "code_offsets");
6078 emit_section_change (acfg, RODATA_SECT, 1);
6079 emit_alignment (acfg, 8);
6080 emit_label (acfg, symbol);
6082 acfg->stats.offsets_size += acfg->nmethods * 4;
6084 sprintf (end_symbol, "methods");
6085 for (i = 0; i < acfg->nmethods; ++i) {
6086 if (acfg->cfgs [i]) {
6087 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6089 emit_int32 (acfg, 0xffffffff);
6094 /* Emit a sorted table mapping methods to their unbox trampolines */
6095 sprintf (symbol, "unbox_trampolines");
6096 emit_section_change (acfg, RODATA_SECT, 1);
6097 emit_alignment (acfg, 8);
6098 emit_label (acfg, symbol);
6100 sprintf (end_symbol, "methods");
6102 for (i = 0; i < acfg->nmethods; ++i) {
6107 cfg = acfg->cfgs [i];
6111 method = cfg->orig_method;
6113 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6114 index = get_method_index (acfg, method);
6115 sprintf (symbol, "ut_%d", index);
6117 emit_int32 (acfg, index);
6118 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6119 /* Make sure the table is sorted by index */
6120 g_assert (index > prev_index);
6124 sprintf (symbol, "unbox_trampolines_end");
6125 emit_label (acfg, symbol);
6129 emit_info (MonoAotCompile *acfg)
6135 offsets = g_new0 (gint32, acfg->nmethods);
6137 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6138 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6140 if (acfg->cfgs [i]) {
6141 emit_method_info (acfg, acfg->cfgs [i]);
6142 offsets [i] = acfg->cfgs [i]->method_info_offset;
6148 sprintf (symbol, "method_info_offsets");
6149 emit_section_change (acfg, RODATA_SECT, 1);
6150 emit_alignment (acfg, 8);
6151 emit_label (acfg, symbol);
6153 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6158 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6160 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6161 #define mix(a,b,c) { \
6162 a -= c; a ^= rot(c, 4); c += b; \
6163 b -= a; b ^= rot(a, 6); a += c; \
6164 c -= b; c ^= rot(b, 8); b += a; \
6165 a -= c; a ^= rot(c,16); c += b; \
6166 b -= a; b ^= rot(a,19); a += c; \
6167 c -= b; c ^= rot(b, 4); b += a; \
6169 #define final(a,b,c) { \
6170 c ^= b; c -= rot(b,14); \
6171 a ^= c; a -= rot(c,11); \
6172 b ^= a; b -= rot(a,25); \
6173 c ^= b; c -= rot(b,16); \
6174 a ^= c; a -= rot(c,4); \
6175 b ^= a; b -= rot(a,14); \
6176 c ^= b; c -= rot(b,24); \
6180 mono_aot_type_hash (MonoType *t1)
6182 guint hash = t1->type;
6184 hash |= t1->byref << 6; /* do not collide with t1->type values */
6186 case MONO_TYPE_VALUETYPE:
6187 case MONO_TYPE_CLASS:
6188 case MONO_TYPE_SZARRAY:
6189 /* check if the distribution is good enough */
6190 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6192 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6193 case MONO_TYPE_ARRAY:
6194 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6195 case MONO_TYPE_GENERICINST:
6196 return ((hash << 5) - hash) ^ 0;
6203 * mono_aot_method_hash:
6205 * Return a hash code for methods which only depends on metadata.
6208 mono_aot_method_hash (MonoMethod *method)
6210 MonoMethodSignature *sig;
6214 guint32 *hashes_start, *hashes;
6216 MonoGenericInst *ginst = NULL;
6218 /* Similar to the hash in mono_method_get_imt_slot () */
6220 sig = mono_method_signature (method);
6222 if (method->is_inflated)
6223 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6225 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6226 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6227 hashes = hashes_start;
6229 /* Some wrappers are assigned to random classes */
6230 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6231 klass = method->klass;
6233 klass = mono_defaults.object_class;
6235 if (!method->wrapper_type) {
6236 char *full_name = mono_type_full_name (&klass->byval_arg);
6238 hashes [0] = mono_metadata_str_hash (full_name);
6242 hashes [0] = mono_metadata_str_hash (klass->name);
6243 hashes [1] = mono_metadata_str_hash (klass->name_space);
6245 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6246 /* The method name includes a stringified pointer */
6249 hashes [2] = mono_metadata_str_hash (method->name);
6250 hashes [3] = method->wrapper_type;
6251 hashes [4] = mono_aot_type_hash (sig->ret);
6253 for (i = 0; i < sig->param_count; i++) {
6254 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6257 for (i = 0; i < ginst->type_argc; ++i)
6258 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6260 g_assert (hindex == hashes_count);
6262 /* Setup internal state */
6263 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6265 /* Handle most of the hashes */
6266 while (hashes_count > 3) {
6275 /* Handle the last 3 hashes (all the case statements fall through) */
6276 switch (hashes_count) {
6277 case 3 : c += hashes [2];
6278 case 2 : b += hashes [1];
6279 case 1 : a += hashes [0];
6281 case 0: /* nothing left to add */
6285 free (hashes_start);
6294 * mono_aot_wrapper_name:
6296 * Return a string which uniqely identifies the given wrapper method.
6299 mono_aot_wrapper_name (MonoMethod *method)
6301 char *name, *tmpsig, *klass_desc;
6303 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6305 switch (method->wrapper_type) {
6306 case MONO_WRAPPER_RUNTIME_INVOKE:
6307 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6308 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6310 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6313 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6314 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6315 g_free (klass_desc);
6325 * mono_aot_get_array_helper_from_wrapper;
6327 * Get the helper method in Array called by an array wrapper method.
6330 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6334 MonoGenericContext ctx;
6335 MonoType *args [16];
6336 char *mname, *iname, *s, *s2, *helper_name = NULL;
6338 prefix = "System.Collections.Generic";
6339 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6340 s2 = strstr (s, "`1.");
6346 //printf ("X: %s %s\n", iname, mname);
6348 if (!strcmp (iname, "IList"))
6349 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6351 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6352 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6354 g_free (helper_name);
6357 if (m->is_generic) {
6358 memset (&ctx, 0, sizeof (ctx));
6359 args [0] = &method->klass->element_class->byval_arg;
6360 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6361 m = mono_class_inflate_generic_method (m, &ctx);
6367 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6369 typedef struct HashEntry {
6370 guint32 key, value, index;
6371 struct HashEntry *next;
6375 * emit_extra_methods:
6377 * Emit methods which are not in the METHOD table, like wrappers.
6380 emit_extra_methods (MonoAotCompile *acfg)
6382 int i, table_size, buf_size;
6385 guint32 *info_offsets;
6388 HashEntry *entry, *new_entry;
6389 int nmethods, max_chain_length;
6392 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6394 /* Emit method info */
6396 for (i = 0; i < acfg->extra_methods->len; ++i) {
6397 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6398 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6404 p = buf = g_malloc (buf_size);
6408 method = cfg->method_to_register;
6410 encode_method_ref (acfg, method, p, &p);
6412 g_assert ((p - buf) < buf_size);
6414 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6419 * Construct a chained hash table for mapping indexes in extra_method_info to
6422 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6423 table = g_ptr_array_sized_new (table_size);
6424 for (i = 0; i < table_size; ++i)
6425 g_ptr_array_add (table, NULL);
6426 chain_lengths = g_new0 (int, table_size);
6427 max_chain_length = 0;
6428 for (i = 0; i < acfg->extra_methods->len; ++i) {
6429 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6430 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6436 key = info_offsets [i];
6437 value = get_method_index (acfg, method);
6439 hash = mono_aot_method_hash (method) % table_size;
6441 chain_lengths [hash] ++;
6442 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6444 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6445 new_entry->key = key;
6446 new_entry->value = value;
6448 entry = g_ptr_array_index (table, hash);
6449 if (entry == NULL) {
6450 new_entry->index = hash;
6451 g_ptr_array_index (table, hash) = new_entry;
6454 entry = entry->next;
6456 entry->next = new_entry;
6457 new_entry->index = table->len;
6458 g_ptr_array_add (table, new_entry);
6462 //printf ("MAX: %d\n", max_chain_length);
6464 /* Emit the table */
6465 sprintf (symbol, "extra_method_table");
6466 emit_section_change (acfg, RODATA_SECT, 0);
6467 emit_alignment (acfg, 8);
6468 emit_label (acfg, symbol);
6470 emit_int32 (acfg, table_size);
6471 for (i = 0; i < table->len; ++i) {
6472 HashEntry *entry = g_ptr_array_index (table, i);
6474 if (entry == NULL) {
6475 emit_int32 (acfg, 0);
6476 emit_int32 (acfg, 0);
6477 emit_int32 (acfg, 0);
6479 //g_assert (entry->key > 0);
6480 emit_int32 (acfg, entry->key);
6481 emit_int32 (acfg, entry->value);
6483 emit_int32 (acfg, entry->next->index);
6485 emit_int32 (acfg, 0);
6490 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6491 * This is used by mono_aot_find_jit_info ().
6493 sprintf (symbol, "extra_method_info_offsets");
6494 emit_section_change (acfg, RODATA_SECT, 0);
6495 emit_alignment (acfg, 8);
6496 emit_label (acfg, symbol);
6498 emit_int32 (acfg, acfg->extra_methods->len);
6499 for (i = 0; i < acfg->extra_methods->len; ++i) {
6500 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6502 emit_int32 (acfg, get_method_index (acfg, method));
6503 emit_int32 (acfg, info_offsets [i]);
6508 emit_exception_info (MonoAotCompile *acfg)
6514 offsets = g_new0 (gint32, acfg->nmethods);
6515 for (i = 0; i < acfg->nmethods; ++i) {
6516 if (acfg->cfgs [i]) {
6517 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6518 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6524 sprintf (symbol, "ex_info_offsets");
6525 emit_section_change (acfg, RODATA_SECT, 1);
6526 emit_alignment (acfg, 8);
6527 emit_label (acfg, symbol);
6529 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6534 emit_unwind_info (MonoAotCompile *acfg)
6540 * The unwind info contains a lot of duplicates so we emit each unique
6541 * entry once, and only store the offset from the start of the table in the
6545 sprintf (symbol, "unwind_info");
6546 emit_section_change (acfg, RODATA_SECT, 1);
6547 emit_alignment (acfg, 8);
6548 emit_label (acfg, symbol);
6550 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6551 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6552 guint8 *unwind_info;
6553 guint32 unwind_info_len;
6557 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6560 encode_value (unwind_info_len, p, &p);
6561 emit_bytes (acfg, buf, p - buf);
6562 emit_bytes (acfg, unwind_info, unwind_info_len);
6564 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6569 emit_class_info (MonoAotCompile *acfg)
6575 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6576 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6577 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6579 sprintf (symbol, "class_info_offsets");
6580 emit_section_change (acfg, RODATA_SECT, 1);
6581 emit_alignment (acfg, 8);
6582 emit_label (acfg, symbol);
6584 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6588 typedef struct ClassNameTableEntry {
6589 guint32 token, index;
6590 struct ClassNameTableEntry *next;
6591 } ClassNameTableEntry;
6594 emit_class_name_table (MonoAotCompile *acfg)
6597 guint32 token, hash;
6602 ClassNameTableEntry *entry, *new_entry;
6605 * Construct a chained hash table for mapping class names to typedef tokens.
6607 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6608 table = g_ptr_array_sized_new (table_size);
6609 for (i = 0; i < table_size; ++i)
6610 g_ptr_array_add (table, NULL);
6611 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6612 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6613 klass = mono_class_get (acfg->image, token);
6615 mono_loader_clear_error ();
6618 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6619 hash = mono_metadata_str_hash (full_name) % table_size;
6622 /* FIXME: Allocate from the mempool */
6623 new_entry = g_new0 (ClassNameTableEntry, 1);
6624 new_entry->token = token;
6626 entry = g_ptr_array_index (table, hash);
6627 if (entry == NULL) {
6628 new_entry->index = hash;
6629 g_ptr_array_index (table, hash) = new_entry;
6632 entry = entry->next;
6634 entry->next = new_entry;
6635 new_entry->index = table->len;
6636 g_ptr_array_add (table, new_entry);
6640 /* Emit the table */
6641 sprintf (symbol, "class_name_table");
6642 emit_section_change (acfg, RODATA_SECT, 0);
6643 emit_alignment (acfg, 8);
6644 emit_label (acfg, symbol);
6646 /* FIXME: Optimize memory usage */
6647 g_assert (table_size < 65000);
6648 emit_int16 (acfg, table_size);
6649 g_assert (table->len < 65000);
6650 for (i = 0; i < table->len; ++i) {
6651 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6653 if (entry == NULL) {
6654 emit_int16 (acfg, 0);
6655 emit_int16 (acfg, 0);
6657 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6659 emit_int16 (acfg, entry->next->index);
6661 emit_int16 (acfg, 0);
6667 emit_image_table (MonoAotCompile *acfg)
6673 * The image table is small but referenced in a lot of places.
6674 * So we emit it at once, and reference its elements by an index.
6677 sprintf (symbol, "image_table");
6678 emit_section_change (acfg, RODATA_SECT, 1);
6679 emit_alignment (acfg, 8);
6680 emit_label (acfg, symbol);
6682 emit_int32 (acfg, acfg->image_table->len);
6683 for (i = 0; i < acfg->image_table->len; i++) {
6684 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6685 MonoAssemblyName *aname = &image->assembly->aname;
6687 /* FIXME: Support multi-module assemblies */
6688 g_assert (image->assembly->image == image);
6690 emit_string (acfg, image->assembly_name);
6691 emit_string (acfg, image->guid);
6692 emit_string (acfg, aname->culture ? aname->culture : "");
6693 emit_string (acfg, (const char*)aname->public_key_token);
6695 emit_alignment (acfg, 8);
6696 emit_int32 (acfg, aname->flags);
6697 emit_int32 (acfg, aname->major);
6698 emit_int32 (acfg, aname->minor);
6699 emit_int32 (acfg, aname->build);
6700 emit_int32 (acfg, aname->revision);
6705 emit_got_info (MonoAotCompile *acfg)
6708 int i, first_plt_got_patch, buf_size;
6710 guint32 *got_info_offsets;
6712 /* Add the patches needed by the PLT to the GOT */
6713 acfg->plt_got_offset_base = acfg->got_offset;
6714 first_plt_got_patch = acfg->got_patches->len;
6715 for (i = 1; i < acfg->plt_offset; ++i) {
6716 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6718 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6720 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6723 acfg->got_offset += acfg->plt_offset;
6727 * - optimize offsets table.
6728 * - reduce number of exported symbols.
6729 * - emit info for a klass only once.
6730 * - determine when a method uses a GOT slot which is guaranteed to be already
6732 * - clean up and document the code.
6733 * - use String.Empty in class libs.
6736 /* Encode info required to decode shared GOT entries */
6737 buf_size = acfg->got_patches->len * 128;
6738 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6739 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6740 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6742 if (acfg->plt_offset)
6743 acfg->plt_got_info_offsets [0] = 0;
6744 for (i = 0; i < acfg->got_patches->len; ++i) {
6745 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6750 encode_value (ji->type, p, &p);
6752 encode_patch (acfg, ji, p, &p);
6753 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6754 g_assert (p - buf <= buf_size);
6755 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6757 if (i >= first_plt_got_patch)
6758 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6759 acfg->stats.got_info_size += p - buf;
6762 /* Emit got_info_offsets table */
6763 sprintf (symbol, "got_info_offsets");
6764 emit_section_change (acfg, RODATA_SECT, 1);
6765 emit_alignment (acfg, 8);
6766 emit_label (acfg, symbol);
6768 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6769 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6773 emit_got (MonoAotCompile *acfg)
6778 /* Don't make GOT global so accesses to it don't need relocations */
6779 sprintf (symbol, "%s", acfg->got_symbol);
6780 emit_section_change (acfg, ".bss", 0);
6781 emit_alignment (acfg, 8);
6782 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6783 emit_label (acfg, symbol);
6784 if (acfg->got_offset > 0)
6785 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6787 sprintf (symbol, "got_end");
6788 emit_label (acfg, symbol);
6792 typedef struct GlobalsTableEntry {
6793 guint32 value, index;
6794 struct GlobalsTableEntry *next;
6795 } GlobalsTableEntry;
6798 emit_globals (MonoAotCompile *acfg)
6804 GlobalsTableEntry *entry, *new_entry;
6806 if (!acfg->aot_opts.static_link)
6810 * When static linking, we emit a table containing our globals.
6814 * Construct a chained hash table for mapping global names to their index in
6815 * the globals table.
6817 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6818 table = g_ptr_array_sized_new (table_size);
6819 for (i = 0; i < table_size; ++i)
6820 g_ptr_array_add (table, NULL);
6821 for (i = 0; i < acfg->globals->len; ++i) {
6822 char *name = g_ptr_array_index (acfg->globals, i);
6824 hash = mono_metadata_str_hash (name) % table_size;
6826 /* FIXME: Allocate from the mempool */
6827 new_entry = g_new0 (GlobalsTableEntry, 1);
6828 new_entry->value = i;
6830 entry = g_ptr_array_index (table, hash);
6831 if (entry == NULL) {
6832 new_entry->index = hash;
6833 g_ptr_array_index (table, hash) = new_entry;
6836 entry = entry->next;
6838 entry->next = new_entry;
6839 new_entry->index = table->len;
6840 g_ptr_array_add (table, new_entry);
6844 /* Emit the table */
6845 sprintf (symbol, ".Lglobals_hash");
6846 emit_section_change (acfg, RODATA_SECT, 0);
6847 emit_alignment (acfg, 8);
6848 emit_label (acfg, symbol);
6850 /* FIXME: Optimize memory usage */
6851 g_assert (table_size < 65000);
6852 emit_int16 (acfg, table_size);
6853 for (i = 0; i < table->len; ++i) {
6854 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6856 if (entry == NULL) {
6857 emit_int16 (acfg, 0);
6858 emit_int16 (acfg, 0);
6860 emit_int16 (acfg, entry->value + 1);
6862 emit_int16 (acfg, entry->next->index);
6864 emit_int16 (acfg, 0);
6868 /* Emit the names */
6869 for (i = 0; i < acfg->globals->len; ++i) {
6870 char *name = g_ptr_array_index (acfg->globals, i);
6872 sprintf (symbol, "name_%d", i);
6873 emit_section_change (acfg, RODATA_SECT, 1);
6875 emit_alignment (acfg, 4);
6877 emit_label (acfg, symbol);
6878 emit_string (acfg, name);
6881 /* Emit the globals table */
6882 sprintf (symbol, "globals");
6883 emit_section_change (acfg, ".data", 0);
6884 /* This is not a global, since it is accessed by the init function */
6885 emit_alignment (acfg, 8);
6886 emit_label (acfg, symbol);
6888 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6889 emit_pointer (acfg, symbol);
6891 for (i = 0; i < acfg->globals->len; ++i) {
6892 char *name = g_ptr_array_index (acfg->globals, i);
6894 sprintf (symbol, "name_%d", i);
6895 emit_pointer (acfg, symbol);
6897 sprintf (symbol, "%s", name);
6898 emit_pointer (acfg, symbol);
6900 /* Null terminate the table */
6901 emit_int32 (acfg, 0);
6902 emit_int32 (acfg, 0);
6906 emit_autoreg (MonoAotCompile *acfg)
6911 * Emit a function into the .ctor section which will be called by the ELF
6912 * loader to register this module with the runtime.
6914 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6917 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6919 arch_emit_autoreg (acfg, symbol);
6925 emit_mem_end (MonoAotCompile *acfg)
6929 sprintf (symbol, "mem_end");
6930 emit_section_change (acfg, ".text", 1);
6931 emit_alignment (acfg, 8);
6932 emit_label (acfg, symbol);
6936 * Emit a structure containing all the information not stored elsewhere.
6939 emit_file_info (MonoAotCompile *acfg)
6944 const char *gc_name;
6947 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6949 if (acfg->aot_opts.bind_to_runtime_version) {
6950 build_info = mono_get_runtime_build_info ();
6951 emit_string_symbol (acfg, "runtime_version", build_info);
6952 g_free (build_info);
6954 emit_string_symbol (acfg, "runtime_version", "");
6957 /* Emit a string holding the assembly name */
6958 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6961 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6964 gc_name = mono_gc_get_gc_name ();
6965 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6967 sprintf (symbol, "mono_aot_file_info");
6968 emit_section_change (acfg, ".data", 0);
6969 emit_alignment (acfg, 8);
6970 emit_label (acfg, symbol);
6971 if (!acfg->aot_opts.static_link)
6972 emit_global (acfg, symbol, FALSE);
6974 /* The data emitted here must match MonoAotFileInfo. */
6976 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6977 emit_int32 (acfg, 0);
6980 * We emit pointers to our data structures instead of emitting global symbols which
6981 * point to them, to reduce the number of globals, and because using globals leads to
6982 * various problems (i.e. arm/thumb).
6984 emit_pointer (acfg, acfg->got_symbol);
6985 emit_pointer (acfg, "methods");
6988 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6990 emit_pointer (acfg, "mono_eh_frame");
6992 emit_pointer (acfg, NULL);
6994 emit_pointer (acfg, "blob");
6995 emit_pointer (acfg, "class_name_table");
6996 emit_pointer (acfg, "class_info_offsets");
6997 emit_pointer (acfg, "method_info_offsets");
6998 emit_pointer (acfg, "ex_info_offsets");
6999 emit_pointer (acfg, "code_offsets");
7000 emit_pointer (acfg, "extra_method_info_offsets");
7001 emit_pointer (acfg, "extra_method_table");
7002 emit_pointer (acfg, "got_info_offsets");
7003 emit_pointer (acfg, "methods_end");
7004 emit_pointer (acfg, "unwind_info");
7005 emit_pointer (acfg, "mem_end");
7006 emit_pointer (acfg, "image_table");
7007 emit_pointer (acfg, "plt");
7008 emit_pointer (acfg, "plt_end");
7009 emit_pointer (acfg, "assembly_guid");
7010 emit_pointer (acfg, "runtime_version");
7011 if (acfg->num_trampoline_got_entries) {
7012 emit_pointer (acfg, "specific_trampolines");
7013 emit_pointer (acfg, "static_rgctx_trampolines");
7014 emit_pointer (acfg, "imt_thunks");
7016 emit_pointer (acfg, NULL);
7017 emit_pointer (acfg, NULL);
7018 emit_pointer (acfg, NULL);
7020 if (acfg->thumb_mixed) {
7021 emit_pointer (acfg, "thumb_end");
7023 emit_pointer (acfg, NULL);
7025 if (acfg->aot_opts.static_link) {
7026 emit_pointer (acfg, "globals");
7028 emit_pointer (acfg, NULL);
7030 emit_pointer (acfg, "assembly_name");
7031 emit_pointer (acfg, "unbox_trampolines");
7032 emit_pointer (acfg, "unbox_trampolines_end");
7034 emit_int32 (acfg, acfg->plt_got_offset_base);
7035 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7036 emit_int32 (acfg, acfg->plt_offset);
7037 emit_int32 (acfg, acfg->nmethods);
7038 emit_int32 (acfg, acfg->flags);
7039 emit_int32 (acfg, acfg->opts);
7040 emit_int32 (acfg, acfg->simd_opts);
7041 emit_int32 (acfg, gc_name_offset);
7043 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7044 emit_int32 (acfg, acfg->num_trampolines [i]);
7045 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7046 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7047 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7048 emit_int32 (acfg, acfg->trampoline_size [i]);
7050 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7055 t.type = MONO_TYPE_R8;
7056 mono_type_size (&t, &align);
7058 emit_int32 (acfg, align);
7060 t.type = MONO_TYPE_I8;
7061 mono_type_size (&t, &align);
7063 emit_int32 (acfg, align);
7066 emit_int32 (acfg, __alignof__ (double));
7067 emit_int32 (acfg, __alignof__ (gint64));
7070 if (acfg->aot_opts.static_link) {
7074 * Emit a global symbol which can be passed by an embedding app to
7075 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7078 #if defined(TARGET_MACH) && !defined(__native_client_codegen__)
7079 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7081 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7084 /* Get rid of characters which cannot occur in symbols */
7086 for (p = symbol; *p; ++p) {
7087 if (!(isalnum (*p) || *p == '_'))
7090 acfg->static_linking_symbol = g_strdup (symbol);
7091 emit_global_inner (acfg, symbol, FALSE);
7092 emit_label (acfg, symbol);
7093 emit_pointer (acfg, "mono_aot_file_info");
7098 emit_blob (MonoAotCompile *acfg)
7102 sprintf (symbol, "blob");
7103 emit_section_change (acfg, RODATA_SECT, 1);
7104 emit_alignment (acfg, 8);
7105 emit_label (acfg, symbol);
7107 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7111 emit_dwarf_info (MonoAotCompile *acfg)
7113 #ifdef EMIT_DWARF_INFO
7115 char symbol [128], symbol2 [128];
7117 /* DIEs for methods */
7118 for (i = 0; i < acfg->nmethods; ++i) {
7119 MonoCompile *cfg = acfg->cfgs [i];
7124 // FIXME: LLVM doesn't define .Lme_...
7125 if (cfg->compile_llvm)
7128 sprintf (symbol, "%s", cfg->asm_symbol);
7129 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7131 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
7137 collect_methods (MonoAotCompile *acfg)
7140 MonoImage *image = acfg->image;
7142 /* Collect methods */
7143 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7145 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7147 method = mono_get_method (acfg->image, token, NULL);
7150 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7154 /* Load all methods eagerly to skip the slower lazy loading code */
7155 mono_class_setup_methods (method->klass);
7157 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7158 /* Compile the wrapper instead */
7159 /* We do this here instead of add_wrappers () because it is easy to do it here */
7160 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7164 /* FIXME: Some mscorlib methods don't have debug info */
7166 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7167 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7168 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7169 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7170 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7171 if (!mono_debug_lookup_method (method)) {
7172 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7179 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7180 add_method_with_index (acfg, method, i, FALSE);
7181 acfg->method_index ++;
7184 add_generic_instances (acfg);
7186 if (acfg->aot_opts.full_aot)
7187 add_wrappers (acfg);
7191 compile_methods (MonoAotCompile *acfg)
7195 if (acfg->aot_opts.nthreads > 0) {
7200 gpointer *user_data;
7201 MonoMethod **methods;
7203 methods_len = acfg->methods->len;
7205 len = acfg->methods->len / acfg->aot_opts.nthreads;
7208 * Partition the list of methods into fragments, and hand it to threads to
7211 threads = g_ptr_array_new ();
7212 /* Make a copy since acfg->methods is modified by compile_method () */
7213 methods = g_new0 (MonoMethod*, methods_len);
7214 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7215 for (i = 0; i < methods_len; ++i)
7216 methods [i] = g_ptr_array_index (acfg->methods, i);
7218 while (i < methods_len) {
7219 frag = g_ptr_array_new ();
7220 for (j = 0; j < len; ++j) {
7221 if (i < methods_len) {
7222 g_ptr_array_add (frag, methods [i]);
7227 user_data = g_new0 (gpointer, 3);
7228 user_data [0] = mono_domain_get ();
7229 user_data [1] = acfg;
7230 user_data [2] = frag;
7232 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7233 g_ptr_array_add (threads, handle);
7237 for (i = 0; i < threads->len; ++i) {
7238 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7244 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7245 for (i = methods_len; i < acfg->methods->len; ++i) {
7246 /* This can new methods to acfg->methods */
7247 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7252 compile_asm (MonoAotCompile *acfg)
7254 char *command, *objfile;
7255 char *outfile_name, *tmp_outfile_name;
7256 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7258 #if defined(TARGET_AMD64)
7259 #define AS_OPTIONS "--64"
7260 #elif defined(TARGET_POWERPC64)
7261 #define AS_OPTIONS "-a64 -mppc64"
7262 #define LD_OPTIONS "-m elf64ppc"
7263 #elif defined(sparc) && SIZEOF_VOID_P == 8
7264 #define AS_OPTIONS "-xarch=v9"
7265 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7266 #define AS_OPTIONS "-arch i386 -W"
7268 #define AS_OPTIONS ""
7271 #ifdef __native_client_codegen__
7272 #if defined(TARGET_AMD64)
7273 #define AS_NAME "nacl64-as"
7275 #define AS_NAME "nacl-as"
7278 #define AS_NAME "as"
7282 #define LD_OPTIONS ""
7285 #define EH_LD_OPTIONS ""
7287 if (acfg->aot_opts.asm_only) {
7288 printf ("Output file: '%s'.\n", acfg->tmpfname);
7289 if (acfg->aot_opts.static_link)
7290 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7294 if (acfg->aot_opts.static_link) {
7295 if (acfg->aot_opts.outfile)
7296 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7298 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7300 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7302 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);
7303 printf ("Executing the native assembler: %s\n", command);
7304 if (system (command) != 0) {
7312 if (acfg->aot_opts.static_link) {
7313 printf ("Output file: '%s'.\n", objfile);
7314 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7319 if (acfg->aot_opts.outfile)
7320 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7322 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7324 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7327 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7328 #elif defined(__ppc__) && defined(TARGET_MACH)
7329 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7330 #elif defined(HOST_WIN32)
7331 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7332 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7333 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7335 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7337 printf ("Executing the native linker: %s\n", command);
7338 if (system (command) != 0) {
7339 g_free (tmp_outfile_name);
7340 g_free (outfile_name);
7348 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7349 printf ("Stripping the binary: %s\n", com);
7353 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
7355 * gas generates 'mapping symbols' each time code and data is mixed, which
7356 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7358 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7359 printf ("Stripping the binary: %s\n", command);
7360 if (system (command) != 0) {
7361 g_free (tmp_outfile_name);
7362 g_free (outfile_name);
7369 rename (tmp_outfile_name, outfile_name);
7371 #if defined(TARGET_MACH)
7372 command = g_strdup_printf ("dsymutil %s", outfile_name);
7373 printf ("Generating debug symbols: %s\n", command);
7374 if (system (command) != 0) {
7379 if (!acfg->aot_opts.save_temps)
7382 g_free (tmp_outfile_name);
7383 g_free (outfile_name);
7386 if (acfg->aot_opts.save_temps)
7387 printf ("Retained input file.\n");
7389 unlink (acfg->tmpfname);
7394 static MonoAotCompile*
7395 acfg_create (MonoAssembly *ass, guint32 opts)
7397 MonoImage *image = ass->image;
7398 MonoAotCompile *acfg;
7401 acfg = g_new0 (MonoAotCompile, 1);
7402 acfg->methods = g_ptr_array_new ();
7403 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7404 acfg->method_depth = g_hash_table_new (NULL, NULL);
7405 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7406 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7407 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7408 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7409 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7410 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7411 acfg->got_patches = g_ptr_array_new ();
7412 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7413 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7414 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7415 acfg->image_hash = g_hash_table_new (NULL, NULL);
7416 acfg->image_table = g_ptr_array_new ();
7417 acfg->globals = g_ptr_array_new ();
7418 acfg->image = image;
7420 /* TODO: Write out set of SIMD instructions used, rather than just those available */
7421 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
7422 acfg->mempool = mono_mempool_new ();
7423 acfg->extra_methods = g_ptr_array_new ();
7424 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7425 acfg->unwind_ops = g_ptr_array_new ();
7426 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7427 acfg->method_order = g_ptr_array_new ();
7428 acfg->export_names = g_hash_table_new (NULL, NULL);
7429 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7430 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7431 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7432 InitializeCriticalSection (&acfg->mutex);
7438 acfg_free (MonoAotCompile *acfg)
7442 img_writer_destroy (acfg->w);
7443 for (i = 0; i < acfg->nmethods; ++i)
7445 g_free (acfg->cfgs [i]);
7446 g_free (acfg->cfgs);
7447 g_free (acfg->static_linking_symbol);
7448 g_free (acfg->got_symbol);
7449 g_free (acfg->plt_symbol);
7450 g_ptr_array_free (acfg->methods, TRUE);
7451 g_ptr_array_free (acfg->got_patches, TRUE);
7452 g_ptr_array_free (acfg->image_table, TRUE);
7453 g_ptr_array_free (acfg->globals, TRUE);
7454 g_ptr_array_free (acfg->unwind_ops, TRUE);
7455 g_hash_table_destroy (acfg->method_indexes);
7456 g_hash_table_destroy (acfg->method_depth);
7457 g_hash_table_destroy (acfg->plt_offset_to_entry);
7458 g_hash_table_destroy (acfg->patch_to_plt_entry);
7459 g_hash_table_destroy (acfg->patch_to_got_offset);
7460 g_hash_table_destroy (acfg->method_to_cfg);
7461 g_hash_table_destroy (acfg->token_info_hash);
7462 g_hash_table_destroy (acfg->method_to_pinvoke_import);
7463 g_hash_table_destroy (acfg->image_hash);
7464 g_hash_table_destroy (acfg->unwind_info_offsets);
7465 g_hash_table_destroy (acfg->method_label_hash);
7466 g_hash_table_destroy (acfg->export_names);
7467 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7468 g_hash_table_destroy (acfg->klass_blob_hash);
7469 g_hash_table_destroy (acfg->method_blob_hash);
7470 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7471 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7472 g_free (acfg->patch_to_got_offset_by_type);
7473 mono_mempool_destroy (acfg->mempool);
7478 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7480 MonoImage *image = ass->image;
7482 MonoAotCompile *acfg;
7483 char *outfile_name, *tmp_outfile_name, *p;
7487 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7489 acfg = acfg_create (ass, opts);
7491 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7492 acfg->aot_opts.write_symbols = TRUE;
7493 acfg->aot_opts.ntrampolines = 1024;
7494 acfg->aot_opts.nrgctx_trampolines = 1024;
7495 acfg->aot_opts.nimt_trampolines = 128;
7496 acfg->aot_opts.llvm_path = g_strdup ("");
7498 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7500 if (acfg->aot_opts.static_link)
7501 acfg->aot_opts.autoreg = TRUE;
7503 //acfg->aot_opts.print_skipped_methods = TRUE;
7505 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7506 if (acfg->aot_opts.full_aot) {
7507 printf ("--aot=full is not supported on this platform.\n");
7512 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7513 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7517 if (acfg->aot_opts.static_link)
7518 acfg->aot_opts.asm_writer = TRUE;
7520 if (acfg->aot_opts.soft_debug) {
7521 MonoDebugOptions *opt = mini_get_debug_options ();
7523 opt->mdb_optimizations = TRUE;
7524 opt->gen_seq_points = TRUE;
7526 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7527 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7530 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7533 if (mono_use_llvm) {
7535 acfg->aot_opts.asm_writer = TRUE;
7536 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7538 if (acfg->aot_opts.soft_debug) {
7539 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7544 if (acfg->aot_opts.full_aot)
7545 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7547 load_profile_files (acfg);
7549 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7550 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7551 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7553 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7555 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7559 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7560 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7561 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7563 /* Get rid of characters which cannot occur in symbols */
7564 for (p = acfg->got_symbol_base; *p; ++p) {
7565 if (!(isalnum (*p) || *p == '_'))
7568 for (p = acfg->plt_symbol; *p; ++p) {
7569 if (!(isalnum (*p) || *p == '_'))
7572 for (p = acfg->assembly_name_sym; *p; ++p) {
7573 if (!(isalnum (*p) || *p == '_'))
7577 acfg->method_index = 1;
7579 collect_methods (acfg);
7581 acfg->cfgs_size = acfg->methods->len + 32;
7582 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7584 /* PLT offset 0 is reserved for the PLT trampoline */
7585 acfg->plt_offset = 1;
7590 mono_llvm_create_aot_module (acfg->got_symbol_base);
7594 /* GOT offset 0 is reserved for the address of the current assembly */
7598 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7599 ji->type = MONO_PATCH_INFO_IMAGE;
7600 ji->data.image = acfg->image;
7602 get_got_offset (acfg, ji);
7604 /* Slot 1 is reserved for the mscorlib got addr */
7605 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7606 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7607 get_got_offset (acfg, ji);
7609 /* This is very common */
7610 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7611 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7612 get_got_offset (acfg, ji);
7617 compile_methods (acfg);
7621 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7627 if (acfg->aot_opts.asm_only) {
7628 if (acfg->aot_opts.outfile)
7629 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7631 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7633 acfg->tmpfname = g_strdup ("temp.s");
7636 emit_llvm_file (acfg);
7640 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7641 if (acfg->aot_opts.outfile)
7642 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7644 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7647 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7648 * it might be in another file system so the rename () won't work.
7650 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7652 acfg->fp = fopen (tmp_outfile_name, "w");
7654 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7658 acfg->w = img_writer_create (acfg->fp, TRUE);
7659 acfg->use_bin_writer = TRUE;
7662 /* Append to the .s file created by llvm */
7663 /* FIXME: Use multiple files instead */
7664 acfg->fp = fopen (acfg->tmpfname, "a+");
7666 if (acfg->aot_opts.asm_only) {
7667 if (acfg->aot_opts.outfile)
7668 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7670 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7671 acfg->fp = fopen (acfg->tmpfname, "w+");
7673 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7674 acfg->fp = fdopen (i, "w+");
7676 if (acfg->fp == 0) {
7677 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7681 acfg->w = img_writer_create (acfg->fp, FALSE);
7683 tmp_outfile_name = NULL;
7684 outfile_name = NULL;
7687 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7689 /* Compute symbols for methods */
7690 for (i = 0; i < acfg->nmethods; ++i) {
7691 if (acfg->cfgs [i]) {
7692 MonoCompile *cfg = acfg->cfgs [i];
7693 int method_index = get_method_index (acfg, cfg->orig_method);
7695 if (COMPILE_LLVM (cfg))
7696 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7698 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7702 if (!acfg->aot_opts.nodebug)
7703 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7705 img_writer_emit_start (acfg->w);
7708 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7710 if (acfg->thumb_mixed) {
7713 * This global symbol marks the end of THUMB code, and the beginning of ARM
7714 * code generated by our JIT.
7716 sprintf (symbol, "thumb_end");
7717 emit_section_change (acfg, ".text", 0);
7718 emit_alignment (acfg, 8);
7719 emit_label (acfg, symbol);
7720 emit_zero_bytes (acfg, 16);
7722 fprintf (acfg->fp, ".arm\n");
7729 emit_extra_methods (acfg);
7731 emit_trampolines (acfg);
7733 emit_class_name_table (acfg);
7735 emit_got_info (acfg);
7737 emit_exception_info (acfg);
7739 emit_unwind_info (acfg);
7741 emit_class_info (acfg);
7745 emit_image_table (acfg);
7749 emit_file_info (acfg);
7753 emit_globals (acfg);
7755 emit_autoreg (acfg);
7758 emit_dwarf_info (acfg);
7759 mono_dwarf_writer_close (acfg->dwarf);
7762 emit_mem_end (acfg);
7764 if (acfg->need_pt_gnu_stack) {
7765 /* This is required so the .so doesn't have an executable stack */
7766 /* The bin writer already emits this */
7767 if (!acfg->use_bin_writer)
7768 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7773 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7776 g_assert (acfg->got_offset <= acfg->final_got_size);
7778 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);
7779 printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
7780 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
7781 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
7782 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7783 if (acfg->stats.genericcount)
7784 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7785 if (acfg->stats.abscount)
7786 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7787 if (acfg->stats.lmfcount)
7788 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7789 if (acfg->stats.ocount)
7790 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7792 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7795 res = img_writer_emit_writeout (acfg->w);
7800 if (acfg->use_bin_writer) {
7801 int err = rename (tmp_outfile_name, outfile_name);
7804 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7808 res = compile_asm (acfg);
7815 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7817 if (acfg->aot_opts.stats) {
7820 printf ("GOT slot distribution:\n");
7821 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7822 if (acfg->stats.got_slot_types [i])
7823 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7826 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);
7838 mono_aot_readonly_field_override (MonoClassField *field)
7844 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)