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"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
74 #define RODATA_SECT ".text"
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__APPLE__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
88 #define SHARED_EXT ".so"
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
95 /* predefined values for static readonly fields without needed to run the .cctor */
96 typedef struct _ReadOnlyValue ReadOnlyValue;
97 struct _ReadOnlyValue {
100 int type; /* to be used later for typechecking to prevent user errors */
109 static ReadOnlyValue *readonly_values = NULL;
111 typedef struct MonoAotOptions {
114 gboolean write_symbols;
115 gboolean metadata_only;
116 gboolean bind_to_runtime_version;
119 gboolean static_link;
124 gboolean log_generics;
127 int nrgctx_trampolines;
128 int nimt_trampolines;
129 gboolean print_skipped_methods;
137 typedef struct MonoAotStats {
138 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
139 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
140 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
141 int got_slots, offsets_size;
142 int got_slot_types [MONO_PATCH_INFO_NONE];
143 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
144 int jit_time, gen_time, link_time;
147 typedef struct MonoAotCompile {
150 GHashTable *method_indexes;
151 GHashTable *method_depth;
154 GHashTable *patch_to_plt_entry;
155 GHashTable *plt_offset_to_entry;
156 GHashTable *patch_to_got_offset;
157 GHashTable **patch_to_got_offset_by_type;
158 GPtrArray *got_patches;
159 GHashTable *image_hash;
160 GHashTable *method_to_cfg;
161 GHashTable *token_info_hash;
162 GPtrArray *extra_methods;
163 GPtrArray *image_table;
165 GPtrArray *method_order;
166 GHashTable *export_names;
167 /* Maps MonoClass* -> blob offset */
168 GHashTable *klass_blob_hash;
169 /* Maps MonoMethod* -> blob offset */
170 GHashTable *method_blob_hash;
171 guint32 *plt_got_info_offsets;
172 guint32 got_offset, plt_offset, plt_got_offset_base;
173 guint32 final_got_size;
174 /* Number of GOT entries reserved for trampolines */
175 guint32 num_trampoline_got_entries;
177 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
178 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
179 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
181 MonoAotOptions aot_opts;
184 MonoMemPool *mempool;
187 char *static_linking_symbol;
188 CRITICAL_SECTION mutex;
189 gboolean use_bin_writer;
191 MonoDwarfWriter *dwarf;
195 GHashTable *unwind_info_offsets;
196 GPtrArray *unwind_ops;
197 guint32 unwind_info_offset;
198 char *got_symbol_base;
201 GHashTable *method_label_hash;
202 const char *temp_prefix;
203 const char *llvm_label_prefix;
204 guint32 label_generator;
206 MonoAotFileFlags flags;
207 MonoDynamicStream blob;
208 MonoClass **typespec_classes;
211 char *assembly_name_sym;
212 GHashTable *plt_entry_debug_sym_cache;
213 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
214 GHashTable *ginst_hash;
219 char *symbol, *llvm_symbol, *debug_sym;
221 gboolean jit_used, llvm_used;
224 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
225 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
227 /* This points to the current acfg in LLVM mode */
228 static MonoAotCompile *llvm_acfg;
230 #ifdef HAVE_ARRAY_ELEM_INIT
231 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
232 #define MSGSTRFIELD1(line) str##line
233 static const struct msgstr_t {
234 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
235 #include "patch-info.h"
238 #define PATCH_INFO(a,b) b,
239 #include "patch-info.h"
242 static const gint16 opidx [] = {
243 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
244 #include "patch-info.h"
248 static G_GNUC_UNUSED const char*
249 get_patch_name (int info)
251 return (const char*)&opstr + opidx [info];
255 #define PATCH_INFO(a,b) b,
256 static const char* const
257 patch_types [MONO_PATCH_INFO_NUM + 1] = {
258 #include "patch-info.h"
262 static G_GNUC_UNUSED const char*
263 get_patch_name (int info)
265 return patch_types [info];
271 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
273 /* Wrappers around the image writer functions */
276 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
278 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
282 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
284 img_writer_emit_push_section (acfg->w, section_name, subsection);
288 emit_pop_section (MonoAotCompile *acfg)
290 img_writer_emit_pop_section (acfg->w);
294 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
296 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
300 emit_label (MonoAotCompile *acfg, const char *name)
302 img_writer_emit_label (acfg->w, name);
306 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
308 img_writer_emit_bytes (acfg->w, buf, size);
312 emit_string (MonoAotCompile *acfg, const char *value)
314 img_writer_emit_string (acfg->w, value);
318 emit_line (MonoAotCompile *acfg)
320 img_writer_emit_line (acfg->w);
324 emit_alignment (MonoAotCompile *acfg, int size)
326 img_writer_emit_alignment (acfg->w, size);
330 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
332 img_writer_emit_pointer_unaligned (acfg->w, target);
336 emit_pointer (MonoAotCompile *acfg, const char *target)
338 img_writer_emit_pointer (acfg->w, target);
342 emit_int16 (MonoAotCompile *acfg, int value)
344 img_writer_emit_int16 (acfg->w, value);
348 emit_int32 (MonoAotCompile *acfg, int value)
350 img_writer_emit_int32 (acfg->w, value);
354 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
356 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
360 emit_zero_bytes (MonoAotCompile *acfg, int num)
362 img_writer_emit_zero_bytes (acfg->w, num);
366 emit_byte (MonoAotCompile *acfg, guint8 val)
368 img_writer_emit_byte (acfg->w, val);
371 #ifdef __native_client_codegen__
373 emit_nacl_call_alignment (MonoAotCompile *acfg)
375 img_writer_emit_nacl_call_alignment (acfg->w);
379 static G_GNUC_UNUSED void
380 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
382 img_writer_emit_global (acfg->w, name, func);
386 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
388 if (acfg->aot_opts.no_dlsym) {
389 g_ptr_array_add (acfg->globals, g_strdup (name));
390 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
392 img_writer_emit_global (acfg->w, name, func);
397 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
399 img_writer_emit_symbol_size (acfg->w, name, end_label);
403 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
405 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
407 /* On apple, all symbols need to be aligned to avoid warnings from ld */
408 emit_alignment (acfg, 4);
410 img_writer_emit_label (acfg->w, name);
411 img_writer_emit_string (acfg->w, value);
414 static G_GNUC_UNUSED void
415 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
418 guint8 b = value & 0x7f;
420 if (value != 0) /* more bytes to come */
426 static G_GNUC_UNUSED void
427 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
430 gboolean negative = (value < 0);
437 /* the following is unnecessary if the
438 * implementation of >>= uses an arithmetic rather
439 * than logical shift for a signed left operand
443 value |= - ((gint64)1 <<(size - 7));
444 /* sign bit of byte is second high order bit (0x40) */
445 if ((value == 0 && !(byte & 0x40)) ||
446 (value == -1 && (byte & 0x40)))
450 emit_byte (acfg, byte);
454 static G_GNUC_UNUSED void
455 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
460 guint8 b = value & 0x7f;
462 if (value != 0) /* more bytes to come */
470 static G_GNUC_UNUSED void
471 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
474 gboolean negative = (value < 0);
482 /* the following is unnecessary if the
483 * implementation of >>= uses an arithmetic rather
484 * than logical shift for a signed left operand
488 value |= - (1 <<(size - 7));
489 /* sign bit of byte is second high order bit (0x40) */
490 if ((value == 0 && !(byte & 0x40)) ||
491 (value == -1 && (byte & 0x40)))
501 /* ARCHITECTURE SPECIFIC CODE */
503 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
504 #define EMIT_DWARF_INFO 1
507 #if defined(TARGET_ARM)
508 #define AOT_FUNC_ALIGNMENT 4
510 #define AOT_FUNC_ALIGNMENT 16
512 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
513 #undef AOT_FUNC_ALIGNMENT
514 #define AOT_FUNC_ALIGNMENT 32
517 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
518 #define PPC_LD_OP "ld"
519 #define PPC_LDX_OP "ldx"
521 #define PPC_LD_OP "lwz"
522 #define PPC_LDX_OP "lwzx"
526 #define AOT_TARGET_STR "AMD64"
531 #define AOT_TARGET_STR "ARM (MACH)"
533 #define AOT_TARGET_STR "ARM (!MACH)"
537 #ifdef TARGET_POWERPC64
538 #ifdef __mono_ilp32__
539 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
541 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
544 #ifdef TARGET_POWERPC
545 #ifdef __mono_ilp32__
546 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
548 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
555 #define AOT_TARGET_STR "X86 (WIN32)"
556 #elif defined(__native_client_codegen__)
557 #define AOT_TARGET_STR "X86 (native client codegen)"
559 #define AOT_TARGET_STR "X86 (!native client codegen)"
563 #ifndef AOT_TARGET_STR
564 #define AOT_TARGET_STR ""
568 arch_init (MonoAotCompile *acfg)
570 acfg->llc_args = g_string_new ("");
571 acfg->as_args = g_string_new ("");
574 * The prefix LLVM likes to put in front of symbol names on darwin.
575 * The mach-os specs require this for globals, but LLVM puts them in front of all
576 * symbols. We need to handle this, since we need to refer to LLVM generated
579 acfg->llvm_label_prefix = "";
582 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
583 g_string_append (acfg->llc_args, "-mattr=+v6");
586 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
587 g_string_append (acfg->as_args, " -mfpu=vfp3");
589 g_string_append (acfg->llc_args, " -soft-float");
592 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
593 acfg->thumb_mixed = TRUE;
595 if (acfg->aot_opts.mtriple)
596 mono_arch_set_target (acfg->aot_opts.mtriple);
600 acfg->llvm_label_prefix = "_";
601 acfg->need_no_dead_strip = TRUE;
604 #if defined(__linux__) && !defined(TARGET_ARM)
605 acfg->need_pt_gnu_stack = TRUE;
610 * arch_emit_direct_call:
612 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
616 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
618 #if defined(TARGET_X86) || defined(TARGET_AMD64)
619 /* Need to make sure this is exactly 5 bytes long */
620 emit_byte (acfg, '\xe8');
621 emit_symbol_diff (acfg, target, ".", -4);
623 #elif defined(TARGET_ARM)
624 if (acfg->use_bin_writer) {
631 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
632 emit_bytes (acfg, buf, 4);
634 img_writer_emit_unset_mode (acfg->w);
635 fprintf (acfg->fp, "bl %s\n", target);
638 #elif defined(TARGET_POWERPC)
639 if (acfg->use_bin_writer) {
640 g_assert_not_reached ();
642 img_writer_emit_unset_mode (acfg->w);
643 fprintf (acfg->fp, "bl %s\n", target);
647 g_assert_not_reached ();
653 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
655 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
656 * in in the 2. slot of every GOT, and require every method to place the GOT
657 * address in r30, even when it doesn't access the GOT otherwise. This way,
658 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
663 * PPC64 uses function descriptors which greatly complicate all code, since
664 * these are used very inconsistently in the runtime. Some functions like
665 * mono_compile_method () return ftn descriptors, while others like the
666 * trampoline creation functions do not.
667 * We assume that all GOT slots contain function descriptors, and create
668 * descriptors in aot-runtime.c when needed.
669 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
670 * from function descriptors, we could do the same, but it would require
671 * rewriting all the ppc/aot code to handle function descriptors properly.
672 * So instead, we use the same approach as on PPC32.
673 * This is a horrible mess, but fixing it would probably lead to an even bigger
679 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
682 #ifdef MONO_ARCH_AOT_SUPPORTED
684 * arch_emit_got_offset:
686 * The memory pointed to by CODE should hold native code for computing the GOT
687 * address. Emit this code while patching it with the offset between code and
688 * the GOT. CODE_SIZE is set to the number of bytes emitted.
691 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
693 #if defined(TARGET_POWERPC64)
694 g_assert (!acfg->use_bin_writer);
695 img_writer_emit_unset_mode (acfg->w);
697 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
698 * unsupported relocations. So we store the got address into the .Lgot_addr
699 * symbol which is in the text segment, compute its address, and load it.
701 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
702 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
703 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
704 fprintf (acfg->fp, "add 30, 30, 0\n");
705 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
706 acfg->label_generator ++;
708 #elif defined(TARGET_POWERPC)
709 g_assert (!acfg->use_bin_writer);
710 img_writer_emit_unset_mode (acfg->w);
711 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
712 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
713 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
714 acfg->label_generator ++;
717 guint32 offset = mono_arch_get_patch_offset (code);
718 emit_bytes (acfg, code, offset);
719 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
721 *code_size = offset + 4;
726 * arch_emit_got_access:
728 * The memory pointed to by CODE should hold native code for loading a GOT
729 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
730 * CODE_SIZE is set to the number of bytes emitted.
733 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
735 /* Emit beginning of instruction */
736 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
738 /* Emit the offset */
740 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
741 *code_size = mono_arch_get_patch_offset (code) + 4;
742 #elif defined(TARGET_X86)
743 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
744 *code_size = mono_arch_get_patch_offset (code) + 4;
745 #elif defined(TARGET_ARM)
746 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
747 *code_size = mono_arch_get_patch_offset (code) + 4;
748 #elif defined(TARGET_POWERPC)
754 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
755 g_assert (code - buf == 8);
756 emit_bytes (acfg, buf, code - buf);
757 *code_size = code - buf;
760 g_assert_not_reached ();
767 * arch_emit_plt_entry:
769 * Emit code for the PLT entry with index INDEX.
772 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
774 #if defined(TARGET_X86)
775 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
776 #if defined(__default_codegen__)
777 /* jmp *<offset>(%ebx) */
778 emit_byte (acfg, 0xff);
779 emit_byte (acfg, 0xa3);
780 emit_int32 (acfg, offset);
781 /* Used by mono_aot_get_plt_info_offset */
782 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
783 #elif defined(__native_client_codegen__)
784 const guint8 kSizeOfNaClJmp = 11;
785 guint8 bytes[kSizeOfNaClJmp];
786 guint8 *pbytes = &bytes[0];
788 x86_jump_membase32 (pbytes, X86_EBX, offset);
789 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
790 /* four bytes of data, used by mono_arch_patch_plt_entry */
791 /* For Native Client, make this work with data embedded in push. */
792 emit_byte (acfg, 0x68); /* hide data in a push */
793 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
794 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
795 #endif /*__native_client_codegen__*/
796 #elif defined(TARGET_AMD64)
797 #if defined(__default_codegen__)
799 * We can't emit jumps because they are 32 bits only so they can't be patched.
800 * So we make indirect calls through GOT entries which are patched by the AOT
801 * loader to point to .Lpd entries.
803 /* jmpq *<offset>(%rip) */
804 emit_byte (acfg, '\xff');
805 emit_byte (acfg, '\x25');
806 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
807 /* Used by mono_aot_get_plt_info_offset */
808 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
809 #elif defined(__native_client_codegen__)
811 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
812 guint8 *code = buf_aligned;
814 /* mov <OFFSET>(%rip), %r11d */
815 emit_byte (acfg, '\x45');
816 emit_byte (acfg, '\x8b');
817 emit_byte (acfg, '\x1d');
818 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
820 amd64_jump_reg (code, AMD64_R11);
821 /* This should be constant for the plt patch */
822 g_assert ((size_t)(code-buf_aligned) == 10);
823 emit_bytes (acfg, buf_aligned, code - buf_aligned);
825 /* Hide data in a push imm32 so it passes validation */
826 emit_byte (acfg, 0x68); /* push */
827 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
828 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
829 #endif /*__native_client_codegen__*/
830 #elif defined(TARGET_ARM)
835 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
836 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
837 emit_bytes (acfg, buf, code - buf);
838 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
839 /* Used by mono_aot_get_plt_info_offset */
840 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
841 #elif defined(TARGET_POWERPC)
842 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
844 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
845 g_assert (!acfg->use_bin_writer);
846 img_writer_emit_unset_mode (acfg->w);
847 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
848 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
849 fprintf (acfg->fp, "add 11, 11, 30\n");
850 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
851 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
852 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
853 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
855 fprintf (acfg->fp, "mtctr 11\n");
856 fprintf (acfg->fp, "bctr\n");
857 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
859 g_assert_not_reached ();
864 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
866 #if defined(TARGET_ARM)
868 /* LLVM calls the PLT entries using bl, so emit a stub */
869 /* FIXME: Too much overhead on every call */
870 fprintf (acfg->fp, ".thumb_func\n");
871 fprintf (acfg->fp, "bx pc\n");
872 fprintf (acfg->fp, "nop\n");
873 fprintf (acfg->fp, ".arm\n");
875 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
876 /* The caller already transitioned to thumb */
877 /* The code below should be 12 bytes long */
878 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
879 /* thumb can't encode ld pc, [pc, ip] */
880 fprintf (acfg->fp, "add ip, pc, ip\n");
881 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
882 fprintf (acfg->fp, "bx ip\n");
883 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
884 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
886 g_assert_not_reached ();
891 * arch_emit_specific_trampoline:
893 * Emit code for a specific trampoline. OFFSET is the offset of the first of
894 * two GOT slots which contain the generic trampoline address and the trampoline
895 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
898 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
901 * The trampolines created here are variations of the specific
902 * trampolines created in mono_arch_create_specific_trampoline (). The
904 * - the generic trampoline address is taken from a got slot.
905 * - the offset of the got slot where the trampoline argument is stored
906 * is embedded in the instruction stream, and the generic trampoline
907 * can load the argument by loading the offset, adding it to the
908 * address of the trampoline to get the address of the got slot, and
909 * loading the argument from there.
910 * - all the trampolines should be of the same length.
912 #if defined(TARGET_AMD64)
913 #if defined(__default_codegen__)
914 /* This should be exactly 16 bytes long */
916 /* call *<offset>(%rip) */
917 emit_byte (acfg, '\x41');
918 emit_byte (acfg, '\xff');
919 emit_byte (acfg, '\x15');
920 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
921 /* This should be relative to the start of the trampoline */
922 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
923 emit_zero_bytes (acfg, 5);
924 #elif defined(__native_client_codegen__)
926 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
927 guint8 *code = buf_aligned;
932 /* Emit this call in 'code' so we can find out how long it is. */
933 amd64_call_reg (code, AMD64_R11);
934 call_start = mono_arch_nacl_skip_nops (buf_aligned);
935 call_len = code - call_start;
937 /* The tramp_size is twice the NaCl alignment because it starts with */
938 /* a call which needs to be aligned to the end of the boundary. */
939 *tramp_size = kNaClAlignment*2;
941 /* Emit nops to align call site below which is 7 bytes plus */
942 /* the length of the call sequence emitted above. */
943 /* Note: this requires the specific trampoline starts on a */
944 /* kNaclAlignedment aligned address, which it does because */
945 /* it's its own function that is aligned. */
947 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
948 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
949 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
951 /* The trampoline is stored at the offset'th pointer, the -4 is */
952 /* present because RIP relative addressing starts at the end of */
953 /* the current instruction, while the label "." is relative to */
954 /* the beginning of the current asm location, which in this case */
955 /* is not the mov instruction, but the offset itself, due to the */
956 /* way the bytes and ints are emitted here. */
957 got_offset = (offset * sizeof(gpointer)) - 4;
959 /* mov <OFFSET>(%rip), %r11d */
960 emit_byte (acfg, '\x45');
961 emit_byte (acfg, '\x8b');
962 emit_byte (acfg, '\x1d');
963 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
966 emit_bytes (acfg, call_start, call_len);
968 /* The arg is stored at the offset+1 pointer, relative to beginning */
969 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
970 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
972 /* We can't emit this data directly, hide in a "push imm32" */
973 emit_byte (acfg, '\x68'); /* push */
974 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
975 emit_alignment (acfg, kNaClAlignment);
976 #endif /*__native_client_codegen__*/
977 #elif defined(TARGET_ARM)
981 /* This should be exactly 20 bytes long */
984 ARM_PUSH (code, 0x5fff);
985 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
986 /* Load the value from the GOT */
987 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
989 ARM_BLX_REG (code, ARMREG_R1);
991 g_assert (code - buf == 16);
994 emit_bytes (acfg, buf, code - buf);
996 * Only one offset is needed, since the second one would be equal to the
999 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1000 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1001 #elif defined(TARGET_POWERPC)
1008 g_assert (!acfg->use_bin_writer);
1011 * PPC has no ip relative addressing, so we need to compute the address
1012 * of the mscorlib got. That is slow and complex, so instead, we store it
1013 * in the second got slot of every aot image. The caller already computed
1014 * the address of its got and placed it into r30.
1016 img_writer_emit_unset_mode (acfg->w);
1017 /* Load mscorlib got address */
1018 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1019 /* Load generic trampoline address */
1020 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1021 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1022 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1023 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1024 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1026 fprintf (acfg->fp, "mtctr 11\n");
1027 /* Load trampoline argument */
1028 /* On ppc, we pass it normally to the generic trampoline */
1029 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1030 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1031 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1032 /* Branch to generic trampoline */
1033 fprintf (acfg->fp, "bctr\n");
1035 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1036 *tramp_size = 10 * 4;
1038 *tramp_size = 9 * 4;
1040 #elif defined(TARGET_X86)
1044 /* Similar to the PPC code above */
1046 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1048 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1049 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1050 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1054 /* Load mscorlib got address */
1055 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1056 /* Push trampoline argument */
1057 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1058 /* Load generic trampoline address */
1059 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1060 /* Branch to generic trampoline */
1061 x86_jump_reg (code, X86_ECX);
1063 #ifdef __native_client_codegen__
1065 /* emit nops to next 32 byte alignment */
1066 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1067 while (code < (buf + a)) x86_nop(code);
1070 emit_bytes (acfg, buf, code - buf);
1072 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1073 g_assert (code - buf == *tramp_size);
1075 g_assert_not_reached ();
1080 * arch_emit_unbox_trampoline:
1082 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1083 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1086 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1088 #if defined(TARGET_AMD64)
1093 this_reg = mono_arch_get_this_arg_reg (NULL);
1095 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1097 emit_bytes (acfg, buf, code - buf);
1099 emit_byte (acfg, '\xe9');
1100 emit_symbol_diff (acfg, call_target, ".", -4);
1101 #elif defined(TARGET_X86)
1108 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1110 emit_bytes (acfg, buf, code - buf);
1113 emit_byte (acfg, '\xe9');
1114 emit_symbol_diff (acfg, call_target, ".", -4);
1115 #elif defined(TARGET_ARM)
1119 if (acfg->thumb_mixed && cfg->compile_llvm) {
1120 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1121 fprintf (acfg->fp, "b %s\n", call_target);
1122 fprintf (acfg->fp, ".arm\n");
1128 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1130 emit_bytes (acfg, buf, code - buf);
1131 /* jump to method */
1132 if (acfg->use_bin_writer) {
1139 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1140 emit_bytes (acfg, buf, 4);
1142 if (acfg->thumb_mixed && cfg->compile_llvm)
1143 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1145 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1147 #elif defined(TARGET_POWERPC)
1150 g_assert (!acfg->use_bin_writer);
1152 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1153 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1155 g_assert_not_reached ();
1160 * arch_emit_static_rgctx_trampoline:
1162 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1163 * two GOT slots which contain the rgctx argument, and the method to jump to.
1164 * TRAMP_SIZE is set to the size of the emitted trampoline.
1165 * These kinds of trampolines cannot be enumerated statically, since there could
1166 * be one trampoline per method instantiation, so we emit the same code for all
1167 * trampolines, and parameterize them using two GOT slots.
1170 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1172 #if defined(TARGET_AMD64)
1173 #if defined(__default_codegen__)
1174 /* This should be exactly 13 bytes long */
1177 /* mov <OFFSET>(%rip), %r10 */
1178 emit_byte (acfg, '\x4d');
1179 emit_byte (acfg, '\x8b');
1180 emit_byte (acfg, '\x15');
1181 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1183 /* jmp *<offset>(%rip) */
1184 emit_byte (acfg, '\xff');
1185 emit_byte (acfg, '\x25');
1186 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1187 #elif defined(__native_client_codegen__)
1189 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1190 guint8 *code = buf_aligned;
1192 /* mov <OFFSET>(%rip), %r10d */
1193 emit_byte (acfg, '\x45');
1194 emit_byte (acfg, '\x8b');
1195 emit_byte (acfg, '\x15');
1196 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1198 /* mov <OFFSET>(%rip), %r11d */
1199 emit_byte (acfg, '\x45');
1200 emit_byte (acfg, '\x8b');
1201 emit_byte (acfg, '\x1d');
1202 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1205 amd64_jump_reg (code, AMD64_R11);
1206 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1208 emit_alignment (acfg, kNaClAlignment);
1209 *tramp_size = kNaClAlignment;
1210 #endif /*__native_client_codegen__*/
1212 #elif defined(TARGET_ARM)
1216 /* This should be exactly 24 bytes long */
1219 /* Load rgctx value */
1220 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1221 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1222 /* Load branch addr + branch */
1223 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1224 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1226 g_assert (code - buf == 16);
1229 emit_bytes (acfg, buf, code - buf);
1230 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1231 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1232 #elif defined(TARGET_POWERPC)
1239 g_assert (!acfg->use_bin_writer);
1242 * PPC has no ip relative addressing, so we need to compute the address
1243 * of the mscorlib got. That is slow and complex, so instead, we store it
1244 * in the second got slot of every aot image. The caller already computed
1245 * the address of its got and placed it into r30.
1247 img_writer_emit_unset_mode (acfg->w);
1248 /* Load mscorlib got address */
1249 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1251 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1252 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1253 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1254 /* Load target address */
1255 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1256 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1257 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1258 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1259 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1260 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1262 fprintf (acfg->fp, "mtctr 11\n");
1263 /* Branch to the target address */
1264 fprintf (acfg->fp, "bctr\n");
1266 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1267 *tramp_size = 11 * 4;
1269 *tramp_size = 9 * 4;
1272 #elif defined(TARGET_X86)
1276 /* Similar to the PPC code above */
1278 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1281 /* Load mscorlib got address */
1282 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1284 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1285 /* Branch to the target address */
1286 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1288 #ifdef __native_client_codegen__
1290 /* emit nops to next 32 byte alignment */
1291 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1292 while (code < (buf + a)) x86_nop(code);
1296 emit_bytes (acfg, buf, code - buf);
1298 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1299 g_assert (code - buf == *tramp_size);
1301 g_assert_not_reached ();
1306 * arch_emit_imt_thunk:
1308 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1309 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1310 * key is the IMT key, and ptr holds the address of a memory location holding
1311 * the address to branch to if the IMT arg matches the key. The array is
1312 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1314 * TRAMP_SIZE is set to the size of the emitted trampoline.
1317 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1319 #if defined(TARGET_AMD64)
1321 #if defined(__native_client_codegen__)
1326 guint8 *mov_buf_ptr = mov_buf;
1328 const int kSizeOfMove = 7;
1329 #if defined(__default_codegen__)
1330 code = buf = g_malloc (256);
1331 #elif defined(__native_client_codegen__)
1332 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1333 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1334 /* The RIP relative move below is emitted first */
1339 /* FIXME: Optimize this, i.e. use binary search etc. */
1340 /* Maybe move the body into a separate function (slower, but much smaller) */
1342 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1345 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1347 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1350 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1352 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1355 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1356 amd64_jump_code (code, labels [0]);
1359 mono_amd64_patch (labels [2], code);
1360 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1361 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1365 mono_amd64_patch (labels [1], code);
1366 x86_breakpoint (code);
1368 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1369 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1370 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1371 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1372 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1373 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1375 emit_bytes (acfg, buf, code - buf);
1377 *tramp_size = code - buf + kSizeOfMove;
1378 #if defined(__native_client_codegen__)
1379 /* The tramp will be padded to the next kNaClAlignment bundle. */
1380 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1383 #if defined(__default_codegen__)
1385 #elif defined(__native_client_codegen__)
1389 #elif defined(TARGET_X86)
1391 #ifdef __native_client_codegen__
1396 #if defined(__default_codegen__)
1397 code = buf = g_malloc (256);
1398 #elif defined(__native_client_codegen__)
1399 buf_alloc = g_malloc (256 + kNaClAlignment);
1400 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1403 /* Allocate a temporary stack slot */
1404 x86_push_reg (code, X86_EAX);
1406 x86_push_reg (code, X86_EAX);
1408 /* Load mscorlib got address */
1409 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1411 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1414 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1416 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1419 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1421 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1424 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1425 x86_jump_code (code, labels [0]);
1428 mono_x86_patch (labels [2], code);
1429 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1430 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1431 /* Save the target address to the temporary stack location */
1432 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1434 x86_pop_reg (code, X86_EAX);
1435 /* Jump to the target address */
1440 mono_x86_patch (labels [1], code);
1441 x86_breakpoint (code);
1443 #ifdef __native_client_codegen__
1445 /* emit nops to next 32 byte alignment */
1446 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1447 while (code < (buf + a)) x86_nop(code);
1450 emit_bytes (acfg, buf, code - buf);
1452 *tramp_size = code - buf;
1454 #if defined(__default_codegen__)
1456 #elif defined(__native_client_codegen__)
1460 #elif defined(TARGET_ARM)
1462 guint8 *code, *code2, *labels [16];
1466 /* The IMT method is in v5 */
1468 /* Need at least two free registers, plus a slot for storing the pc */
1469 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1471 /* Load the parameter from the GOT */
1472 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1473 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1476 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1477 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1479 ARM_B_COND (code, ARMCOND_EQ, 0);
1481 /* End-of-loop check */
1482 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1484 ARM_B_COND (code, ARMCOND_EQ, 0);
1487 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1490 arm_patch (labels [4], labels [1]);
1493 arm_patch (labels [2], code);
1494 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1495 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1496 /* Save it to the third stack slot */
1497 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1498 /* Restore the registers and branch */
1499 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1502 arm_patch (labels [3], code);
1503 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1504 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1505 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1509 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1511 emit_bytes (acfg, buf, code - buf);
1512 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1514 *tramp_size = code - buf + 4;
1515 #elif defined(TARGET_POWERPC)
1517 guint8 *code, *labels [16];
1521 /* Load the mscorlib got address */
1522 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1523 /* Load the parameter from the GOT */
1524 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1525 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1527 /* Load and check key */
1529 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1530 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1532 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1534 /* End-of-loop check */
1535 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1537 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1540 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1543 mono_ppc_patch (labels [4], labels [1]);
1546 mono_ppc_patch (labels [2], code);
1547 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1548 /* r11 now contains the value of the vtable slot */
1549 /* this is not a function descriptor on ppc64 */
1550 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1551 ppc_mtctr (code, ppc_r11);
1552 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1555 mono_ppc_patch (labels [3], code);
1559 *tramp_size = code - buf;
1561 emit_bytes (acfg, buf, code - buf);
1563 g_assert_not_reached ();
1568 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1570 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1571 /* Based on code generated by gcc */
1572 img_writer_emit_unset_mode (acfg->w);
1575 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1576 ".section .ctors,\"aw\",@progbits\n"
1580 ".section .opd,\"aw\"\n"
1583 ".long .%s,.TOC.@tocbase32\n"
1586 ".type .%s,@function\n"
1588 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1590 ".section .ctors,\"aw\",@progbits\n"
1594 ".section .opd,\"aw\"\n"
1597 ".long .%1$s,.TOC.@tocbase32\n"
1598 ".size %1$s,.-%1$s\n"
1600 ".type .%1$s,@function\n"
1602 ".%1$s:\n", symbol);
1613 "lis 3, .Lglobals@h\n"
1614 "ori 3, 3, .Lglobals@l\n"
1615 "bl .mono_aot_register_module\n"
1623 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1625 ".size .%s,.-.%s\n", symbol, symbol);
1628 ".size .%1$s,.-.%1$s\n", symbol);
1634 /* END OF ARCH SPECIFIC CODE */
1637 mono_get_field_token (MonoClassField *field)
1639 MonoClass *klass = field->parent;
1642 for (i = 0; i < klass->field.count; ++i) {
1643 if (field == &klass->fields [i])
1644 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1647 g_assert_not_reached ();
1652 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1656 //printf ("ENCODE: %d 0x%x.\n", value, value);
1659 * Same encoding as the one used in the metadata, extended to handle values
1660 * greater than 0x1fffffff.
1662 if ((value >= 0) && (value <= 127))
1664 else if ((value >= 0) && (value <= 16383)) {
1665 p [0] = 0x80 | (value >> 8);
1666 p [1] = value & 0xff;
1668 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1669 p [0] = (value >> 24) | 0xc0;
1670 p [1] = (value >> 16) & 0xff;
1671 p [2] = (value >> 8) & 0xff;
1672 p [3] = value & 0xff;
1677 p [1] = (value >> 24) & 0xff;
1678 p [2] = (value >> 16) & 0xff;
1679 p [3] = (value >> 8) & 0xff;
1680 p [4] = value & 0xff;
1688 stream_init (MonoDynamicStream *sh)
1691 sh->alloc_size = 4096;
1692 sh->data = g_malloc (4096);
1694 /* So offsets are > 0 */
1700 make_room_in_stream (MonoDynamicStream *stream, int size)
1702 if (size <= stream->alloc_size)
1705 while (stream->alloc_size <= size) {
1706 if (stream->alloc_size < 4096)
1707 stream->alloc_size = 4096;
1709 stream->alloc_size *= 2;
1712 stream->data = g_realloc (stream->data, stream->alloc_size);
1716 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1720 make_room_in_stream (stream, stream->index + len);
1721 memcpy (stream->data + stream->index, data, len);
1722 idx = stream->index;
1723 stream->index += len;
1730 * Add data to the binary blob inside the aot image. Returns the offset inside the
1731 * blob where the data was stored.
1734 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1736 if (acfg->blob.alloc_size == 0)
1737 stream_init (&acfg->blob);
1739 return add_stream_data (&acfg->blob, (char*)data, data_len);
1743 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1748 if (acfg->blob.alloc_size == 0)
1749 stream_init (&acfg->blob);
1751 count = acfg->blob.index % align;
1753 /* we assume the stream data will be aligned */
1755 add_stream_data (&acfg->blob, buf, 4 - count);
1757 return add_stream_data (&acfg->blob, (char*)data, data_len);
1761 * emit_offset_table:
1763 * Emit a table of increasing offsets in a compact form using differential encoding.
1764 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1765 * group size, the more compact the table becomes, but the slower it becomes to compute
1766 * a given entry. Returns the size of the table.
1769 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1771 gint32 current_offset;
1772 int i, buf_size, ngroups, index_entry_size;
1774 guint32 *index_offsets;
1776 ngroups = (noffsets + (group_size - 1)) / group_size;
1778 index_offsets = g_new0 (guint32, ngroups);
1780 buf_size = noffsets * 4;
1781 p = buf = g_malloc0 (buf_size);
1784 for (i = 0; i < noffsets; ++i) {
1785 //printf ("D: %d -> %d\n", i, offsets [i]);
1786 if ((i % group_size) == 0) {
1787 index_offsets [i / group_size] = p - buf;
1788 /* Emit the full value for these entries */
1789 encode_value (offsets [i], p, &p);
1791 /* The offsets are allowed to be non-increasing */
1792 //g_assert (offsets [i] >= current_offset);
1793 encode_value (offsets [i] - current_offset, p, &p);
1795 current_offset = offsets [i];
1798 if (ngroups && index_offsets [ngroups - 1] < 65000)
1799 index_entry_size = 2;
1801 index_entry_size = 4;
1803 /* Emit the header */
1804 emit_int32 (acfg, noffsets);
1805 emit_int32 (acfg, group_size);
1806 emit_int32 (acfg, ngroups);
1807 emit_int32 (acfg, index_entry_size);
1809 /* Emit the index */
1810 for (i = 0; i < ngroups; ++i) {
1811 if (index_entry_size == 2)
1812 emit_int16 (acfg, index_offsets [i]);
1814 emit_int32 (acfg, index_offsets [i]);
1818 emit_bytes (acfg, buf, p - buf);
1820 return (int)(p - buf) + (ngroups * 4);
1824 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1828 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1832 index = g_hash_table_size (cfg->image_hash);
1833 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1834 g_ptr_array_add (cfg->image_table, image);
1840 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1843 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1845 /* FIXME: Search referenced images as well */
1846 if (!acfg->typespec_classes) {
1847 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1848 for (i = 0; i < len; ++i) {
1849 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1852 for (i = 0; i < len; ++i) {
1853 if (acfg->typespec_classes [i] == klass)
1858 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1864 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1867 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1870 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1873 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1876 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1881 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1885 if (klass->generic_class) {
1887 g_assert (klass->type_token);
1889 /* Find a typespec for a class if possible */
1890 token = find_typespec_for_class (acfg, klass);
1892 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1893 encode_value (token, p, &p);
1895 MonoClass *gclass = klass->generic_class->container_class;
1896 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1897 static int count = 0;
1900 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1901 encode_klass_ref (acfg, gclass, p, &p);
1902 encode_ginst (acfg, inst, p, &p);
1906 } else if (klass->type_token) {
1907 int iindex = get_image_index (acfg, klass->image);
1909 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1911 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1912 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1914 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1915 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1916 encode_value (get_image_index (acfg, klass->image), p, &p);
1918 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1919 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1920 g_assert (container);
1922 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1923 encode_value (klass->byval_arg.type, p, &p);
1924 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1926 encode_value (container->is_method, p, &p);
1927 if (container->is_method)
1928 encode_method_ref (acfg, container->owner.method, p, &p);
1930 encode_klass_ref (acfg, container->owner.klass, p, &p);
1931 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1932 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1933 encode_type (acfg, &klass->byval_arg, p, &p);
1936 g_assert (klass->rank > 0);
1937 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1938 encode_value (klass->rank, p, &p);
1939 encode_klass_ref (acfg, klass->element_class, p, &p);
1947 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1948 * standard metadata encoding.
1951 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1953 gboolean shared = FALSE;
1956 * The encoding of generic instances is large so emit them only once.
1958 if (klass->generic_class) {
1960 g_assert (klass->type_token);
1962 /* Find a typespec for a class if possible */
1963 token = find_typespec_for_class (acfg, klass);
1966 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1971 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
1975 buf2 = g_malloc (1024);
1978 encode_klass_ref_inner (acfg, klass, p, &p);
1979 g_assert (p - buf2 < 1024);
1981 offset = add_to_blob (acfg, buf2, p - buf2);
1984 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
1990 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
1991 encode_value (offset, p, &p);
1996 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2000 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2002 guint32 token = mono_get_field_token (field);
2005 encode_klass_ref (cfg, field->parent, p, &p);
2006 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2007 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2012 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2017 encode_value (inst->type_argc, p, &p);
2018 for (i = 0; i < inst->type_argc; ++i)
2019 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2024 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2027 MonoGenericInst *inst;
2029 inst = context->class_inst;
2031 g_assert (inst->type_argc);
2032 encode_ginst (acfg, inst, p, &p);
2034 encode_value (0, p, &p);
2036 inst = context->method_inst;
2038 g_assert (inst->type_argc);
2039 encode_ginst (acfg, inst, p, &p);
2041 encode_value (0, p, &p);
2047 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2051 g_assert (t->num_mods == 0);
2052 /* t->attrs can be ignored */
2053 //g_assert (t->attrs == 0);
2056 *p = MONO_TYPE_PINNED;
2060 *p = MONO_TYPE_BYREF;
2068 case MONO_TYPE_VOID:
2069 case MONO_TYPE_BOOLEAN:
2070 case MONO_TYPE_CHAR:
2083 case MONO_TYPE_STRING:
2084 case MONO_TYPE_OBJECT:
2085 case MONO_TYPE_TYPEDBYREF:
2087 case MONO_TYPE_VALUETYPE:
2088 case MONO_TYPE_CLASS:
2089 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2091 case MONO_TYPE_SZARRAY:
2092 encode_klass_ref (acfg, t->data.klass, p, &p);
2095 encode_type (acfg, t->data.type, p, &p);
2097 case MONO_TYPE_GENERICINST: {
2098 MonoClass *gclass = t->data.generic_class->container_class;
2099 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2101 encode_klass_ref (acfg, gclass, p, &p);
2102 encode_ginst (acfg, inst, p, &p);
2105 case MONO_TYPE_ARRAY: {
2106 MonoArrayType *array = t->data.array;
2109 encode_klass_ref (acfg, array->eklass, p, &p);
2110 encode_value (array->rank, p, &p);
2111 encode_value (array->numsizes, p, &p);
2112 for (i = 0; i < array->numsizes; ++i)
2113 encode_value (array->sizes [i], p, &p);
2114 encode_value (array->numlobounds, p, &p);
2115 for (i = 0; i < array->numlobounds; ++i)
2116 encode_value (array->lobounds [i], p, &p);
2120 g_assert_not_reached ();
2127 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2133 /* Similar to the metadata encoding */
2134 if (sig->generic_param_count)
2138 if (sig->explicit_this)
2140 flags |= (sig->call_convention & 0x0F);
2144 if (sig->generic_param_count)
2145 encode_value (sig->generic_param_count, p, &p);
2146 encode_value (sig->param_count, p, &p);
2148 encode_type (acfg, sig->ret, p, &p);
2149 for (i = 0; i < sig->param_count; ++i) {
2150 if (sig->sentinelpos == i) {
2151 *p = MONO_TYPE_SENTINEL;
2154 encode_type (acfg, sig->params [i], p, &p);
2160 #define MAX_IMAGE_INDEX 250
2163 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2165 guint32 image_index = get_image_index (acfg, method->klass->image);
2166 guint32 token = method->token;
2167 MonoJumpInfoToken *ji;
2171 * The encoding for most methods is as follows:
2172 * - image index encoded as a leb128
2173 * - token index encoded as a leb128
2174 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2175 * types of method encodings.
2178 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2180 /* Mark methods which can't use aot trampolines because they need the further
2181 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2183 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2184 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2185 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2187 if (method->wrapper_type) {
2188 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2190 encode_value (method->wrapper_type, p, &p);
2192 switch (method->wrapper_type) {
2193 case MONO_WRAPPER_REMOTING_INVOKE:
2194 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2195 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2198 m = mono_marshal_method_from_wrapper (method);
2200 encode_method_ref (acfg, m, p, &p);
2203 case MONO_WRAPPER_PROXY_ISINST:
2204 case MONO_WRAPPER_LDFLD:
2205 case MONO_WRAPPER_LDFLDA:
2206 case MONO_WRAPPER_STFLD:
2207 case MONO_WRAPPER_ISINST: {
2208 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2209 encode_klass_ref (acfg, proxy_class, p, &p);
2212 case MONO_WRAPPER_LDFLD_REMOTE:
2213 case MONO_WRAPPER_STFLD_REMOTE:
2215 case MONO_WRAPPER_ALLOC: {
2216 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2218 /* The GC name is saved once in MonoAotFileInfo */
2219 g_assert (info->alloc_type != -1);
2220 encode_value (info->alloc_type, p, &p);
2223 case MONO_WRAPPER_WRITE_BARRIER:
2225 case MONO_WRAPPER_STELEMREF: {
2226 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2229 encode_value (info->subtype, p, &p);
2230 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2231 encode_value (info->d.virtual_stelemref.kind, p, &p);
2234 case MONO_WRAPPER_UNKNOWN: {
2235 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2238 encode_value (info->subtype, p, &p);
2239 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2240 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2241 encode_klass_ref (acfg, method->klass, p, &p);
2244 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2245 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2248 encode_value (info->subtype, p, &p);
2249 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2250 strcpy ((char*)p, method->name);
2251 p += strlen (method->name) + 1;
2253 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2254 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2258 case MONO_WRAPPER_SYNCHRONIZED: {
2261 m = mono_marshal_method_from_wrapper (method);
2263 g_assert (m != method);
2264 encode_method_ref (acfg, m, p, &p);
2267 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2268 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2271 encode_value (info->subtype, p, &p);
2273 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2274 encode_value (info->d.element_addr.rank, p, &p);
2275 encode_value (info->d.element_addr.elem_size, p, &p);
2276 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2277 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2279 g_assert_not_reached ();
2283 case MONO_WRAPPER_CASTCLASS: {
2284 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2287 encode_value (info->subtype, p, &p);
2290 case MONO_WRAPPER_RUNTIME_INVOKE: {
2291 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2294 encode_value (info->subtype, p, &p);
2295 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2296 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2298 MonoMethodSignature *sig;
2300 encode_value (0, p, &p);
2302 sig = mono_method_signature (method);
2303 encode_signature (acfg, sig, p, &p);
2307 case MONO_WRAPPER_DELEGATE_INVOKE:
2308 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2309 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2310 MonoMethodSignature *sig = mono_method_signature (method);
2311 encode_signature (acfg, sig, p, &p);
2314 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2315 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2318 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2319 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2323 g_assert_not_reached ();
2325 } else if (mono_method_signature (method)->is_inflated) {
2327 * This is a generic method, find the original token which referenced it and
2329 * Obtain the token from information recorded by the JIT.
2331 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2333 image_index = get_image_index (acfg, ji->image);
2334 g_assert (image_index < MAX_IMAGE_INDEX);
2337 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2338 encode_value (image_index, p, &p);
2339 encode_value (token, p, &p);
2341 MonoMethod *declaring;
2342 MonoGenericContext *context = mono_method_get_context (method);
2344 g_assert (method->is_inflated);
2345 declaring = ((MonoMethodInflated*)method)->declaring;
2348 * This might be a non-generic method of a generic instance, which
2349 * doesn't have a token since the reference is generated by the JIT
2350 * like Nullable:Box/Unbox, or by generic sharing.
2353 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2354 /* Encode the klass */
2355 encode_klass_ref (acfg, method->klass, p, &p);
2356 /* Encode the method */
2357 image_index = get_image_index (acfg, method->klass->image);
2358 g_assert (image_index < MAX_IMAGE_INDEX);
2359 g_assert (declaring->token);
2360 token = declaring->token;
2361 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2362 encode_value (image_index, p, &p);
2363 encode_value (token, p, &p);
2364 encode_generic_context (acfg, context, p, &p);
2366 } else if (token == 0) {
2367 /* This might be a method of a constructed type like int[,].Set */
2368 /* Obtain the token from information recorded by the JIT */
2369 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2371 image_index = get_image_index (acfg, ji->image);
2372 g_assert (image_index < MAX_IMAGE_INDEX);
2375 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2376 encode_value (image_index, p, &p);
2377 encode_value (token, p, &p);
2380 g_assert (method->klass->rank);
2382 /* Encode directly */
2383 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2384 encode_klass_ref (acfg, method->klass, p, &p);
2385 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2386 encode_value (0, p, &p);
2387 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2388 encode_value (1, p, &p);
2389 else if (!strcmp (method->name, "Get"))
2390 encode_value (2, p, &p);
2391 else if (!strcmp (method->name, "Address"))
2392 encode_value (3, p, &p);
2393 else if (!strcmp (method->name, "Set"))
2394 encode_value (4, p, &p);
2396 g_assert_not_reached ();
2399 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2400 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2406 compare_patches (gconstpointer a, gconstpointer b)
2410 i = (*(MonoJumpInfo**)a)->ip.i;
2411 j = (*(MonoJumpInfo**)b)->ip.i;
2422 static G_GNUC_UNUSED char*
2423 patch_to_string (MonoJumpInfo *patch_info)
2427 str = g_string_new ("");
2429 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2431 switch (patch_info->type) {
2432 case MONO_PATCH_INFO_VTABLE:
2433 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2438 g_string_append_printf (str, ")");
2439 return g_string_free (str, FALSE);
2445 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2448 static inline gboolean
2449 is_plt_patch (MonoJumpInfo *patch_info)
2451 switch (patch_info->type) {
2452 case MONO_PATCH_INFO_METHOD:
2453 case MONO_PATCH_INFO_INTERNAL_METHOD:
2454 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2455 case MONO_PATCH_INFO_ICALL_ADDR:
2456 case MONO_PATCH_INFO_CLASS_INIT:
2457 case MONO_PATCH_INFO_RGCTX_FETCH:
2458 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2459 case MONO_PATCH_INFO_MONITOR_ENTER:
2460 case MONO_PATCH_INFO_MONITOR_EXIT:
2461 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2471 * Return the symbol identifying the plt entry PLT_OFFSET.
2474 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2478 * The Apple linker reorganizes object files, so it doesn't like branches to local
2479 * labels, since those have no relocations.
2481 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2483 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2490 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2492 static MonoPltEntry*
2493 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2497 if (!is_plt_patch (patch_info))
2500 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2502 // FIXME: This breaks the calculation of final_got_size
2503 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2505 * Allocate a separate PLT slot for each such patch, since some plt
2506 * entries will refer to the method itself, and some will refer to the
2513 MonoJumpInfo *new_ji;
2515 g_assert (!acfg->final_got_size);
2517 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2519 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2520 res->plt_offset = acfg->plt_offset;
2522 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2523 if (acfg->aot_opts.write_symbols)
2524 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2526 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2528 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2530 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2532 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2534 acfg->plt_offset ++;
2543 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2544 * JI could be found if it exists, otherwise allocates a new one.
2547 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2551 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2553 return got_offset - 1;
2555 got_offset = acfg->got_offset;
2556 acfg->got_offset ++;
2558 if (acfg->final_got_size)
2559 g_assert (got_offset < acfg->final_got_size);
2561 acfg->stats.got_slots ++;
2562 acfg->stats.got_slot_types [ji->type] ++;
2564 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2565 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2566 g_ptr_array_add (acfg->got_patches, ji);
2571 /* Add a method to the list of methods which need to be emitted */
2573 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2576 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2577 g_ptr_array_add (acfg->methods, method);
2578 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2579 acfg->nmethods = acfg->methods->len + 1;
2582 if (method->wrapper_type || extra)
2583 g_ptr_array_add (acfg->extra_methods, method);
2587 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2589 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2597 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2601 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2605 index = acfg->method_index;
2606 add_method_with_index (acfg, method, index, extra);
2608 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2610 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2612 acfg->method_index ++;
2618 add_method (MonoAotCompile *acfg, MonoMethod *method)
2620 return add_method_full (acfg, method, FALSE, 0);
2624 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2626 add_method_full (acfg, method, TRUE, 0);
2630 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2632 if (acfg->aot_opts.log_generics)
2633 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2635 add_method_full (acfg, method, TRUE, depth);
2639 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2641 MonoAotCompile *acfg = user_data;
2642 MonoJitICallInfo *callinfo = value;
2643 MonoMethod *wrapper;
2649 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2650 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2653 add_method (acfg, wrapper);
2657 get_runtime_invoke_sig (MonoMethodSignature *sig)
2659 MonoMethodBuilder *mb;
2662 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2663 m = mono_mb_create_method (mb, sig, 16);
2664 return mono_marshal_get_runtime_invoke (m, FALSE);
2668 can_marshal_struct (MonoClass *klass)
2670 MonoClassField *field;
2671 gboolean can_marshal = TRUE;
2672 gpointer iter = NULL;
2674 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2677 /* Only allow a few field types to avoid asserts in the marshalling code */
2678 while ((field = mono_class_get_fields (klass, &iter))) {
2679 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2682 switch (field->type->type) {
2687 case MONO_TYPE_BOOLEAN:
2690 case MONO_TYPE_CHAR:
2698 case MONO_TYPE_STRING:
2700 case MONO_TYPE_VALUETYPE:
2701 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2702 can_marshal = FALSE;
2705 can_marshal = FALSE;
2711 /* Its hard to compute whenever these can be marshalled or not */
2712 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2719 add_wrappers (MonoAotCompile *acfg)
2721 MonoMethod *method, *m;
2723 MonoMethodSignature *sig, *csig;
2727 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2728 * so there is only one wrapper of a given type, or inlining their contents into their
2733 * FIXME: This depends on the fact that different wrappers have different
2737 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2739 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2740 gboolean skip = FALSE;
2742 method = mono_get_method (acfg->image, token, NULL);
2744 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2745 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2746 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2749 if (method->is_generic || method->klass->generic_container)
2752 /* Skip methods which can not be handled by get_runtime_invoke () */
2753 sig = mono_method_signature (method);
2756 if ((sig->ret->type == MONO_TYPE_PTR) ||
2757 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2760 for (j = 0; j < sig->param_count; j++) {
2761 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2765 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2766 if (!method->klass->contextbound) {
2767 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2768 gboolean has_nullable = FALSE;
2770 for (j = 0; j < sig->param_count; j++) {
2771 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2772 has_nullable = TRUE;
2775 if (info && !has_nullable) {
2776 /* Supported by the dynamic runtime-invoke wrapper */
2784 //printf ("%s\n", mono_method_full_name (method, TRUE));
2785 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2789 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2790 #ifdef MONO_ARCH_HAVE_TLS_GET
2791 MonoMethodDesc *desc;
2792 MonoMethod *orig_method;
2796 /* Runtime invoke wrappers */
2798 /* void runtime-invoke () [.cctor] */
2799 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2800 csig->ret = &mono_defaults.void_class->byval_arg;
2801 add_method (acfg, get_runtime_invoke_sig (csig));
2803 /* void runtime-invoke () [Finalize] */
2804 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2806 csig->ret = &mono_defaults.void_class->byval_arg;
2807 add_method (acfg, get_runtime_invoke_sig (csig));
2809 /* void runtime-invoke (string) [exception ctor] */
2810 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2812 csig->ret = &mono_defaults.void_class->byval_arg;
2813 csig->params [0] = &mono_defaults.string_class->byval_arg;
2814 add_method (acfg, get_runtime_invoke_sig (csig));
2816 /* void runtime-invoke (string, string) [exception ctor] */
2817 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2819 csig->ret = &mono_defaults.void_class->byval_arg;
2820 csig->params [0] = &mono_defaults.string_class->byval_arg;
2821 csig->params [1] = &mono_defaults.string_class->byval_arg;
2822 add_method (acfg, get_runtime_invoke_sig (csig));
2824 /* string runtime-invoke () [Exception.ToString ()] */
2825 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2827 csig->ret = &mono_defaults.string_class->byval_arg;
2828 add_method (acfg, get_runtime_invoke_sig (csig));
2830 /* void runtime-invoke (string, Exception) [exception ctor] */
2831 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2833 csig->ret = &mono_defaults.void_class->byval_arg;
2834 csig->params [0] = &mono_defaults.string_class->byval_arg;
2835 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2836 add_method (acfg, get_runtime_invoke_sig (csig));
2838 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2839 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2841 csig->ret = &(mono_class_from_name (
2842 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2843 csig->params [0] = &mono_defaults.string_class->byval_arg;
2844 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2845 add_method (acfg, get_runtime_invoke_sig (csig));
2847 /* runtime-invoke used by finalizers */
2848 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2850 /* This is used by mono_runtime_capture_context () */
2851 method = mono_get_context_capture_method ();
2853 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2855 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2856 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2859 /* JIT icall wrappers */
2860 /* FIXME: locking */
2861 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2864 add_method (acfg, mono_marshal_get_stelemref ());
2866 #ifdef MONO_ARCH_HAVE_TLS_GET
2867 /* Managed Allocators */
2868 nallocators = mono_gc_get_managed_allocator_types ();
2869 for (i = 0; i < nallocators; ++i) {
2870 m = mono_gc_get_managed_allocator_by_type (i);
2872 add_method (acfg, m);
2875 /* Monitor Enter/Exit */
2876 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2877 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2878 /* This is a v4 method */
2880 method = mono_monitor_get_fast_path (orig_method);
2882 add_method (acfg, method);
2884 mono_method_desc_free (desc);
2886 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2887 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2888 g_assert (orig_method);
2889 mono_method_desc_free (desc);
2890 method = mono_monitor_get_fast_path (orig_method);
2892 add_method (acfg, method);
2895 /* Stelemref wrappers */
2896 /* There is only a constant number of these, iterating over all types should handle them all */
2897 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2900 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2901 klass = mono_class_get (acfg->image, token);
2903 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2905 mono_loader_clear_error ();
2908 /* castclass_with_check wrapper */
2909 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2910 /* isinst_with_check wrapper */
2911 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2913 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2915 MonoMethodDesc *desc;
2918 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2919 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2920 mono_method_desc_free (desc);
2922 m = mono_monitor_get_fast_path (m);
2923 add_method (acfg, m);
2930 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2931 * we use the original method instead at runtime.
2932 * Since full-aot doesn't support remoting, this is not a problem.
2935 /* remoting-invoke wrappers */
2936 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2937 MonoMethodSignature *sig;
2939 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2940 method = mono_get_method (acfg->image, token, NULL);
2942 sig = mono_method_signature (method);
2944 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2945 m = mono_marshal_get_remoting_invoke_with_check (method);
2947 add_method (acfg, m);
2952 /* delegate-invoke wrappers */
2953 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2956 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2957 klass = mono_class_get (acfg->image, token);
2960 mono_loader_clear_error ();
2964 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2965 method = mono_get_delegate_invoke (klass);
2967 m = mono_marshal_get_delegate_invoke (method, NULL);
2969 add_method (acfg, m);
2971 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2973 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2975 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2977 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2981 /* Synchronized wrappers */
2982 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2983 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2984 method = mono_get_method (acfg->image, token, NULL);
2986 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2987 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2990 /* pinvoke wrappers */
2991 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2993 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2995 method = mono_get_method (acfg->image, token, NULL);
2997 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2998 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2999 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3003 /* native-to-managed wrappers */
3004 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3006 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3007 MonoCustomAttrInfo *cattr;
3010 method = mono_get_method (acfg->image, token, NULL);
3013 * Only generate native-to-managed wrappers for methods which have an
3014 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3015 * name to avoid defining a new assembly to contain it.
3017 cattr = mono_custom_attrs_from_method (method);
3020 for (j = 0; j < cattr->num_attrs; ++j)
3021 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3023 if (j < cattr->num_attrs) {
3024 MonoCustomAttrEntry *e = &cattr->attrs [j];
3025 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3026 const char *p = (const char*)e->data;
3028 int slen, num_named, named_type, data_type;
3032 char *export_name = NULL;
3033 MonoMethod *wrapper;
3035 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3036 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3037 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3038 mono_method_full_name (method, TRUE));
3042 g_assert (sig->param_count == 1);
3043 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3046 * Decode the cattr manually since we can't create objects
3047 * during aot compilation.
3053 /* From load_cattr_value () in reflection.c */
3054 slen = mono_metadata_decode_value (p, &p);
3055 n = g_memdup (p, slen + 1);
3057 t = mono_reflection_type_from_name (n, acfg->image);
3061 klass = mono_class_from_mono_type (t);
3062 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3066 num_named = read16 (p);
3069 g_assert (num_named < 2);
3070 if (num_named == 1) {
3073 MonoType *prop_type;
3075 /* parse ExportSymbol attribute */
3077 named_type = *named;
3082 name_len = mono_metadata_decode_blob_size (named, &named);
3083 name = g_malloc (name_len + 1);
3084 memcpy (name, named, name_len);
3085 name [name_len] = 0;
3088 g_assert (named_type == 0x54);
3089 g_assert (!strcmp (name, "ExportSymbol"));
3091 prop_type = &mono_defaults.string_class->byval_arg;
3093 /* load_cattr_value (), string case */
3094 g_assert (*named != (char)0xff);
3095 slen = mono_metadata_decode_value (named, &named);
3096 export_name = g_malloc (slen + 1);
3097 memcpy (export_name, named, slen);
3098 export_name [slen] = 0;
3102 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3103 add_method (acfg, wrapper);
3105 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3109 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3110 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3111 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3115 /* StructureToPtr/PtrToStructure wrappers */
3116 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3119 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3120 klass = mono_class_get (acfg->image, token);
3123 mono_loader_clear_error ();
3127 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3128 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3129 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3135 has_type_vars (MonoClass *klass)
3137 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3140 return has_type_vars (klass->element_class);
3141 if (klass->generic_class) {
3142 MonoGenericContext *context = &klass->generic_class->context;
3143 if (context->class_inst) {
3146 for (i = 0; i < context->class_inst->type_argc; ++i)
3147 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3155 method_has_type_vars (MonoMethod *method)
3157 if (has_type_vars (method->klass))
3160 if (method->is_inflated) {
3161 MonoGenericContext *context = mono_method_get_context (method);
3162 if (context->method_inst) {
3165 for (i = 0; i < context->method_inst->type_argc; ++i)
3166 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3173 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3176 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3178 /* This might lead to a huge code blowup so only do it if neccesary */
3179 if (!acfg->aot_opts.full_aot && !force)
3182 add_generic_class_with_depth (acfg, klass, 0, ref);
3186 check_type_depth (MonoType *t, int depth)
3194 case MONO_TYPE_GENERICINST: {
3195 MonoGenericClass *gklass = t->data.generic_class;
3196 MonoGenericInst *ginst = gklass->context.class_inst;
3199 for (i = 0; i < ginst->type_argc; ++i) {
3200 if (check_type_depth (ginst->type_argv [i], depth + 1))
3214 * add_generic_class:
3216 * Add all methods of a generic class.
3219 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3224 if (!acfg->ginst_hash)
3225 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3227 mono_class_init (klass);
3229 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3232 if (has_type_vars (klass))
3235 if (!klass->generic_class && !klass->rank)
3238 if (!acfg->ginst_hash)
3239 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3241 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3244 if (check_type_depth (&klass->byval_arg, 0))
3247 if (acfg->aot_opts.log_generics)
3248 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3250 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3253 while ((method = mono_class_get_methods (klass, &iter))) {
3254 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3258 if (method->is_generic)
3263 * FIXME: Instances which are referenced by these methods are not added,
3264 * for example Array.Resize<int> for List<int>.Add ().
3266 add_extra_method_with_depth (acfg, method, depth + 1);
3269 if (klass->delegate) {
3270 method = mono_get_delegate_invoke (klass);
3272 method = mono_marshal_get_delegate_invoke (method, NULL);
3274 if (acfg->aot_opts.log_generics)
3275 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3277 add_method (acfg, method);
3280 /* Add superclasses */
3282 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3285 * For ICollection<T>, add instances of the helper methods
3286 * in Array, since a T[] could be cast to ICollection<T>.
3288 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3289 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3290 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3291 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3295 if (!strcmp (klass->name, "IEnumerator`1"))
3296 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3298 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3300 /* Add the T[]/InternalEnumerator class */
3301 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3305 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3306 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3310 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3311 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3315 while ((method = mono_class_get_methods (array_class, &iter))) {
3316 if (strstr (method->name, name_prefix)) {
3317 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3319 add_extra_method_with_depth (acfg, m, depth);
3323 g_free (name_prefix);
3326 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3327 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3328 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3329 MonoClass *icomparable, *gcomparer;
3330 MonoGenericContext ctx;
3331 MonoType *args [16];
3333 memset (&ctx, 0, sizeof (ctx));
3335 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3336 g_assert (icomparable);
3337 args [0] = &tclass->byval_arg;
3338 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3340 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3341 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3342 g_assert (gcomparer);
3343 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3347 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3348 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3349 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3350 MonoClass *iface, *gcomparer;
3351 MonoGenericContext ctx;
3352 MonoType *args [16];
3354 memset (&ctx, 0, sizeof (ctx));
3356 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3358 args [0] = &tclass->byval_arg;
3359 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3361 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3362 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3363 g_assert (gcomparer);
3364 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3370 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3373 MonoGenericContext ctx;
3374 MonoType *args [16];
3376 memset (&ctx, 0, sizeof (ctx));
3378 for (i = 0; i < ninsts; ++i) {
3379 args [0] = insts [i];
3380 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3381 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3386 * add_generic_instances:
3388 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3391 add_generic_instances (MonoAotCompile *acfg)
3396 MonoMethodHeader *header;
3397 MonoMethodSignature *sig;
3398 MonoGenericContext *context;
3400 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3401 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3402 method = mono_get_method (acfg->image, token, NULL);
3407 if (method->klass->image != acfg->image)
3410 context = mono_method_get_context (method);
3412 if (context && ((context->class_inst && context->class_inst->is_open)))
3416 * For open methods, create an instantiation which can be passed to the JIT.
3417 * FIXME: Handle class_inst as well.
3419 if (context && context->method_inst && context->method_inst->is_open) {
3420 MonoGenericContext shared_context;
3421 MonoGenericInst *inst;
3422 MonoType **type_argv;
3424 MonoMethod *declaring_method;
3425 gboolean supported = TRUE;
3427 /* Check that the context doesn't contain open constructed types */
3428 if (context->class_inst) {
3429 inst = context->class_inst;
3430 for (i = 0; i < inst->type_argc; ++i) {
3431 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)
3433 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3437 if (context->method_inst) {
3438 inst = context->method_inst;
3439 for (i = 0; i < inst->type_argc; ++i) {
3440 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)
3442 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3450 memset (&shared_context, 0, sizeof (MonoGenericContext));
3452 inst = context->class_inst;
3454 type_argv = g_new0 (MonoType*, inst->type_argc);
3455 for (i = 0; i < inst->type_argc; ++i) {
3456 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)
3457 type_argv [i] = &mono_defaults.object_class->byval_arg;
3459 type_argv [i] = inst->type_argv [i];
3462 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3466 inst = context->method_inst;
3468 type_argv = g_new0 (MonoType*, inst->type_argc);
3469 for (i = 0; i < inst->type_argc; ++i) {
3470 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)
3471 type_argv [i] = &mono_defaults.object_class->byval_arg;
3473 type_argv [i] = inst->type_argv [i];
3476 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3480 if (method->is_generic || method->klass->generic_container)
3481 declaring_method = method;
3483 declaring_method = mono_method_get_declaring_generic_method (method);
3485 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3489 * If the method is fully sharable, it was already added in place of its
3490 * generic definition.
3492 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3496 * FIXME: Partially shared methods are not shared here, so we end up with
3497 * many identical methods.
3499 add_extra_method (acfg, method);
3502 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3505 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3507 klass = mono_class_get (acfg->image, token);
3508 if (!klass || klass->rank) {
3509 mono_loader_clear_error ();
3513 add_generic_class (acfg, klass, FALSE, "typespec");
3516 /* Add types of args/locals */
3517 for (i = 0; i < acfg->methods->len; ++i) {
3520 method = g_ptr_array_index (acfg->methods, i);
3522 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3524 sig = mono_method_signature (method);
3527 for (j = 0; j < sig->param_count; ++j)
3528 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3529 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3532 header = mono_method_get_header (method);
3535 for (j = 0; j < header->num_locals; ++j)
3536 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3537 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3541 if (acfg->image == mono_defaults.corlib) {
3543 MonoType *insts [256];
3546 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3547 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3548 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3549 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3550 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3551 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3552 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3553 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3554 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3555 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3556 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3557 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3559 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3560 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3562 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3563 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3565 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3567 /* Add instances of the array generic interfaces for primitive types */
3568 /* This will add instances of the InternalArray_ helper methods in Array too */
3569 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3571 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3572 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3574 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3575 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3577 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3580 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3581 * used for all instances of GetGenericValueImpl by the AOT runtime.
3584 MonoGenericContext ctx;
3585 MonoType *args [16];
3586 MonoMethod *get_method;
3587 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3589 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3592 memset (&ctx, 0, sizeof (ctx));
3593 args [0] = &mono_defaults.object_class->byval_arg;
3594 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3595 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3599 /* Same for CompareExchange<T>/Exchange<T> */
3601 MonoGenericContext ctx;
3602 MonoType *args [16];
3604 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3605 gpointer iter = NULL;
3607 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3608 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3609 memset (&ctx, 0, sizeof (ctx));
3610 args [0] = &mono_defaults.object_class->byval_arg;
3611 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3612 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3620 * is_direct_callable:
3622 * Return whenever the method identified by JI is directly callable without
3623 * going through the PLT.
3626 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3628 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3629 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3631 gboolean direct_callable = TRUE;
3633 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3634 direct_callable = FALSE;
3635 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3636 // FIXME: Maybe call the wrapper directly ?
3637 direct_callable = FALSE;
3639 if (direct_callable)
3648 * emit_and_reloc_code:
3650 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3651 * is true, calls are made through the GOT too. This is used for emitting trampolines
3652 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3653 * since trampolines are needed to make PTL work.
3656 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3658 int i, pindex, start_index, method_index;
3660 MonoJumpInfo *patch_info;
3661 MonoMethodHeader *header;
3662 gboolean skip, direct_call;
3664 char direct_call_target [1024];
3667 header = mono_method_get_header (method);
3669 method_index = get_method_index (acfg, method);
3672 /* Collect and sort relocations */
3673 patches = g_ptr_array_new ();
3674 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3675 g_ptr_array_add (patches, patch_info);
3676 g_ptr_array_sort (patches, compare_patches);
3679 for (i = 0; i < code_len; i++) {
3681 for (pindex = start_index; pindex < patches->len; ++pindex) {
3682 patch_info = g_ptr_array_index (patches, pindex);
3683 if (patch_info->ip.i >= i)
3687 #ifdef MONO_ARCH_AOT_SUPPORTED
3689 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3690 start_index = pindex;
3692 switch (patch_info->type) {
3693 case MONO_PATCH_INFO_NONE:
3695 case MONO_PATCH_INFO_GOT_OFFSET: {
3698 arch_emit_got_offset (acfg, code + i, &code_size);
3701 patch_info->type = MONO_PATCH_INFO_NONE;
3706 * If this patch is a call, try emitting a direct call instead of
3707 * through a PLT entry. This is possible if the called method is in
3708 * the same assembly and requires no initialization.
3710 direct_call = FALSE;
3711 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3712 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3713 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3714 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3716 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3717 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3718 patch_info->type = MONO_PATCH_INFO_NONE;
3719 acfg->stats.direct_calls ++;
3722 acfg->stats.all_calls ++;
3725 if (!got_only && !direct_call) {
3726 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3728 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3730 sprintf (direct_call_target, "%s", plt_entry->symbol);
3732 /* Nullify the patch */
3733 patch_info->type = MONO_PATCH_INFO_NONE;
3734 plt_entry->jit_used = TRUE;
3741 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3746 got_slot = get_got_offset (acfg, patch_info);
3748 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3755 #endif /* MONO_ARCH_AOT_SUPPORTED */
3758 /* Find next patch */
3760 for (pindex = start_index; pindex < patches->len; ++pindex) {
3761 patch_info = g_ptr_array_index (patches, pindex);
3762 if (patch_info->ip.i >= i)
3766 /* Try to emit multiple bytes at once */
3767 if (pindex < patches->len && patch_info->ip.i > i) {
3768 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3769 i = patch_info->ip.i - 1;
3771 emit_bytes (acfg, code + i, 1);
3780 * Modify SYMBOL so it only includes characters permissible in symbols.
3783 sanitize_symbol (char *symbol)
3785 int i, len = strlen (symbol);
3787 for (i = 0; i < len; ++i)
3788 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3793 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3795 char *name1, *name2, *cached;
3796 int i, j, len, count;
3798 name1 = mono_method_full_name (method, TRUE);
3799 len = strlen (name1);
3800 name2 = malloc (strlen (prefix) + len + 16);
3801 memcpy (name2, prefix, strlen (prefix));
3802 j = strlen (prefix);
3803 for (i = 0; i < len; ++i) {
3804 if (isalnum (name1 [i])) {
3805 name2 [j ++] = name1 [i];
3806 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3808 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3811 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3820 while (g_hash_table_lookup (cache, name2)) {
3821 sprintf (name2 + j, "_%d", count);
3825 cached = g_strdup (name2);
3826 g_hash_table_insert (cache, cached, cached);
3832 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3837 char *debug_sym = NULL;
3839 int func_alignment = AOT_FUNC_ALIGNMENT;
3840 MonoMethodHeader *header;
3843 method = cfg->orig_method;
3844 code = cfg->native_code;
3845 header = cfg->header;
3847 method_index = get_method_index (acfg, method);
3849 /* Make the labels local */
3850 sprintf (symbol, "%s", cfg->asm_symbol);
3852 emit_section_change (acfg, ".text", 0);
3853 emit_alignment (acfg, func_alignment);
3854 emit_label (acfg, symbol);
3856 if (acfg->aot_opts.write_symbols) {
3858 * Write a C style symbol for every method, this has two uses:
3859 * - it works on platforms where the dwarf debugging info is not
3861 * - it allows the setting of breakpoints of aot-ed methods.
3863 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3865 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3866 if (acfg->need_no_dead_strip)
3867 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3868 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3869 emit_label (acfg, debug_sym);
3872 export_name = g_hash_table_lookup (acfg->export_names, method);
3874 /* Emit a global symbol for the method */
3875 emit_global_inner (acfg, export_name, TRUE);
3876 emit_label (acfg, export_name);
3879 if (cfg->verbose_level > 0)
3880 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3882 acfg->stats.code_size += cfg->code_len;
3884 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3886 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3890 if (acfg->aot_opts.write_symbols) {
3891 emit_symbol_size (acfg, debug_sym, ".");
3895 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3896 emit_label (acfg, symbol);
3902 * Encode PATCH_INFO into its disk representation.
3905 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3909 switch (patch_info->type) {
3910 case MONO_PATCH_INFO_NONE:
3912 case MONO_PATCH_INFO_IMAGE:
3913 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3915 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3916 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3917 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3919 case MONO_PATCH_INFO_METHOD_REL:
3920 encode_value ((gint)patch_info->data.offset, p, &p);
3922 case MONO_PATCH_INFO_SWITCH: {
3923 gpointer *table = (gpointer *)patch_info->data.table->table;
3926 encode_value (patch_info->data.table->table_size, p, &p);
3927 for (k = 0; k < patch_info->data.table->table_size; k++)
3928 encode_value ((int)(gssize)table [k], p, &p);
3931 case MONO_PATCH_INFO_METHODCONST:
3932 case MONO_PATCH_INFO_METHOD:
3933 case MONO_PATCH_INFO_METHOD_JUMP:
3934 case MONO_PATCH_INFO_ICALL_ADDR:
3935 case MONO_PATCH_INFO_METHOD_RGCTX:
3936 encode_method_ref (acfg, patch_info->data.method, p, &p);
3938 case MONO_PATCH_INFO_INTERNAL_METHOD:
3939 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3940 guint32 len = strlen (patch_info->data.name);
3942 encode_value (len, p, &p);
3944 memcpy (p, patch_info->data.name, len);
3949 case MONO_PATCH_INFO_LDSTR: {
3950 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3951 guint32 token = patch_info->data.token->token;
3952 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3953 encode_value (image_index, p, &p);
3954 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3957 case MONO_PATCH_INFO_RVA:
3958 case MONO_PATCH_INFO_DECLSEC:
3959 case MONO_PATCH_INFO_LDTOKEN:
3960 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3961 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3962 encode_value (patch_info->data.token->token, p, &p);
3963 encode_value (patch_info->data.token->has_context, p, &p);
3964 if (patch_info->data.token->has_context)
3965 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3967 case MONO_PATCH_INFO_EXC_NAME: {
3968 MonoClass *ex_class;
3971 mono_class_from_name (mono_defaults.exception_class->image,
3972 "System", patch_info->data.target);
3973 g_assert (ex_class);
3974 encode_klass_ref (acfg, ex_class, p, &p);
3977 case MONO_PATCH_INFO_R4:
3978 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3980 case MONO_PATCH_INFO_R8:
3981 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3982 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3984 case MONO_PATCH_INFO_VTABLE:
3985 case MONO_PATCH_INFO_CLASS:
3986 case MONO_PATCH_INFO_IID:
3987 case MONO_PATCH_INFO_ADJUSTED_IID:
3988 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3990 case MONO_PATCH_INFO_CLASS_INIT:
3991 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3992 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3994 case MONO_PATCH_INFO_FIELD:
3995 case MONO_PATCH_INFO_SFLDA:
3996 encode_field_info (acfg, patch_info->data.field, p, &p);
3998 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4000 case MONO_PATCH_INFO_RGCTX_FETCH: {
4001 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4006 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4007 * reference the same method, so encode the method only once.
4009 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4011 buf2 = g_malloc (1024);
4014 encode_method_ref (acfg, entry->method, p2, &p2);
4015 g_assert (p2 - buf2 < 1024);
4017 offset = add_to_blob (acfg, buf2, p2 - buf2);
4020 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4025 encode_value (offset, p, &p);
4026 g_assert (entry->info_type < 256);
4027 g_assert (entry->data->type < 256);
4028 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4029 encode_patch (acfg, entry->data, p, &p);
4032 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4033 case MONO_PATCH_INFO_MONITOR_ENTER:
4034 case MONO_PATCH_INFO_MONITOR_EXIT:
4035 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4037 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4038 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4039 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4041 case MONO_PATCH_INFO_SIGNATURE:
4042 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4045 g_warning ("unable to handle jump info %d", patch_info->type);
4046 g_assert_not_reached ();
4053 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4056 guint32 pindex, offset;
4057 MonoJumpInfo *patch_info;
4059 encode_value (n_patches, p, &p);
4061 for (pindex = 0; pindex < patches->len; ++pindex) {
4062 patch_info = g_ptr_array_index (patches, pindex);
4064 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4068 offset = get_got_offset (acfg, patch_info);
4069 encode_value (offset, p, &p);
4076 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4080 int pindex, buf_size, n_patches;
4082 MonoJumpInfo *patch_info;
4083 MonoMethodHeader *header;
4084 guint32 method_index;
4086 guint32 first_got_offset;
4088 method = cfg->orig_method;
4089 header = mono_method_get_header (method);
4091 method_index = get_method_index (acfg, method);
4093 /* Sort relocations */
4094 patches = g_ptr_array_new ();
4095 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4096 g_ptr_array_add (patches, patch_info);
4097 g_ptr_array_sort (patches, compare_patches);
4099 first_got_offset = acfg->cfgs [method_index]->got_offset;
4101 /**********************/
4102 /* Encode method info */
4103 /**********************/
4105 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4106 p = buf = g_malloc (buf_size);
4108 if (mono_class_get_cctor (method->klass))
4109 encode_klass_ref (acfg, method->klass, p, &p);
4111 /* Not needed when loading the method */
4112 encode_value (0, p, &p);
4115 if (cfg->opt & MONO_OPT_SHARED) {
4116 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4117 for (l = cfg->ldstr_list; l; l = l->next) {
4118 encode_value ((long)l->data, p, &p);
4122 /* Used only in shared mode */
4123 g_assert (!cfg->ldstr_list);
4126 for (pindex = 0; pindex < patches->len; ++pindex) {
4127 patch_info = g_ptr_array_index (patches, pindex);
4129 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4130 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4131 patch_info->type = MONO_PATCH_INFO_NONE;
4136 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4137 /* Stored in a GOT slot initialized at module load time */
4138 patch_info->type = MONO_PATCH_INFO_NONE;
4142 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4143 /* Stored in a GOT slot initialized at module load time */
4144 patch_info->type = MONO_PATCH_INFO_NONE;
4148 if (is_plt_patch (patch_info)) {
4149 /* Calls are made through the PLT */
4150 patch_info->type = MONO_PATCH_INFO_NONE;
4158 g_assert (cfg->has_got_slots);
4160 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4162 acfg->stats.info_size += p - buf;
4164 g_assert (p - buf < buf_size);
4166 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4171 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4173 guint32 cache_index;
4176 /* Reuse the unwind module to canonize and store unwind info entries */
4177 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4179 /* Use +/- 1 to distinguish 0s from missing entries */
4180 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4188 * It would be easier to use assembler symbols, but the caller needs an
4191 offset = acfg->unwind_info_offset;
4192 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4193 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4196 encode_value (encoded_len, p, &p);
4198 acfg->unwind_info_offset += encoded_len + (p - buf);
4204 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4207 int i, k, buf_size, method_index;
4208 guint32 debug_info_size;
4210 MonoMethodHeader *header;
4211 guint8 *p, *buf, *debug_info;
4212 MonoJitInfo *jinfo = cfg->jit_info;
4214 gboolean use_unwind_ops = FALSE;
4215 MonoSeqPointInfo *seq_points;
4217 method = cfg->orig_method;
4218 code = cfg->native_code;
4219 header = cfg->header;
4221 method_index = get_method_index (acfg, method);
4223 if (!acfg->aot_opts.nodebug) {
4224 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4227 debug_info_size = 0;
4230 seq_points = cfg->seq_point_info;
4232 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4233 p = buf = g_malloc (buf_size);
4235 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4236 use_unwind_ops = cfg->unwind_ops != NULL;
4239 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);
4241 encode_value (flags, p, &p);
4243 if (use_unwind_ops) {
4244 guint32 encoded_len;
4248 * This is a duplicate of the data in the .debug_frame section, but that
4249 * section cannot be accessed using the dl interface.
4251 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4252 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4255 encode_value (jinfo->used_regs, p, &p);
4258 /*Encode the number of holes before the number of clauses to make decoding easier*/
4259 if (jinfo->has_try_block_holes) {
4260 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4261 encode_value (table->num_holes, p, &p);
4264 /* Exception table */
4265 if (cfg->compile_llvm) {
4267 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4268 * since the information is only available to llc. Instead, we let llc save the data
4269 * into the LSDA, and read it from there at runtime.
4271 /* The assembly might be CIL stripped so emit the data ourselves */
4272 if (header->num_clauses)
4273 encode_value (header->num_clauses, p, &p);
4275 for (k = 0; k < header->num_clauses; ++k) {
4276 MonoExceptionClause *clause;
4278 clause = &header->clauses [k];
4280 encode_value (clause->flags, p, &p);
4281 if (clause->data.catch_class) {
4282 encode_value (1, p, &p);
4283 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4285 encode_value (0, p, &p);
4288 /* Emit a list of nesting clauses */
4289 for (i = 0; i < header->num_clauses; ++i) {
4291 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4293 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4295 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4296 encode_value (i, p, &p);
4298 encode_value (-1, p, &p);
4301 if (jinfo->num_clauses)
4302 encode_value (jinfo->num_clauses, p, &p);
4304 for (k = 0; k < jinfo->num_clauses; ++k) {
4305 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4307 encode_value (ei->flags, p, &p);
4308 encode_value (ei->exvar_offset, p, &p);
4310 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4311 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4313 if (ei->data.catch_class) {
4314 encode_value (1, p, &p);
4315 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4317 encode_value (0, p, &p);
4321 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4322 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4323 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4327 if (jinfo->has_generic_jit_info) {
4328 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4332 encode_value (gi->nlocs, p, &p);
4334 for (i = 0; i < gi->nlocs; ++i) {
4335 MonoDwarfLocListEntry *entry = &gi->locations [i];
4337 encode_value (entry->is_reg ? 1 : 0, p, &p);
4338 encode_value (entry->reg, p, &p);
4340 encode_value (entry->offset, p, &p);
4342 g_assert (entry->from == 0);
4344 encode_value (entry->from, p, &p);
4345 encode_value (entry->to, p, &p);
4348 if (!cfg->compile_llvm) {
4349 encode_value (gi->has_this ? 1 : 0, p, &p);
4350 encode_value (gi->this_reg, p, &p);
4351 encode_value (gi->this_offset, p, &p);
4356 * Need to encode jinfo->method too, since it is not equal to 'method'
4357 * when using generic sharing.
4359 encode_method_ref (acfg, jinfo->method, p, &p);
4362 if (jinfo->has_try_block_holes) {
4363 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4364 for (i = 0; i < table->num_holes; ++i) {
4365 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4366 encode_value (hole->clause, p, &p);
4367 encode_value (hole->length, p, &p);
4368 encode_value (hole->offset, p, &p);
4372 if (jinfo->has_arch_eh_info) {
4373 MonoArchEHJitInfo *eh_info;
4375 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4376 encode_value (eh_info->stack_size, p, &p);
4380 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4382 encode_value (seq_points->len, p, &p);
4383 last_il_offset = last_native_offset = 0;
4384 for (i = 0; i < seq_points->len; ++i) {
4385 SeqPoint *sp = &seq_points->seq_points [i];
4386 il_offset = sp->il_offset;
4387 native_offset = sp->native_offset;
4388 encode_value (il_offset - last_il_offset, p, &p);
4389 encode_value (native_offset - last_native_offset, p, &p);
4390 last_il_offset = il_offset;
4391 last_native_offset = native_offset;
4393 encode_value (sp->next_len, p, &p);
4394 for (j = 0; j < sp->next_len; ++j)
4395 encode_value (sp->next [j], p, &p);
4399 g_assert (debug_info_size < buf_size);
4401 encode_value (debug_info_size, p, &p);
4402 if (debug_info_size) {
4403 memcpy (p, debug_info, debug_info_size);
4404 p += debug_info_size;
4405 g_free (debug_info);
4410 encode_value (cfg->gc_map_size, p, &p);
4411 /* The GC map requires 4 bytes of alignment */
4412 while ((gsize)p % 4)
4414 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4415 p += cfg->gc_map_size;
4418 acfg->stats.ex_info_size += p - buf;
4420 g_assert (p - buf < buf_size);
4423 /* The GC Map requires 4 byte alignment */
4424 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4429 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4431 MonoClass *klass = mono_class_get (acfg->image, token);
4433 int i, buf_size, res;
4434 gboolean no_special_static, cant_encode;
4435 gpointer iter = NULL;
4438 mono_loader_clear_error ();
4442 p = buf = g_malloc (buf_size);
4444 /* Mark as unusable */
4445 encode_value (-1, p, &p);
4447 res = add_to_blob (acfg, buf, p - buf);
4453 buf_size = 10240 + (klass->vtable_size * 16);
4454 p = buf = g_malloc (buf_size);
4458 mono_class_init (klass);
4460 mono_class_get_nested_types (klass, &iter);
4461 g_assert (klass->nested_classes_inited);
4463 mono_class_setup_vtable (klass);
4466 * Emit all the information which is required for creating vtables so
4467 * the runtime does not need to create the MonoMethod structures which
4468 * take up a lot of space.
4471 no_special_static = !mono_class_has_special_static_fields (klass);
4473 /* Check whenever we have enough info to encode the vtable */
4474 cant_encode = FALSE;
4475 for (i = 0; i < klass->vtable_size; ++i) {
4476 MonoMethod *cm = klass->vtable [i];
4478 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4482 mono_class_has_finalizer (klass);
4484 if (klass->generic_container || cant_encode) {
4485 encode_value (-1, p, &p);
4487 encode_value (klass->vtable_size, p, &p);
4488 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);
4489 if (klass->has_cctor)
4490 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4491 if (klass->has_finalize)
4492 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4494 encode_value (klass->instance_size, p, &p);
4495 encode_value (mono_class_data_size (klass), p, &p);
4496 encode_value (klass->packing_size, p, &p);
4497 encode_value (klass->min_align, p, &p);
4499 for (i = 0; i < klass->vtable_size; ++i) {
4500 MonoMethod *cm = klass->vtable [i];
4503 encode_method_ref (acfg, cm, p, &p);
4505 encode_value (0, p, &p);
4509 acfg->stats.class_info_size += p - buf;
4511 g_assert (p - buf < buf_size);
4512 res = add_to_blob (acfg, buf, p - buf);
4519 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4521 char *debug_sym = NULL;
4524 case MONO_PATCH_INFO_METHOD:
4525 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4527 case MONO_PATCH_INFO_INTERNAL_METHOD:
4528 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4530 case MONO_PATCH_INFO_CLASS_INIT:
4531 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4532 sanitize_symbol (debug_sym);
4534 case MONO_PATCH_INFO_RGCTX_FETCH:
4535 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4537 case MONO_PATCH_INFO_ICALL_ADDR: {
4538 char *s = get_debug_sym (ji->data.method, "", cache);
4540 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4544 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4545 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4547 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4548 debug_sym = g_strdup_printf ("plt__generic_class_init");
4558 * Calls made from AOTed code are routed through a table of jumps similar to the
4559 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4560 * control to the AOT runtime through a trampoline.
4563 emit_plt (MonoAotCompile *acfg)
4569 sprintf (symbol, "plt");
4571 emit_section_change (acfg, ".text", 0);
4572 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4573 emit_label (acfg, symbol);
4574 emit_label (acfg, acfg->plt_symbol);
4576 for (i = 0; i < acfg->plt_offset; ++i) {
4577 char *debug_sym = NULL;
4578 MonoPltEntry *plt_entry = NULL;
4583 * The first plt entry is unused.
4587 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4592 * If the target is directly callable, alias the plt symbol to point to
4594 * FIXME: Use this to simplify emit_and_reloc_code ().
4595 * FIXME: Avoid the got slot.
4596 * FIXME: Add support to the binary writer.
4598 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4599 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4601 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4602 /* LLVM calls the PLT entries using bl, so emit a stub */
4603 fprintf (acfg->fp, "\n.thumb_func\n");
4604 emit_label (acfg, plt_entry->llvm_symbol);
4605 fprintf (acfg->fp, "bx pc\n");
4606 fprintf (acfg->fp, "nop\n");
4607 fprintf (acfg->fp, ".arm\n");
4608 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4610 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4616 debug_sym = plt_entry->debug_sym;
4618 if (acfg->thumb_mixed && !plt_entry->jit_used)
4619 /* Emit only a thumb version */
4622 if (!acfg->thumb_mixed)
4623 emit_label (acfg, plt_entry->llvm_symbol);
4626 if (acfg->need_no_dead_strip)
4627 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4628 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4629 emit_label (acfg, debug_sym);
4632 emit_label (acfg, plt_entry->symbol);
4634 arch_emit_plt_entry (acfg, i);
4637 emit_symbol_size (acfg, debug_sym, ".");
4640 if (acfg->thumb_mixed) {
4641 /* Make sure the ARM symbols don't alias the thumb ones */
4642 emit_zero_bytes (acfg, 16);
4645 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4648 for (i = 0; i < acfg->plt_offset; ++i) {
4649 char *debug_sym = NULL;
4650 MonoPltEntry *plt_entry = NULL;
4656 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4659 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4662 /* Skip plt entries not actually called by LLVM code */
4663 if (!plt_entry->llvm_used)
4666 if (acfg->aot_opts.write_symbols) {
4667 if (plt_entry->debug_sym)
4668 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4672 #if defined(__APPLE__)
4673 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4674 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4676 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4677 emit_label (acfg, debug_sym);
4679 fprintf (acfg->fp, "\n.thumb_func\n");
4681 emit_label (acfg, plt_entry->llvm_symbol);
4683 arch_emit_llvm_plt_entry (acfg, i);
4686 emit_symbol_size (acfg, debug_sym, ".");
4692 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4694 sprintf (symbol, "plt_end");
4695 emit_label (acfg, symbol);
4698 static G_GNUC_UNUSED void
4699 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4701 char start_symbol [256];
4703 guint32 buf_size, info_offset;
4704 MonoJumpInfo *patch_info;
4715 code_size = info->code_size;
4717 unwind_ops = info->unwind_ops;
4719 #ifdef __native_client_codegen__
4720 mono_nacl_fix_patches (code, ji);
4725 sprintf (start_symbol, "%s", name);
4727 emit_section_change (acfg, ".text", 0);
4728 emit_global (acfg, start_symbol, TRUE);
4729 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4730 emit_label (acfg, start_symbol);
4732 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4733 emit_label (acfg, symbol);
4736 * The code should access everything through the GOT, so we pass
4739 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4741 emit_symbol_size (acfg, start_symbol, ".");
4745 /* Sort relocations */
4746 patches = g_ptr_array_new ();
4747 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4748 if (patch_info->type != MONO_PATCH_INFO_NONE)
4749 g_ptr_array_add (patches, patch_info);
4750 g_ptr_array_sort (patches, compare_patches);
4752 buf_size = patches->len * 128 + 128;
4753 buf = g_malloc (buf_size);
4756 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4757 g_assert (p - buf < buf_size);
4759 sprintf (symbol, "%s_p", name);
4761 info_offset = add_to_blob (acfg, buf, p - buf);
4763 emit_section_change (acfg, RODATA_SECT, 0);
4764 emit_global (acfg, symbol, FALSE);
4765 emit_label (acfg, symbol);
4767 emit_int32 (acfg, info_offset);
4769 /* Emit debug info */
4773 sprintf (symbol, "%s", name);
4774 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4777 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4782 emit_trampolines (MonoAotCompile *acfg)
4785 char end_symbol [256];
4786 int i, tramp_got_offset;
4787 MonoAotTrampoline ntype;
4788 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4792 if (!acfg->aot_opts.full_aot)
4795 g_assert (acfg->image->assembly);
4797 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4798 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4799 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4800 MonoTrampInfo *info;
4803 * Emit the generic trampolines.
4805 * We could save some code by treating the generic trampolines as a wrapper
4806 * method, but that approach has its own complexities, so we choose the simpler
4809 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4810 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4811 emit_trampoline (acfg, acfg->got_offset, info);
4814 mono_arch_get_nullified_class_init_trampoline (&info);
4815 emit_trampoline (acfg, acfg->got_offset, info);
4816 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4817 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4818 emit_trampoline (acfg, acfg->got_offset, info);
4819 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4820 emit_trampoline (acfg, acfg->got_offset, info);
4823 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4824 emit_trampoline (acfg, acfg->got_offset, info);
4826 /* Emit the exception related code pieces */
4827 mono_arch_get_restore_context (&info, TRUE);
4828 emit_trampoline (acfg, acfg->got_offset, info);
4829 mono_arch_get_call_filter (&info, TRUE);
4830 emit_trampoline (acfg, acfg->got_offset, info);
4831 mono_arch_get_throw_exception (&info, TRUE);
4832 emit_trampoline (acfg, acfg->got_offset, info);
4833 mono_arch_get_rethrow_exception (&info, TRUE);
4834 emit_trampoline (acfg, acfg->got_offset, info);
4835 mono_arch_get_throw_corlib_exception (&info, TRUE);
4836 emit_trampoline (acfg, acfg->got_offset, info);
4838 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4840 GSList *l = mono_arch_get_trampolines (TRUE);
4843 MonoTrampInfo *info = l->data;
4845 emit_trampoline (acfg, acfg->got_offset, info);
4851 for (i = 0; i < 128; ++i) {
4854 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4855 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4856 emit_trampoline (acfg, acfg->got_offset, info);
4858 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4859 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4860 emit_trampoline (acfg, acfg->got_offset, info);
4866 /* delegate_invoke_impl trampolines */
4867 l = mono_arch_get_delegate_invoke_impls ();
4869 MonoTrampInfo *info = l->data;
4871 emit_trampoline (acfg, acfg->got_offset, info);
4876 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4878 /* Emit trampolines which are numerous */
4881 * These include the following:
4882 * - specific trampolines
4883 * - static rgctx invoke trampolines
4885 * These trampolines have the same code, they are parameterized by GOT
4887 * They are defined in this file, in the arch_... routines instead of
4888 * in tramp-<ARCH>.c, since it is easier to do it this way.
4892 * When running in aot-only mode, we can't create specific trampolines at
4893 * runtime, so we create a few, and save them in the AOT file.
4894 * Normal trampolines embed their argument as a literal inside the
4895 * trampoline code, we can't do that here, so instead we embed an offset
4896 * which needs to be added to the trampoline address to get the address of
4897 * the GOT slot which contains the argument value.
4898 * The generated trampolines jump to the generic trampolines using another
4899 * GOT slot, which will be setup by the AOT loader to point to the
4900 * generic trampoline code of the given type.
4904 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4908 emit_section_change (acfg, ".text", 0);
4910 tramp_got_offset = acfg->got_offset;
4912 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4914 case MONO_AOT_TRAMP_SPECIFIC:
4915 sprintf (symbol, "specific_trampolines");
4917 case MONO_AOT_TRAMP_STATIC_RGCTX:
4918 sprintf (symbol, "static_rgctx_trampolines");
4920 case MONO_AOT_TRAMP_IMT_THUNK:
4921 sprintf (symbol, "imt_thunks");
4924 g_assert_not_reached ();
4927 sprintf (end_symbol, "%s_e", symbol);
4929 if (acfg->aot_opts.write_symbols)
4930 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
4932 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4933 emit_label (acfg, symbol);
4935 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4937 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4941 case MONO_AOT_TRAMP_SPECIFIC:
4942 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4943 tramp_got_offset += 2;
4945 case MONO_AOT_TRAMP_STATIC_RGCTX:
4946 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4947 tramp_got_offset += 2;
4949 case MONO_AOT_TRAMP_IMT_THUNK:
4950 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4951 tramp_got_offset += 1;
4954 g_assert_not_reached ();
4956 #ifdef __native_client_codegen__
4957 /* align to avoid 32-byte boundary crossings */
4958 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4961 if (!acfg->trampoline_size [ntype]) {
4962 g_assert (tramp_size);
4963 acfg->trampoline_size [ntype] = tramp_size;
4967 emit_label (acfg, end_symbol);
4970 /* Reserve some entries at the end of the GOT for our use */
4971 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4974 acfg->got_offset += acfg->num_trampoline_got_entries;
4978 str_begins_with (const char *str1, const char *str2)
4980 int len = strlen (str2);
4981 return strncmp (str1, str2, len) == 0;
4985 mono_aot_readonly_field_override (MonoClassField *field)
4988 for (rdv = readonly_values; rdv; rdv = rdv->next) {
4989 char *p = rdv->name;
4991 len = strlen (field->parent->name_space);
4992 if (strncmp (p, field->parent->name_space, len))
4997 len = strlen (field->parent->name);
4998 if (strncmp (p, field->parent->name, len))
5003 if (strcmp (p, field->name))
5005 switch (rdv->type) {
5007 return &rdv->value.i1;
5009 return &rdv->value.i2;
5011 return &rdv->value.i4;
5020 add_readonly_value (MonoAotOptions *opts, const char *val)
5025 /* the format of val is:
5026 * namespace.typename.fieldname=type/value
5027 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5029 fval = strrchr (val, '/');
5031 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5034 tval = strrchr (val, '=');
5036 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5039 rdv = g_new0 (ReadOnlyValue, 1);
5040 rdv->name = g_malloc0 (tval - val + 1);
5041 memcpy (rdv->name, val, tval - val);
5044 if (strncmp (tval, "i1", 2) == 0) {
5045 rdv->value.i1 = atoi (fval);
5046 rdv->type = MONO_TYPE_I1;
5047 } else if (strncmp (tval, "i2", 2) == 0) {
5048 rdv->value.i2 = atoi (fval);
5049 rdv->type = MONO_TYPE_I2;
5050 } else if (strncmp (tval, "i4", 2) == 0) {
5051 rdv->value.i4 = atoi (fval);
5052 rdv->type = MONO_TYPE_I4;
5054 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5057 rdv->next = readonly_values;
5058 readonly_values = rdv;
5062 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5064 gchar **args, **ptr;
5066 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5067 for (ptr = args; ptr && *ptr; ptr ++) {
5068 const char *arg = *ptr;
5070 if (str_begins_with (arg, "outfile=")) {
5071 opts->outfile = g_strdup (arg + strlen ("outfile="));
5072 } else if (str_begins_with (arg, "save-temps")) {
5073 opts->save_temps = TRUE;
5074 } else if (str_begins_with (arg, "keep-temps")) {
5075 opts->save_temps = TRUE;
5076 } else if (str_begins_with (arg, "write-symbols")) {
5077 opts->write_symbols = TRUE;
5078 } else if (str_begins_with (arg, "no-write-symbols")) {
5079 opts->write_symbols = FALSE;
5080 } else if (str_begins_with (arg, "metadata-only")) {
5081 opts->metadata_only = TRUE;
5082 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5083 opts->bind_to_runtime_version = TRUE;
5084 } else if (str_begins_with (arg, "full")) {
5085 opts->full_aot = TRUE;
5086 } else if (str_begins_with (arg, "threads=")) {
5087 opts->nthreads = atoi (arg + strlen ("threads="));
5088 } else if (str_begins_with (arg, "static")) {
5089 opts->static_link = TRUE;
5090 opts->no_dlsym = TRUE;
5091 } else if (str_begins_with (arg, "asmonly")) {
5092 opts->asm_only = TRUE;
5093 } else if (str_begins_with (arg, "asmwriter")) {
5094 opts->asm_writer = TRUE;
5095 } else if (str_begins_with (arg, "nodebug")) {
5096 opts->nodebug = TRUE;
5097 } else if (str_begins_with (arg, "ntrampolines=")) {
5098 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5099 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5100 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5101 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5102 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5103 } else if (str_begins_with (arg, "autoreg")) {
5104 opts->autoreg = TRUE;
5105 } else if (str_begins_with (arg, "tool-prefix=")) {
5106 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5107 } else if (str_begins_with (arg, "soft-debug")) {
5108 opts->soft_debug = TRUE;
5109 } else if (str_begins_with (arg, "print-skipped")) {
5110 opts->print_skipped_methods = TRUE;
5111 } else if (str_begins_with (arg, "stats")) {
5113 } else if (str_begins_with (arg, "log-generics")) {
5114 opts->log_generics = TRUE;
5115 } else if (str_begins_with (arg, "mtriple=")) {
5116 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5117 } else if (str_begins_with (arg, "llvm-path=")) {
5118 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5119 } else if (str_begins_with (arg, "readonly-value=")) {
5120 add_readonly_value (opts, arg + strlen ("readonly-value="));
5121 } else if (str_begins_with (arg, "info")) {
5122 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5124 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5125 printf ("Supported options for --aot:\n");
5126 printf (" outfile=\n");
5127 printf (" save-temps\n");
5128 printf (" keep-temps\n");
5129 printf (" write-symbols\n");
5130 printf (" metadata-only\n");
5131 printf (" bind-to-runtime-version\n");
5133 printf (" threads=\n");
5134 printf (" static\n");
5135 printf (" asmonly\n");
5136 printf (" asmwriter\n");
5137 printf (" nodebug\n");
5138 printf (" ntrampolines=\n");
5139 printf (" nrgctx-trampolines=\n");
5140 printf (" nimt-trampolines=\n");
5141 printf (" autoreg\n");
5142 printf (" tool-prefix=\n");
5143 printf (" readonly-value=\n");
5144 printf (" soft-debug\n");
5145 printf (" print-skipped\n");
5146 printf (" stats\n");
5148 printf (" help/?\n");
5151 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5160 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5162 MonoMethod *method = (MonoMethod*)key;
5163 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5164 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5165 MonoAotCompile *acfg = user_data;
5167 new_ji->image = ji->image;
5168 new_ji->token = ji->token;
5169 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5173 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5175 if (klass->type_token)
5177 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5180 return can_encode_class (acfg, klass->element_class);
5185 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5187 switch (patch_info->type) {
5188 case MONO_PATCH_INFO_METHOD:
5189 case MONO_PATCH_INFO_METHODCONST: {
5190 MonoMethod *method = patch_info->data.method;
5192 if (method->wrapper_type) {
5193 switch (method->wrapper_type) {
5194 case MONO_WRAPPER_NONE:
5195 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5196 case MONO_WRAPPER_XDOMAIN_INVOKE:
5197 case MONO_WRAPPER_STFLD:
5198 case MONO_WRAPPER_LDFLD:
5199 case MONO_WRAPPER_LDFLDA:
5200 case MONO_WRAPPER_LDFLD_REMOTE:
5201 case MONO_WRAPPER_STFLD_REMOTE:
5202 case MONO_WRAPPER_STELEMREF:
5203 case MONO_WRAPPER_ISINST:
5204 case MONO_WRAPPER_PROXY_ISINST:
5205 case MONO_WRAPPER_ALLOC:
5206 case MONO_WRAPPER_REMOTING_INVOKE:
5207 case MONO_WRAPPER_UNKNOWN:
5208 case MONO_WRAPPER_WRITE_BARRIER:
5210 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5211 case MONO_WRAPPER_CASTCLASS: {
5212 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5221 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5225 if (!method->token) {
5226 /* The method is part of a constructed type like Int[,].Set (). */
5227 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5228 if (method->klass->rank)
5236 case MONO_PATCH_INFO_VTABLE:
5237 case MONO_PATCH_INFO_CLASS_INIT:
5238 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5239 case MONO_PATCH_INFO_CLASS:
5240 case MONO_PATCH_INFO_IID:
5241 case MONO_PATCH_INFO_ADJUSTED_IID:
5242 if (!can_encode_class (acfg, patch_info->data.klass)) {
5243 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5247 case MONO_PATCH_INFO_RGCTX_FETCH: {
5248 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5250 if (!can_encode_patch (acfg, entry->data))
5264 * AOT compile a given method.
5265 * This function might be called by multiple threads, so it must be thread-safe.
5268 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5271 MonoJumpInfo *patch_info;
5274 MonoMethod *wrapped;
5276 if (acfg->aot_opts.metadata_only)
5279 mono_acfg_lock (acfg);
5280 index = get_method_index (acfg, method);
5281 mono_acfg_unlock (acfg);
5283 /* fixme: maybe we can also precompile wrapper methods */
5284 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5285 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5286 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5287 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5291 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5294 wrapped = mono_marshal_method_from_wrapper (method);
5295 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5296 // FIXME: The wrapper should be generic too, but it is not
5299 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5302 InterlockedIncrement (&acfg->stats.mcount);
5305 if (method->is_generic || method->klass->generic_container) {
5306 InterlockedIncrement (&acfg->stats.genericcount);
5311 //acfg->aot_opts.print_skipped_methods = TRUE;
5314 * Since these methods are the only ones which are compiled with
5315 * AOT support, and they are not used by runtime startup/shutdown code,
5316 * the runtime will not see AOT methods during AOT compilation,so it
5317 * does not need to support them by creating a fake GOT etc.
5319 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5320 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5321 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5322 InterlockedIncrement (&acfg->stats.genericcount);
5325 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5326 if (acfg->aot_opts.print_skipped_methods)
5327 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5328 /* Let the exception happen at runtime */
5332 if (cfg->disable_aot) {
5333 if (acfg->aot_opts.print_skipped_methods)
5334 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5335 InterlockedIncrement (&acfg->stats.ocount);
5336 mono_destroy_compile (cfg);
5340 /* Nullify patches which need no aot processing */
5341 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5342 switch (patch_info->type) {
5343 case MONO_PATCH_INFO_LABEL:
5344 case MONO_PATCH_INFO_BB:
5345 patch_info->type = MONO_PATCH_INFO_NONE;
5352 /* Collect method->token associations from the cfg */
5353 mono_acfg_lock (acfg);
5354 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5355 mono_acfg_unlock (acfg);
5358 * Check for absolute addresses.
5361 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5362 switch (patch_info->type) {
5363 case MONO_PATCH_INFO_ABS:
5364 /* unable to handle this */
5373 if (acfg->aot_opts.print_skipped_methods)
5374 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5375 InterlockedIncrement (&acfg->stats.abscount);
5376 mono_destroy_compile (cfg);
5380 /* Lock for the rest of the code */
5381 mono_acfg_lock (acfg);
5384 * Check for methods/klasses we can't encode.
5387 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5388 if (!can_encode_patch (acfg, patch_info))
5393 if (acfg->aot_opts.print_skipped_methods)
5394 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5395 acfg->stats.ocount++;
5396 mono_destroy_compile (cfg);
5397 mono_acfg_unlock (acfg);
5401 /* Adds generic instances referenced by this method */
5403 * The depth is used to avoid infinite loops when generic virtual recursion is
5406 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5408 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5409 switch (patch_info->type) {
5410 case MONO_PATCH_INFO_METHOD: {
5411 MonoMethod *m = patch_info->data.method;
5412 if (m->is_inflated) {
5413 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5414 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5415 !method_has_type_vars (m)) {
5416 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5417 if (acfg->aot_opts.full_aot)
5418 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5420 add_extra_method_with_depth (acfg, m, depth + 1);
5423 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5425 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5426 add_extra_method_with_depth (acfg, m, depth + 1);
5429 case MONO_PATCH_INFO_VTABLE: {
5430 MonoClass *klass = patch_info->data.klass;
5432 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5433 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5436 case MONO_PATCH_INFO_SFLDA: {
5437 MonoClass *klass = patch_info->data.field->parent;
5439 /* The .cctor needs to run at runtime. */
5440 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5441 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5450 /* Determine whenever the method has GOT slots */
5451 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5452 switch (patch_info->type) {
5453 case MONO_PATCH_INFO_GOT_OFFSET:
5454 case MONO_PATCH_INFO_NONE:
5455 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5457 case MONO_PATCH_INFO_IMAGE:
5458 /* The assembly is stored in GOT slot 0 */
5459 if (patch_info->data.image != acfg->image)
5460 cfg->has_got_slots = TRUE;
5463 if (!is_plt_patch (patch_info))
5464 cfg->has_got_slots = TRUE;
5469 if (!cfg->has_got_slots)
5470 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5473 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5475 /* Make a copy of the patch info which is in the mempool */
5477 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5479 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5480 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5483 patches = new_patch_info;
5485 patches_end->next = new_patch_info;
5486 patches_end = new_patch_info;
5488 cfg->patch_info = patches;
5490 /* Make a copy of the unwind info */
5492 GSList *l, *unwind_ops;
5496 for (l = cfg->unwind_ops; l; l = l->next) {
5497 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5498 memcpy (op, l->data, sizeof (MonoUnwindOp));
5499 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5501 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5503 /* Make a copy of the argument/local info */
5505 MonoInst **args, **locals;
5506 MonoMethodSignature *sig;
5507 MonoMethodHeader *header;
5510 sig = mono_method_signature (method);
5511 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5512 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5513 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5514 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5518 header = mono_method_get_header (method);
5519 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5520 for (i = 0; i < header->num_locals; ++i) {
5521 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5522 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5524 cfg->locals = locals;
5527 /* Free some fields used by cfg to conserve memory */
5528 mono_mempool_destroy (cfg->mempool);
5529 cfg->mempool = NULL;
5530 g_free (cfg->varinfo);
5531 cfg->varinfo = NULL;
5535 mono_regstate_free (cfg->rs);
5539 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5541 while (index >= acfg->cfgs_size) {
5542 MonoCompile **new_cfgs;
5545 new_size = acfg->cfgs_size * 2;
5546 new_cfgs = g_new0 (MonoCompile*, new_size);
5547 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5548 g_free (acfg->cfgs);
5549 acfg->cfgs = new_cfgs;
5550 acfg->cfgs_size = new_size;
5552 acfg->cfgs [index] = cfg;
5554 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5557 if (cfg->orig_method->wrapper_type)
5558 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5561 mono_acfg_unlock (acfg);
5563 InterlockedIncrement (&acfg->stats.ccount);
5567 compile_thread_main (gpointer *user_data)
5569 MonoDomain *domain = user_data [0];
5570 MonoAotCompile *acfg = user_data [1];
5571 GPtrArray *methods = user_data [2];
5574 mono_thread_attach (domain);
5576 for (i = 0; i < methods->len; ++i)
5577 compile_method (acfg, g_ptr_array_index (methods, i));
5581 load_profile_files (MonoAotCompile *acfg)
5585 int file_index, res, method_index, i;
5588 GList *unordered, *l;
5593 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5595 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5600 infile = fopen (tmp, "r");
5603 printf ("Using profile data file '%s'\n", tmp);
5608 res = fscanf (infile, "%32s\n", ver);
5609 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5610 printf ("Profile file has wrong version or invalid.\n");
5617 MonoMethodDesc *desc;
5620 if (fgets (name, 1023, infile) == NULL)
5623 /* Kill the newline */
5624 if (strlen (name) > 0)
5625 name [strlen (name) - 1] = '\0';
5627 desc = mono_method_desc_new (name, TRUE);
5629 method = mono_method_desc_search_in_image (desc, acfg->image);
5631 if (method && mono_method_get_token (method)) {
5632 token = mono_method_get_token (method);
5633 method_index = mono_metadata_token_index (token) - 1;
5636 for (i = 0; i < acfg->method_order->len; ++i) {
5637 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5643 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5645 //printf ("No method found matching '%s'.\n", name);
5651 /* Add missing methods */
5653 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5655 for (i = 0; i < acfg->method_order->len; ++i) {
5656 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5662 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5664 unordered = g_list_reverse (unordered);
5665 for (l = unordered; l; l = l->next)
5666 g_ptr_array_add (acfg->method_order, l->data);
5669 /* Used by the LLVM backend */
5671 mono_aot_get_got_offset (MonoJumpInfo *ji)
5673 return get_got_offset (llvm_acfg, ji);
5677 mono_aot_get_method_name (MonoCompile *cfg)
5679 if (llvm_acfg->aot_opts.static_link)
5680 /* Include the assembly name too to avoid duplicate symbol errors */
5681 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5683 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5687 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5689 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5690 MonoPltEntry *plt_entry;
5693 ji->data.target = data;
5695 if (!can_encode_patch (llvm_acfg, ji))
5698 plt_entry = get_plt_entry (llvm_acfg, ji);
5699 plt_entry->llvm_used = TRUE;
5701 #if defined(__APPLE__)
5702 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5704 return g_strdup_printf (plt_entry->llvm_symbol);
5709 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5713 mono_acfg_lock (llvm_acfg);
5714 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5715 mono_acfg_unlock (llvm_acfg);
5725 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5729 emit_llvm_file (MonoAotCompile *acfg)
5731 char *command, *opts;
5733 MonoJumpInfo *patch_info;
5736 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5740 /* Compute the final size of the got */
5741 for (i = 0; i < acfg->nmethods; ++i) {
5742 if (acfg->cfgs [i]) {
5743 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5744 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5745 if (!is_plt_patch (patch_info))
5746 get_got_offset (acfg, patch_info);
5748 get_plt_entry (acfg, patch_info);
5754 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5756 if (acfg->aot_opts.full_aot) {
5760 * Need to add the got entries used by the trampolines.
5761 * This is only a conservative approximation.
5763 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5764 /* For the generic + rgctx trampolines */
5765 acfg->final_got_size += 200;
5766 /* For the specific trampolines */
5767 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5768 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5773 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5776 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5777 * a lot of time, and doesn't seem to save much space.
5778 * The following optimizations cannot be enabled:
5780 * - 'jump-threading' changes our blockaddress references to int constants.
5781 * - 'basiccg' fails because it contains:
5782 * if (CS && !isa<IntrinsicInst>(II)) {
5783 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5784 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5785 * The opt list below was produced by taking the output of:
5786 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5787 * then removing tailcallelim + the global opts, and adding a second gvn.
5789 opts = g_strdup ("-instcombine -simplifycfg");
5790 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");
5792 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5793 printf ("Executing opt: %s\n", command);
5794 if (system (command) != 0) {
5800 if (!acfg->llc_args)
5801 acfg->llc_args = g_string_new ("");
5803 /* Verbose asm slows down llc greatly */
5804 g_string_append (acfg->llc_args, " -asm-verbose=false");
5806 if (acfg->aot_opts.mtriple)
5807 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5809 if (llvm_acfg->aot_opts.static_link)
5810 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5812 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5813 unlink (acfg->tmpfname);
5815 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);
5817 printf ("Executing llc: %s\n", command);
5819 if (system (command) != 0) {
5826 emit_code (MonoAotCompile *acfg)
5828 int oindex, i, prev_index;
5830 char end_symbol [256];
5832 #if defined(TARGET_POWERPC64)
5833 sprintf (symbol, ".Lgot_addr");
5834 emit_section_change (acfg, ".text", 0);
5835 emit_alignment (acfg, 8);
5836 emit_label (acfg, symbol);
5837 emit_pointer (acfg, acfg->got_symbol);
5841 * This global symbol is used to compute the address of each method using the
5842 * code_offsets array. It is also used to compute the memory ranges occupied by
5843 * AOT code, so it must be equal to the address of the first emitted method.
5845 sprintf (symbol, "methods");
5846 emit_section_change (acfg, ".text", 0);
5847 emit_alignment (acfg, 8);
5849 for (i = 0; i < acfg->nmethods; ++i) {
5850 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5851 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5855 if (i == acfg->nmethods)
5856 /* No LLVM compiled methods */
5857 emit_label (acfg, symbol);
5859 emit_label (acfg, symbol);
5863 * Emit some padding so the local symbol for the first method doesn't have the
5864 * same address as 'methods'.
5866 #if defined(__default_codegen__)
5867 emit_zero_bytes (acfg, 16);
5868 #elif defined(__native_client_codegen__)
5870 const int kPaddingSize = 16;
5871 guint8 pad_buffer[kPaddingSize];
5872 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5873 emit_bytes (acfg, pad_buffer, kPaddingSize);
5877 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5881 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5883 cfg = acfg->cfgs [i];
5888 method = cfg->orig_method;
5890 /* Emit unbox trampoline */
5891 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5892 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
5894 emit_section_change (acfg, ".text", 0);
5895 #ifdef __native_client_codegen__
5896 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5899 if (acfg->thumb_mixed && cfg->compile_llvm)
5900 fprintf (acfg->fp, "\n.thumb_func\n");
5902 emit_label (acfg, symbol);
5904 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5907 if (cfg->compile_llvm)
5908 acfg->stats.llvm_count ++;
5910 emit_method_code (acfg, cfg);
5913 sprintf (symbol, "methods_end");
5914 emit_section_change (acfg, ".text", 0);
5915 emit_alignment (acfg, 8);
5916 emit_label (acfg, symbol);
5919 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5920 * from optimizing them away, since it doesn't see that code_offsets references them.
5921 * JITted methods don't need this since they are referenced using assembler local
5923 * FIXME: This is why write-symbols doesn't work on OSX ?
5925 if (acfg->llvm && acfg->need_no_dead_strip) {
5926 fprintf (acfg->fp, "\n");
5927 for (i = 0; i < acfg->nmethods; ++i) {
5928 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5929 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5933 sprintf (symbol, "code_offsets");
5934 emit_section_change (acfg, RODATA_SECT, 1);
5935 emit_alignment (acfg, 8);
5936 emit_label (acfg, symbol);
5938 acfg->stats.offsets_size += acfg->nmethods * 4;
5940 sprintf (end_symbol, "methods");
5941 for (i = 0; i < acfg->nmethods; ++i) {
5942 if (acfg->cfgs [i]) {
5943 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5945 emit_int32 (acfg, 0xffffffff);
5950 /* Emit a sorted table mapping methods to their unbox trampolines */
5951 sprintf (symbol, "unbox_trampolines");
5952 emit_section_change (acfg, RODATA_SECT, 1);
5953 emit_alignment (acfg, 8);
5954 emit_label (acfg, symbol);
5956 sprintf (end_symbol, "methods");
5958 for (i = 0; i < acfg->nmethods; ++i) {
5963 cfg = acfg->cfgs [i];
5967 method = cfg->orig_method;
5969 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5970 index = get_method_index (acfg, method);
5971 sprintf (symbol, "ut_%d", index);
5973 emit_int32 (acfg, index);
5974 emit_symbol_diff (acfg, symbol, end_symbol, 0);
5975 /* Make sure the table is sorted by index */
5976 g_assert (index > prev_index);
5980 sprintf (symbol, "unbox_trampolines_end");
5981 emit_label (acfg, symbol);
5985 emit_info (MonoAotCompile *acfg)
5991 offsets = g_new0 (gint32, acfg->nmethods);
5993 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5994 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5996 if (acfg->cfgs [i]) {
5997 emit_method_info (acfg, acfg->cfgs [i]);
5998 offsets [i] = acfg->cfgs [i]->method_info_offset;
6004 sprintf (symbol, "method_info_offsets");
6005 emit_section_change (acfg, RODATA_SECT, 1);
6006 emit_alignment (acfg, 8);
6007 emit_label (acfg, symbol);
6009 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6014 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6016 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6017 #define mix(a,b,c) { \
6018 a -= c; a ^= rot(c, 4); c += b; \
6019 b -= a; b ^= rot(a, 6); a += c; \
6020 c -= b; c ^= rot(b, 8); b += a; \
6021 a -= c; a ^= rot(c,16); c += b; \
6022 b -= a; b ^= rot(a,19); a += c; \
6023 c -= b; c ^= rot(b, 4); b += a; \
6025 #define final(a,b,c) { \
6026 c ^= b; c -= rot(b,14); \
6027 a ^= c; a -= rot(c,11); \
6028 b ^= a; b -= rot(a,25); \
6029 c ^= b; c -= rot(b,16); \
6030 a ^= c; a -= rot(c,4); \
6031 b ^= a; b -= rot(a,14); \
6032 c ^= b; c -= rot(b,24); \
6036 mono_aot_type_hash (MonoType *t1)
6038 guint hash = t1->type;
6040 hash |= t1->byref << 6; /* do not collide with t1->type values */
6042 case MONO_TYPE_VALUETYPE:
6043 case MONO_TYPE_CLASS:
6044 case MONO_TYPE_SZARRAY:
6045 /* check if the distribution is good enough */
6046 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6048 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6049 case MONO_TYPE_ARRAY:
6050 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6051 case MONO_TYPE_GENERICINST:
6052 return ((hash << 5) - hash) ^ 0;
6059 * mono_aot_method_hash:
6061 * Return a hash code for methods which only depends on metadata.
6064 mono_aot_method_hash (MonoMethod *method)
6066 MonoMethodSignature *sig;
6070 guint32 *hashes_start, *hashes;
6072 MonoGenericInst *ginst = NULL;
6074 /* Similar to the hash in mono_method_get_imt_slot () */
6076 sig = mono_method_signature (method);
6078 if (method->is_inflated)
6079 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6081 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6082 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6083 hashes = hashes_start;
6085 /* Some wrappers are assigned to random classes */
6086 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6087 klass = method->klass;
6089 klass = mono_defaults.object_class;
6091 if (!method->wrapper_type) {
6092 char *full_name = mono_type_full_name (&klass->byval_arg);
6094 hashes [0] = mono_metadata_str_hash (full_name);
6098 hashes [0] = mono_metadata_str_hash (klass->name);
6099 hashes [1] = mono_metadata_str_hash (klass->name_space);
6101 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6102 /* The method name includes a stringified pointer */
6105 hashes [2] = mono_metadata_str_hash (method->name);
6106 hashes [3] = method->wrapper_type;
6107 hashes [4] = mono_aot_type_hash (sig->ret);
6109 for (i = 0; i < sig->param_count; i++) {
6110 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6113 for (i = 0; i < ginst->type_argc; ++i)
6114 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6116 g_assert (hindex == hashes_count);
6118 /* Setup internal state */
6119 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6121 /* Handle most of the hashes */
6122 while (hashes_count > 3) {
6131 /* Handle the last 3 hashes (all the case statements fall through) */
6132 switch (hashes_count) {
6133 case 3 : c += hashes [2];
6134 case 2 : b += hashes [1];
6135 case 1 : a += hashes [0];
6137 case 0: /* nothing left to add */
6141 free (hashes_start);
6150 * mono_aot_wrapper_name:
6152 * Return a string which uniqely identifies the given wrapper method.
6155 mono_aot_wrapper_name (MonoMethod *method)
6157 char *name, *tmpsig, *klass_desc;
6159 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6161 switch (method->wrapper_type) {
6162 case MONO_WRAPPER_RUNTIME_INVOKE:
6163 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6164 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6166 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6169 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6170 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6171 g_free (klass_desc);
6181 * mono_aot_get_array_helper_from_wrapper;
6183 * Get the helper method in Array called by an array wrapper method.
6186 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6190 MonoGenericContext ctx;
6191 MonoType *args [16];
6192 char *mname, *iname, *s, *s2, *helper_name = NULL;
6194 prefix = "System.Collections.Generic";
6195 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6196 s2 = strstr (s, "`1.");
6202 //printf ("X: %s %s\n", iname, mname);
6204 if (!strcmp (iname, "IList"))
6205 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6207 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6208 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6210 g_free (helper_name);
6213 if (m->is_generic) {
6214 memset (&ctx, 0, sizeof (ctx));
6215 args [0] = &method->klass->element_class->byval_arg;
6216 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6217 m = mono_class_inflate_generic_method (m, &ctx);
6223 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6225 typedef struct HashEntry {
6226 guint32 key, value, index;
6227 struct HashEntry *next;
6231 * emit_extra_methods:
6233 * Emit methods which are not in the METHOD table, like wrappers.
6236 emit_extra_methods (MonoAotCompile *acfg)
6238 int i, table_size, buf_size;
6241 guint32 *info_offsets;
6244 HashEntry *entry, *new_entry;
6245 int nmethods, max_chain_length;
6248 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6250 /* Emit method info */
6252 for (i = 0; i < acfg->extra_methods->len; ++i) {
6253 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6254 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6260 p = buf = g_malloc (buf_size);
6264 method = cfg->method_to_register;
6266 encode_method_ref (acfg, method, p, &p);
6268 g_assert ((p - buf) < buf_size);
6270 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6275 * Construct a chained hash table for mapping indexes in extra_method_info to
6278 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6279 table = g_ptr_array_sized_new (table_size);
6280 for (i = 0; i < table_size; ++i)
6281 g_ptr_array_add (table, NULL);
6282 chain_lengths = g_new0 (int, table_size);
6283 max_chain_length = 0;
6284 for (i = 0; i < acfg->extra_methods->len; ++i) {
6285 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6286 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6292 key = info_offsets [i];
6293 value = get_method_index (acfg, method);
6295 hash = mono_aot_method_hash (method) % table_size;
6297 chain_lengths [hash] ++;
6298 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6300 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6301 new_entry->key = key;
6302 new_entry->value = value;
6304 entry = g_ptr_array_index (table, hash);
6305 if (entry == NULL) {
6306 new_entry->index = hash;
6307 g_ptr_array_index (table, hash) = new_entry;
6310 entry = entry->next;
6312 entry->next = new_entry;
6313 new_entry->index = table->len;
6314 g_ptr_array_add (table, new_entry);
6318 //printf ("MAX: %d\n", max_chain_length);
6320 /* Emit the table */
6321 sprintf (symbol, "extra_method_table");
6322 emit_section_change (acfg, RODATA_SECT, 0);
6323 emit_alignment (acfg, 8);
6324 emit_label (acfg, symbol);
6326 emit_int32 (acfg, table_size);
6327 for (i = 0; i < table->len; ++i) {
6328 HashEntry *entry = g_ptr_array_index (table, i);
6330 if (entry == NULL) {
6331 emit_int32 (acfg, 0);
6332 emit_int32 (acfg, 0);
6333 emit_int32 (acfg, 0);
6335 //g_assert (entry->key > 0);
6336 emit_int32 (acfg, entry->key);
6337 emit_int32 (acfg, entry->value);
6339 emit_int32 (acfg, entry->next->index);
6341 emit_int32 (acfg, 0);
6346 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6347 * This is used by mono_aot_find_jit_info ().
6349 sprintf (symbol, "extra_method_info_offsets");
6350 emit_section_change (acfg, RODATA_SECT, 0);
6351 emit_alignment (acfg, 8);
6352 emit_label (acfg, symbol);
6354 emit_int32 (acfg, acfg->extra_methods->len);
6355 for (i = 0; i < acfg->extra_methods->len; ++i) {
6356 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6358 emit_int32 (acfg, get_method_index (acfg, method));
6359 emit_int32 (acfg, info_offsets [i]);
6364 emit_exception_info (MonoAotCompile *acfg)
6370 offsets = g_new0 (gint32, acfg->nmethods);
6371 for (i = 0; i < acfg->nmethods; ++i) {
6372 if (acfg->cfgs [i]) {
6373 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6374 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6380 sprintf (symbol, "ex_info_offsets");
6381 emit_section_change (acfg, RODATA_SECT, 1);
6382 emit_alignment (acfg, 8);
6383 emit_label (acfg, symbol);
6385 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6390 emit_unwind_info (MonoAotCompile *acfg)
6396 * The unwind info contains a lot of duplicates so we emit each unique
6397 * entry once, and only store the offset from the start of the table in the
6401 sprintf (symbol, "unwind_info");
6402 emit_section_change (acfg, RODATA_SECT, 1);
6403 emit_alignment (acfg, 8);
6404 emit_label (acfg, symbol);
6406 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6407 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6408 guint8 *unwind_info;
6409 guint32 unwind_info_len;
6413 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6416 encode_value (unwind_info_len, p, &p);
6417 emit_bytes (acfg, buf, p - buf);
6418 emit_bytes (acfg, unwind_info, unwind_info_len);
6420 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6425 emit_class_info (MonoAotCompile *acfg)
6431 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6432 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6433 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6435 sprintf (symbol, "class_info_offsets");
6436 emit_section_change (acfg, RODATA_SECT, 1);
6437 emit_alignment (acfg, 8);
6438 emit_label (acfg, symbol);
6440 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6444 typedef struct ClassNameTableEntry {
6445 guint32 token, index;
6446 struct ClassNameTableEntry *next;
6447 } ClassNameTableEntry;
6450 emit_class_name_table (MonoAotCompile *acfg)
6453 guint32 token, hash;
6458 ClassNameTableEntry *entry, *new_entry;
6461 * Construct a chained hash table for mapping class names to typedef tokens.
6463 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6464 table = g_ptr_array_sized_new (table_size);
6465 for (i = 0; i < table_size; ++i)
6466 g_ptr_array_add (table, NULL);
6467 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6468 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6469 klass = mono_class_get (acfg->image, token);
6471 mono_loader_clear_error ();
6474 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6475 hash = mono_metadata_str_hash (full_name) % table_size;
6478 /* FIXME: Allocate from the mempool */
6479 new_entry = g_new0 (ClassNameTableEntry, 1);
6480 new_entry->token = token;
6482 entry = g_ptr_array_index (table, hash);
6483 if (entry == NULL) {
6484 new_entry->index = hash;
6485 g_ptr_array_index (table, hash) = new_entry;
6488 entry = entry->next;
6490 entry->next = new_entry;
6491 new_entry->index = table->len;
6492 g_ptr_array_add (table, new_entry);
6496 /* Emit the table */
6497 sprintf (symbol, "class_name_table");
6498 emit_section_change (acfg, RODATA_SECT, 0);
6499 emit_alignment (acfg, 8);
6500 emit_label (acfg, symbol);
6502 /* FIXME: Optimize memory usage */
6503 g_assert (table_size < 65000);
6504 emit_int16 (acfg, table_size);
6505 g_assert (table->len < 65000);
6506 for (i = 0; i < table->len; ++i) {
6507 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6509 if (entry == NULL) {
6510 emit_int16 (acfg, 0);
6511 emit_int16 (acfg, 0);
6513 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6515 emit_int16 (acfg, entry->next->index);
6517 emit_int16 (acfg, 0);
6523 emit_image_table (MonoAotCompile *acfg)
6529 * The image table is small but referenced in a lot of places.
6530 * So we emit it at once, and reference its elements by an index.
6533 sprintf (symbol, "image_table");
6534 emit_section_change (acfg, RODATA_SECT, 1);
6535 emit_alignment (acfg, 8);
6536 emit_label (acfg, symbol);
6538 emit_int32 (acfg, acfg->image_table->len);
6539 for (i = 0; i < acfg->image_table->len; i++) {
6540 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6541 MonoAssemblyName *aname = &image->assembly->aname;
6543 /* FIXME: Support multi-module assemblies */
6544 g_assert (image->assembly->image == image);
6546 emit_string (acfg, image->assembly_name);
6547 emit_string (acfg, image->guid);
6548 emit_string (acfg, aname->culture ? aname->culture : "");
6549 emit_string (acfg, (const char*)aname->public_key_token);
6551 emit_alignment (acfg, 8);
6552 emit_int32 (acfg, aname->flags);
6553 emit_int32 (acfg, aname->major);
6554 emit_int32 (acfg, aname->minor);
6555 emit_int32 (acfg, aname->build);
6556 emit_int32 (acfg, aname->revision);
6561 emit_got_info (MonoAotCompile *acfg)
6564 int i, first_plt_got_patch, buf_size;
6566 guint32 *got_info_offsets;
6568 /* Add the patches needed by the PLT to the GOT */
6569 acfg->plt_got_offset_base = acfg->got_offset;
6570 first_plt_got_patch = acfg->got_patches->len;
6571 for (i = 1; i < acfg->plt_offset; ++i) {
6572 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6574 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6576 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6579 acfg->got_offset += acfg->plt_offset;
6583 * - optimize offsets table.
6584 * - reduce number of exported symbols.
6585 * - emit info for a klass only once.
6586 * - determine when a method uses a GOT slot which is guaranteed to be already
6588 * - clean up and document the code.
6589 * - use String.Empty in class libs.
6592 /* Encode info required to decode shared GOT entries */
6593 buf_size = acfg->got_patches->len * 128;
6594 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6595 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6596 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6598 if (acfg->plt_offset)
6599 acfg->plt_got_info_offsets [0] = 0;
6600 for (i = 0; i < acfg->got_patches->len; ++i) {
6601 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6606 encode_value (ji->type, p, &p);
6608 encode_patch (acfg, ji, p, &p);
6609 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6610 g_assert (p - buf <= buf_size);
6611 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6613 if (i >= first_plt_got_patch)
6614 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6615 acfg->stats.got_info_size += p - buf;
6618 /* Emit got_info_offsets table */
6619 sprintf (symbol, "got_info_offsets");
6620 emit_section_change (acfg, RODATA_SECT, 1);
6621 emit_alignment (acfg, 8);
6622 emit_label (acfg, symbol);
6624 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6625 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6629 emit_got (MonoAotCompile *acfg)
6634 /* Don't make GOT global so accesses to it don't need relocations */
6635 sprintf (symbol, "%s", acfg->got_symbol);
6636 emit_section_change (acfg, ".bss", 0);
6637 emit_alignment (acfg, 8);
6638 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6639 emit_label (acfg, symbol);
6640 if (acfg->got_offset > 0)
6641 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6643 sprintf (symbol, "got_end");
6644 emit_label (acfg, symbol);
6648 typedef struct GlobalsTableEntry {
6649 guint32 value, index;
6650 struct GlobalsTableEntry *next;
6651 } GlobalsTableEntry;
6654 emit_globals (MonoAotCompile *acfg)
6660 GlobalsTableEntry *entry, *new_entry;
6662 if (!acfg->aot_opts.static_link)
6666 * When static linking, we emit a table containing our globals.
6670 * Construct a chained hash table for mapping global names to their index in
6671 * the globals table.
6673 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6674 table = g_ptr_array_sized_new (table_size);
6675 for (i = 0; i < table_size; ++i)
6676 g_ptr_array_add (table, NULL);
6677 for (i = 0; i < acfg->globals->len; ++i) {
6678 char *name = g_ptr_array_index (acfg->globals, i);
6680 hash = mono_metadata_str_hash (name) % table_size;
6682 /* FIXME: Allocate from the mempool */
6683 new_entry = g_new0 (GlobalsTableEntry, 1);
6684 new_entry->value = i;
6686 entry = g_ptr_array_index (table, hash);
6687 if (entry == NULL) {
6688 new_entry->index = hash;
6689 g_ptr_array_index (table, hash) = new_entry;
6692 entry = entry->next;
6694 entry->next = new_entry;
6695 new_entry->index = table->len;
6696 g_ptr_array_add (table, new_entry);
6700 /* Emit the table */
6701 sprintf (symbol, ".Lglobals_hash");
6702 emit_section_change (acfg, RODATA_SECT, 0);
6703 emit_alignment (acfg, 8);
6704 emit_label (acfg, symbol);
6706 /* FIXME: Optimize memory usage */
6707 g_assert (table_size < 65000);
6708 emit_int16 (acfg, table_size);
6709 for (i = 0; i < table->len; ++i) {
6710 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6712 if (entry == NULL) {
6713 emit_int16 (acfg, 0);
6714 emit_int16 (acfg, 0);
6716 emit_int16 (acfg, entry->value + 1);
6718 emit_int16 (acfg, entry->next->index);
6720 emit_int16 (acfg, 0);
6724 /* Emit the names */
6725 for (i = 0; i < acfg->globals->len; ++i) {
6726 char *name = g_ptr_array_index (acfg->globals, i);
6728 sprintf (symbol, "name_%d", i);
6729 emit_section_change (acfg, RODATA_SECT, 1);
6731 emit_alignment (acfg, 4);
6733 emit_label (acfg, symbol);
6734 emit_string (acfg, name);
6737 /* Emit the globals table */
6738 sprintf (symbol, "globals");
6739 emit_section_change (acfg, ".data", 0);
6740 /* This is not a global, since it is accessed by the init function */
6741 emit_alignment (acfg, 8);
6742 emit_label (acfg, symbol);
6744 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6745 emit_pointer (acfg, symbol);
6747 for (i = 0; i < acfg->globals->len; ++i) {
6748 char *name = g_ptr_array_index (acfg->globals, i);
6750 sprintf (symbol, "name_%d", i);
6751 emit_pointer (acfg, symbol);
6753 sprintf (symbol, "%s", name);
6754 emit_pointer (acfg, symbol);
6756 /* Null terminate the table */
6757 emit_int32 (acfg, 0);
6758 emit_int32 (acfg, 0);
6762 emit_autoreg (MonoAotCompile *acfg)
6767 * Emit a function into the .ctor section which will be called by the ELF
6768 * loader to register this module with the runtime.
6770 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6773 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6775 arch_emit_autoreg (acfg, symbol);
6781 emit_mem_end (MonoAotCompile *acfg)
6785 sprintf (symbol, "mem_end");
6786 emit_section_change (acfg, ".text", 1);
6787 emit_alignment (acfg, 8);
6788 emit_label (acfg, symbol);
6792 * Emit a structure containing all the information not stored elsewhere.
6795 emit_file_info (MonoAotCompile *acfg)
6800 const char *gc_name;
6803 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6805 if (acfg->aot_opts.bind_to_runtime_version) {
6806 build_info = mono_get_runtime_build_info ();
6807 emit_string_symbol (acfg, "runtime_version", build_info);
6808 g_free (build_info);
6810 emit_string_symbol (acfg, "runtime_version", "");
6813 /* Emit a string holding the assembly name */
6814 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6817 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6820 gc_name = mono_gc_get_gc_name ();
6821 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6823 sprintf (symbol, "mono_aot_file_info");
6824 emit_section_change (acfg, ".data", 0);
6825 emit_alignment (acfg, 8);
6826 emit_label (acfg, symbol);
6827 if (!acfg->aot_opts.static_link)
6828 emit_global (acfg, symbol, FALSE);
6830 /* The data emitted here must match MonoAotFileInfo. */
6832 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6833 emit_int32 (acfg, 0);
6836 * We emit pointers to our data structures instead of emitting global symbols which
6837 * point to them, to reduce the number of globals, and because using globals leads to
6838 * various problems (i.e. arm/thumb).
6840 emit_pointer (acfg, acfg->got_symbol);
6841 emit_pointer (acfg, "methods");
6844 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6846 emit_pointer (acfg, "mono_eh_frame");
6848 emit_pointer (acfg, NULL);
6850 emit_pointer (acfg, "blob");
6851 emit_pointer (acfg, "class_name_table");
6852 emit_pointer (acfg, "class_info_offsets");
6853 emit_pointer (acfg, "method_info_offsets");
6854 emit_pointer (acfg, "ex_info_offsets");
6855 emit_pointer (acfg, "code_offsets");
6856 emit_pointer (acfg, "extra_method_info_offsets");
6857 emit_pointer (acfg, "extra_method_table");
6858 emit_pointer (acfg, "got_info_offsets");
6859 emit_pointer (acfg, "methods_end");
6860 emit_pointer (acfg, "unwind_info");
6861 emit_pointer (acfg, "mem_end");
6862 emit_pointer (acfg, "image_table");
6863 emit_pointer (acfg, "plt");
6864 emit_pointer (acfg, "plt_end");
6865 emit_pointer (acfg, "assembly_guid");
6866 emit_pointer (acfg, "runtime_version");
6867 if (acfg->num_trampoline_got_entries) {
6868 emit_pointer (acfg, "specific_trampolines");
6869 emit_pointer (acfg, "static_rgctx_trampolines");
6870 emit_pointer (acfg, "imt_thunks");
6872 emit_pointer (acfg, NULL);
6873 emit_pointer (acfg, NULL);
6874 emit_pointer (acfg, NULL);
6876 if (acfg->thumb_mixed) {
6877 emit_pointer (acfg, "thumb_end");
6879 emit_pointer (acfg, NULL);
6881 if (acfg->aot_opts.static_link) {
6882 emit_pointer (acfg, "globals");
6884 emit_pointer (acfg, NULL);
6886 emit_pointer (acfg, "assembly_name");
6887 emit_pointer (acfg, "unbox_trampolines");
6888 emit_pointer (acfg, "unbox_trampolines_end");
6890 emit_int32 (acfg, acfg->plt_got_offset_base);
6891 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6892 emit_int32 (acfg, acfg->plt_offset);
6893 emit_int32 (acfg, acfg->nmethods);
6894 emit_int32 (acfg, acfg->flags);
6895 emit_int32 (acfg, acfg->opts);
6896 emit_int32 (acfg, gc_name_offset);
6898 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6899 emit_int32 (acfg, acfg->num_trampolines [i]);
6900 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6901 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6902 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6903 emit_int32 (acfg, acfg->trampoline_size [i]);
6905 #if defined (TARGET_ARM) && defined (__APPLE__)
6910 t.type = MONO_TYPE_R8;
6911 mono_type_size (&t, &align);
6913 emit_int32 (acfg, align);
6915 t.type = MONO_TYPE_I8;
6916 mono_type_size (&t, &align);
6918 emit_int32 (acfg, align);
6921 emit_int32 (acfg, __alignof__ (double));
6922 emit_int32 (acfg, __alignof__ (gint64));
6925 if (acfg->aot_opts.static_link) {
6929 * Emit a global symbol which can be passed by an embedding app to
6930 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6933 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6934 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6936 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6939 /* Get rid of characters which cannot occur in symbols */
6941 for (p = symbol; *p; ++p) {
6942 if (!(isalnum (*p) || *p == '_'))
6945 acfg->static_linking_symbol = g_strdup (symbol);
6946 emit_global_inner (acfg, symbol, FALSE);
6947 emit_label (acfg, symbol);
6948 emit_pointer (acfg, "mono_aot_file_info");
6953 emit_blob (MonoAotCompile *acfg)
6957 sprintf (symbol, "blob");
6958 emit_section_change (acfg, RODATA_SECT, 1);
6959 emit_alignment (acfg, 8);
6960 emit_label (acfg, symbol);
6962 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6966 emit_dwarf_info (MonoAotCompile *acfg)
6968 #ifdef EMIT_DWARF_INFO
6970 char symbol [128], symbol2 [128];
6972 /* DIEs for methods */
6973 for (i = 0; i < acfg->nmethods; ++i) {
6974 MonoCompile *cfg = acfg->cfgs [i];
6979 // FIXME: LLVM doesn't define .Lme_...
6980 if (cfg->compile_llvm)
6983 sprintf (symbol, "%s", cfg->asm_symbol);
6984 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6986 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 ()));
6992 collect_methods (MonoAotCompile *acfg)
6995 MonoImage *image = acfg->image;
6997 /* Collect methods */
6998 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7000 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7002 method = mono_get_method (acfg->image, token, NULL);
7005 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7009 /* Load all methods eagerly to skip the slower lazy loading code */
7010 mono_class_setup_methods (method->klass);
7012 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7013 /* Compile the wrapper instead */
7014 /* We do this here instead of add_wrappers () because it is easy to do it here */
7015 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7019 /* FIXME: Some mscorlib methods don't have debug info */
7021 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7022 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7023 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7024 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7025 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7026 if (!mono_debug_lookup_method (method)) {
7027 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7034 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7035 add_method_with_index (acfg, method, i, FALSE);
7036 acfg->method_index ++;
7039 add_generic_instances (acfg);
7041 if (acfg->aot_opts.full_aot)
7042 add_wrappers (acfg);
7046 compile_methods (MonoAotCompile *acfg)
7050 if (acfg->aot_opts.nthreads > 0) {
7055 gpointer *user_data;
7056 MonoMethod **methods;
7058 methods_len = acfg->methods->len;
7060 len = acfg->methods->len / acfg->aot_opts.nthreads;
7063 * Partition the list of methods into fragments, and hand it to threads to
7066 threads = g_ptr_array_new ();
7067 /* Make a copy since acfg->methods is modified by compile_method () */
7068 methods = g_new0 (MonoMethod*, methods_len);
7069 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7070 for (i = 0; i < methods_len; ++i)
7071 methods [i] = g_ptr_array_index (acfg->methods, i);
7073 while (i < methods_len) {
7074 frag = g_ptr_array_new ();
7075 for (j = 0; j < len; ++j) {
7076 if (i < methods_len) {
7077 g_ptr_array_add (frag, methods [i]);
7082 user_data = g_new0 (gpointer, 3);
7083 user_data [0] = mono_domain_get ();
7084 user_data [1] = acfg;
7085 user_data [2] = frag;
7087 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7088 g_ptr_array_add (threads, handle);
7092 for (i = 0; i < threads->len; ++i) {
7093 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7099 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7100 for (i = methods_len; i < acfg->methods->len; ++i) {
7101 /* This can new methods to acfg->methods */
7102 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7107 compile_asm (MonoAotCompile *acfg)
7109 char *command, *objfile;
7110 char *outfile_name, *tmp_outfile_name;
7111 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7113 #if defined(TARGET_AMD64)
7114 #define AS_OPTIONS "--64"
7115 #elif defined(TARGET_POWERPC64)
7116 #define AS_OPTIONS "-a64 -mppc64"
7117 #define LD_OPTIONS "-m elf64ppc"
7118 #elif defined(sparc) && SIZEOF_VOID_P == 8
7119 #define AS_OPTIONS "-xarch=v9"
7120 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7121 #define AS_OPTIONS "-arch i386 -W"
7123 #define AS_OPTIONS ""
7126 #ifdef __native_client_codegen__
7127 #if defined(TARGET_AMD64)
7128 #define AS_NAME "nacl64-as"
7130 #define AS_NAME "nacl-as"
7133 #define AS_NAME "as"
7137 #define LD_OPTIONS ""
7140 #define EH_LD_OPTIONS ""
7142 if (acfg->aot_opts.asm_only) {
7143 printf ("Output file: '%s'.\n", acfg->tmpfname);
7144 if (acfg->aot_opts.static_link)
7145 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7149 if (acfg->aot_opts.static_link) {
7150 if (acfg->aot_opts.outfile)
7151 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7153 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7155 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7157 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);
7158 printf ("Executing the native assembler: %s\n", command);
7159 if (system (command) != 0) {
7167 if (acfg->aot_opts.static_link) {
7168 printf ("Output file: '%s'.\n", objfile);
7169 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7174 if (acfg->aot_opts.outfile)
7175 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7177 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7179 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7182 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7183 #elif defined(__ppc__) && defined(__APPLE__)
7184 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7185 #elif defined(HOST_WIN32)
7186 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7187 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7188 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7190 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7192 printf ("Executing the native linker: %s\n", command);
7193 if (system (command) != 0) {
7194 g_free (tmp_outfile_name);
7195 g_free (outfile_name);
7203 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7204 printf ("Stripping the binary: %s\n", com);
7208 #if defined(TARGET_ARM) && !defined(__APPLE__)
7210 * gas generates 'mapping symbols' each time code and data is mixed, which
7211 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7213 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7214 printf ("Stripping the binary: %s\n", command);
7215 if (system (command) != 0) {
7216 g_free (tmp_outfile_name);
7217 g_free (outfile_name);
7224 rename (tmp_outfile_name, outfile_name);
7226 g_free (tmp_outfile_name);
7227 g_free (outfile_name);
7230 if (acfg->aot_opts.save_temps)
7231 printf ("Retained input file.\n");
7233 unlink (acfg->tmpfname);
7238 static MonoAotCompile*
7239 acfg_create (MonoAssembly *ass, guint32 opts)
7241 MonoImage *image = ass->image;
7242 MonoAotCompile *acfg;
7245 acfg = g_new0 (MonoAotCompile, 1);
7246 acfg->methods = g_ptr_array_new ();
7247 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7248 acfg->method_depth = g_hash_table_new (NULL, NULL);
7249 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7250 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7251 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7252 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7253 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7254 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7255 acfg->got_patches = g_ptr_array_new ();
7256 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7257 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7258 acfg->image_hash = g_hash_table_new (NULL, NULL);
7259 acfg->image_table = g_ptr_array_new ();
7260 acfg->globals = g_ptr_array_new ();
7261 acfg->image = image;
7263 acfg->mempool = mono_mempool_new ();
7264 acfg->extra_methods = g_ptr_array_new ();
7265 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7266 acfg->unwind_ops = g_ptr_array_new ();
7267 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7268 acfg->method_order = g_ptr_array_new ();
7269 acfg->export_names = g_hash_table_new (NULL, NULL);
7270 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7271 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7272 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7273 InitializeCriticalSection (&acfg->mutex);
7279 acfg_free (MonoAotCompile *acfg)
7283 img_writer_destroy (acfg->w);
7284 for (i = 0; i < acfg->nmethods; ++i)
7286 g_free (acfg->cfgs [i]);
7287 g_free (acfg->cfgs);
7288 g_free (acfg->static_linking_symbol);
7289 g_free (acfg->got_symbol);
7290 g_free (acfg->plt_symbol);
7291 g_ptr_array_free (acfg->methods, TRUE);
7292 g_ptr_array_free (acfg->got_patches, TRUE);
7293 g_ptr_array_free (acfg->image_table, TRUE);
7294 g_ptr_array_free (acfg->globals, TRUE);
7295 g_ptr_array_free (acfg->unwind_ops, TRUE);
7296 g_hash_table_destroy (acfg->method_indexes);
7297 g_hash_table_destroy (acfg->method_depth);
7298 g_hash_table_destroy (acfg->plt_offset_to_entry);
7299 g_hash_table_destroy (acfg->patch_to_plt_entry);
7300 g_hash_table_destroy (acfg->patch_to_got_offset);
7301 g_hash_table_destroy (acfg->method_to_cfg);
7302 g_hash_table_destroy (acfg->token_info_hash);
7303 g_hash_table_destroy (acfg->image_hash);
7304 g_hash_table_destroy (acfg->unwind_info_offsets);
7305 g_hash_table_destroy (acfg->method_label_hash);
7306 g_hash_table_destroy (acfg->export_names);
7307 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7308 g_hash_table_destroy (acfg->klass_blob_hash);
7309 g_hash_table_destroy (acfg->method_blob_hash);
7310 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7311 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7312 g_free (acfg->patch_to_got_offset_by_type);
7313 mono_mempool_destroy (acfg->mempool);
7318 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7320 MonoImage *image = ass->image;
7322 MonoAotCompile *acfg;
7323 char *outfile_name, *tmp_outfile_name, *p;
7327 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7329 acfg = acfg_create (ass, opts);
7331 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7332 acfg->aot_opts.write_symbols = TRUE;
7333 acfg->aot_opts.ntrampolines = 1024;
7334 acfg->aot_opts.nrgctx_trampolines = 1024;
7335 acfg->aot_opts.nimt_trampolines = 128;
7336 acfg->aot_opts.llvm_path = g_strdup ("");
7338 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7340 if (acfg->aot_opts.static_link)
7341 acfg->aot_opts.autoreg = TRUE;
7343 //acfg->aot_opts.print_skipped_methods = TRUE;
7345 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7346 if (acfg->aot_opts.full_aot) {
7347 printf ("--aot=full is not supported on this platform.\n");
7352 if (acfg->aot_opts.static_link)
7353 acfg->aot_opts.asm_writer = TRUE;
7355 if (acfg->aot_opts.soft_debug) {
7356 MonoDebugOptions *opt = mini_get_debug_options ();
7358 opt->mdb_optimizations = TRUE;
7359 opt->gen_seq_points = TRUE;
7361 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7362 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7365 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7368 if (mono_use_llvm) {
7370 acfg->aot_opts.asm_writer = TRUE;
7371 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7373 if (acfg->aot_opts.soft_debug) {
7374 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7379 if (acfg->aot_opts.full_aot)
7380 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7382 load_profile_files (acfg);
7384 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7385 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7386 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7388 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7390 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7394 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7395 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7396 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7398 /* Get rid of characters which cannot occur in symbols */
7399 for (p = acfg->got_symbol_base; *p; ++p) {
7400 if (!(isalnum (*p) || *p == '_'))
7403 for (p = acfg->plt_symbol; *p; ++p) {
7404 if (!(isalnum (*p) || *p == '_'))
7407 for (p = acfg->assembly_name_sym; *p; ++p) {
7408 if (!(isalnum (*p) || *p == '_'))
7412 acfg->method_index = 1;
7414 collect_methods (acfg);
7416 acfg->cfgs_size = acfg->methods->len + 32;
7417 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7419 /* PLT offset 0 is reserved for the PLT trampoline */
7420 acfg->plt_offset = 1;
7425 mono_llvm_create_aot_module (acfg->got_symbol_base);
7429 /* GOT offset 0 is reserved for the address of the current assembly */
7433 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7434 ji->type = MONO_PATCH_INFO_IMAGE;
7435 ji->data.image = acfg->image;
7437 get_got_offset (acfg, ji);
7439 /* Slot 1 is reserved for the mscorlib got addr */
7440 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7441 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7442 get_got_offset (acfg, ji);
7444 /* This is very common */
7445 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7446 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7447 get_got_offset (acfg, ji);
7452 compile_methods (acfg);
7456 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7462 if (acfg->aot_opts.asm_only) {
7463 if (acfg->aot_opts.outfile)
7464 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7466 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7468 acfg->tmpfname = g_strdup ("temp.s");
7471 emit_llvm_file (acfg);
7475 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7476 if (acfg->aot_opts.outfile)
7477 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7479 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7482 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7483 * it might be in another file system so the rename () won't work.
7485 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7487 acfg->fp = fopen (tmp_outfile_name, "w");
7489 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7493 acfg->w = img_writer_create (acfg->fp, TRUE);
7494 acfg->use_bin_writer = TRUE;
7497 /* Append to the .s file created by llvm */
7498 /* FIXME: Use multiple files instead */
7499 acfg->fp = fopen (acfg->tmpfname, "a+");
7501 if (acfg->aot_opts.asm_only) {
7502 if (acfg->aot_opts.outfile)
7503 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7505 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7506 acfg->fp = fopen (acfg->tmpfname, "w+");
7508 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7509 acfg->fp = fdopen (i, "w+");
7511 if (acfg->fp == 0) {
7512 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7516 acfg->w = img_writer_create (acfg->fp, FALSE);
7518 tmp_outfile_name = NULL;
7519 outfile_name = NULL;
7522 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7524 /* Compute symbols for methods */
7525 for (i = 0; i < acfg->nmethods; ++i) {
7526 if (acfg->cfgs [i]) {
7527 MonoCompile *cfg = acfg->cfgs [i];
7528 int method_index = get_method_index (acfg, cfg->orig_method);
7530 if (COMPILE_LLVM (cfg))
7531 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7533 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7537 if (!acfg->aot_opts.nodebug)
7538 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7540 img_writer_emit_start (acfg->w);
7543 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7545 if (acfg->thumb_mixed) {
7548 * This global symbol marks the end of THUMB code, and the beginning of ARM
7549 * code generated by our JIT.
7551 sprintf (symbol, "thumb_end");
7552 emit_section_change (acfg, ".text", 0);
7553 emit_label (acfg, symbol);
7554 emit_zero_bytes (acfg, 16);
7556 fprintf (acfg->fp, ".arm\n");
7563 emit_extra_methods (acfg);
7565 emit_trampolines (acfg);
7567 emit_class_name_table (acfg);
7569 emit_got_info (acfg);
7571 emit_exception_info (acfg);
7573 emit_unwind_info (acfg);
7575 emit_class_info (acfg);
7579 emit_image_table (acfg);
7583 emit_file_info (acfg);
7587 emit_globals (acfg);
7589 emit_autoreg (acfg);
7592 emit_dwarf_info (acfg);
7593 mono_dwarf_writer_close (acfg->dwarf);
7596 emit_mem_end (acfg);
7598 if (acfg->need_pt_gnu_stack) {
7599 /* This is required so the .so doesn't have an executable stack */
7600 /* The bin writer already emits this */
7601 if (!acfg->use_bin_writer)
7602 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7607 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7610 g_assert (acfg->got_offset <= acfg->final_got_size);
7612 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);
7615 res = img_writer_emit_writeout (acfg->w);
7620 if (acfg->use_bin_writer) {
7621 int err = rename (tmp_outfile_name, outfile_name);
7624 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7628 res = compile_asm (acfg);
7635 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7637 printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
7638 if (acfg->stats.genericcount)
7639 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7640 if (acfg->stats.abscount)
7641 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7642 if (acfg->stats.lmfcount)
7643 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7644 if (acfg->stats.ocount)
7645 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7647 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7648 printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
7649 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7651 if (acfg->aot_opts.stats) {
7654 printf ("GOT slot distribution:\n");
7655 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7656 if (acfg->stats.got_slot_types [i])
7657 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7660 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);
7672 mono_aot_readonly_field_override (MonoClassField *field)
7678 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)