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)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internal.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
99 gboolean write_symbols;
100 gboolean metadata_only;
101 gboolean bind_to_runtime_version;
104 gboolean static_link;
108 gboolean dwarf_debug;
110 gboolean log_generics;
111 gboolean log_instances;
112 gboolean direct_pinvoke;
113 gboolean direct_icalls;
114 gboolean no_direct_calls;
115 gboolean use_trampolines_page;
116 gboolean no_instances;
121 int nrgctx_trampolines;
122 int nimt_trampolines;
123 int ngsharedvt_arg_trampolines;
124 int nrgctx_fetch_trampolines;
125 gboolean print_skipped_methods;
131 char *instances_logfile_path;
136 typedef struct MonoAotStats {
137 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
138 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
139 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
140 int got_slots, offsets_size;
141 int got_slot_types [MONO_PATCH_INFO_NONE];
142 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
143 int jit_time, gen_time, link_time;
146 typedef struct GotInfo {
147 GHashTable *patch_to_got_offset;
148 GHashTable **patch_to_got_offset_by_type;
149 GPtrArray *got_patches;
152 typedef struct MonoAotCompile {
155 GHashTable *method_indexes;
156 GHashTable *method_depth;
159 GHashTable **patch_to_plt_entry;
160 GHashTable *plt_offset_to_entry;
161 //GHashTable *patch_to_got_offset;
162 //GHashTable **patch_to_got_offset_by_type;
163 //GPtrArray *got_patches;
164 GotInfo got_info, llvm_got_info;
165 GHashTable *image_hash;
166 GHashTable *method_to_cfg;
167 GHashTable *token_info_hash;
168 GHashTable *method_to_pinvoke_import;
169 GPtrArray *extra_methods;
170 GPtrArray *image_table;
172 GPtrArray *method_order;
173 GHashTable *export_names;
174 /* Maps MonoClass* -> blob offset */
175 GHashTable *klass_blob_hash;
176 /* Maps MonoMethod* -> blob offset */
177 GHashTable *method_blob_hash;
178 guint32 *plt_got_info_offsets;
179 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
180 /* Number of GOT entries reserved for trampolines */
181 guint32 num_trampoline_got_entries;
182 guint32 tramp_page_size;
184 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
185 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
186 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
187 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
189 MonoAotOptions aot_opts;
193 MonoMemPool *mempool;
196 char *static_linking_symbol;
198 gboolean use_bin_writer;
199 gboolean gas_line_numbers;
200 /* Whenever to emit LLVM code into a separate object file */
201 gboolean llvm_separate;
202 /* Whenever to emit an object file directly from llc */
203 gboolean llvm_owriter;
205 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
215 char *got_symbol_base;
216 char *llvm_got_symbol_base;
218 char *llvm_got_symbol;
220 char *methods_symbol;
221 char *llvm_eh_frame_symbol;
222 GHashTable *method_label_hash;
223 const char *temp_prefix;
224 const char *user_symbol_prefix;
225 const char *llvm_label_prefix;
226 const char *inst_directive;
228 guint32 label_generator;
230 MonoAotFileFlags flags;
231 MonoDynamicStream blob;
232 MonoClass **typespec_classes;
235 char *assembly_name_sym;
236 GHashTable *plt_entry_debug_sym_cache;
237 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
238 GHashTable *ginst_hash;
239 GHashTable *dwarf_ln_filenames;
240 gboolean global_symbols;
241 int objc_selector_index, objc_selector_index_2;
242 GPtrArray *objc_selectors;
243 GHashTable *objc_selector_to_index;
245 FILE *instances_logfile;
250 char *symbol, *llvm_symbol, *debug_sym;
252 gboolean jit_used, llvm_used;
255 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
258 /* This points to the current acfg in LLVM mode */
259 static MonoAotCompile *llvm_acfg;
261 #ifdef HAVE_ARRAY_ELEM_INIT
262 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
263 #define MSGSTRFIELD1(line) str##line
264 static const struct msgstr_t {
265 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
266 #include "patch-info.h"
269 #define PATCH_INFO(a,b) b,
270 #include "patch-info.h"
273 static const gint16 opidx [] = {
274 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
275 #include "patch-info.h"
279 static G_GNUC_UNUSED const char*
280 get_patch_name (int info)
282 return (const char*)&opstr + opidx [info];
286 #define PATCH_INFO(a,b) b,
287 static const char* const
288 patch_types [MONO_PATCH_INFO_NUM + 1] = {
289 #include "patch-info.h"
293 static G_GNUC_UNUSED const char*
294 get_patch_name (int info)
296 return patch_types [info];
302 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
305 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
311 output = acfg->logfile;
315 va_start (args, format);
316 vfprintf (output, format, args);
321 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
327 output = acfg->logfile;
331 va_start (args, format);
332 vfprintf (output, format, args);
336 /* Wrappers around the image writer functions */
339 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
341 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
345 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
347 img_writer_emit_push_section (acfg->w, section_name, subsection);
351 emit_pop_section (MonoAotCompile *acfg)
353 img_writer_emit_pop_section (acfg->w);
357 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
359 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
363 emit_label (MonoAotCompile *acfg, const char *name)
365 img_writer_emit_label (acfg->w, name);
369 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
371 img_writer_emit_bytes (acfg->w, buf, size);
375 emit_string (MonoAotCompile *acfg, const char *value)
377 img_writer_emit_string (acfg->w, value);
381 emit_line (MonoAotCompile *acfg)
383 img_writer_emit_line (acfg->w);
387 emit_alignment (MonoAotCompile *acfg, int size)
389 img_writer_emit_alignment (acfg->w, size);
393 emit_alignment_code (MonoAotCompile *acfg, int size)
395 if (acfg->align_pad_value)
396 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
398 img_writer_emit_alignment (acfg->w, size);
402 emit_padding (MonoAotCompile *acfg, int size)
407 if (acfg->align_pad_value) {
408 for (i = 0; i < 16; ++i)
409 buf [i] = acfg->align_pad_value;
411 memset (buf, 0, sizeof (buf));
414 for (i = 0; i < size; i += 16) {
416 emit_bytes (acfg, buf, size - i);
418 emit_bytes (acfg, buf, 16);
423 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
425 img_writer_emit_pointer_unaligned (acfg->w, target);
429 emit_pointer (MonoAotCompile *acfg, const char *target)
431 img_writer_emit_pointer (acfg->w, target);
435 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
437 if (prefix [0] != '\0') {
438 char *s = g_strdup_printf ("%s%s", prefix, target);
439 img_writer_emit_pointer (acfg->w, s);
442 img_writer_emit_pointer (acfg->w, target);
447 emit_int16 (MonoAotCompile *acfg, int value)
449 img_writer_emit_int16 (acfg->w, value);
453 emit_int32 (MonoAotCompile *acfg, int value)
455 img_writer_emit_int32 (acfg->w, value);
459 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
461 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
465 emit_zero_bytes (MonoAotCompile *acfg, int num)
467 img_writer_emit_zero_bytes (acfg->w, num);
471 emit_byte (MonoAotCompile *acfg, guint8 val)
473 img_writer_emit_byte (acfg->w, val);
476 #ifdef __native_client_codegen__
478 emit_nacl_call_alignment (MonoAotCompile *acfg)
480 img_writer_emit_nacl_call_alignment (acfg->w);
484 static G_GNUC_UNUSED void
485 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
487 img_writer_emit_global (acfg->w, name, func);
491 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
493 if (acfg->aot_opts.no_dlsym) {
494 g_ptr_array_add (acfg->globals, g_strdup (name));
495 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
497 img_writer_emit_global (acfg->w, name, func);
502 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
504 img_writer_emit_symbol_size (acfg->w, name, end_label);
508 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
510 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
512 /* On apple, all symbols need to be aligned to avoid warnings from ld */
513 emit_alignment (acfg, 4);
515 img_writer_emit_label (acfg->w, name);
516 img_writer_emit_string (acfg->w, value);
519 static G_GNUC_UNUSED void
520 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
523 guint8 b = value & 0x7f;
525 if (value != 0) /* more bytes to come */
531 static G_GNUC_UNUSED void
532 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
535 gboolean negative = (value < 0);
542 /* the following is unnecessary if the
543 * implementation of >>= uses an arithmetic rather
544 * than logical shift for a signed left operand
548 value |= - ((gint64)1 <<(size - 7));
549 /* sign bit of byte is second high order bit (0x40) */
550 if ((value == 0 && !(byte & 0x40)) ||
551 (value == -1 && (byte & 0x40)))
555 emit_byte (acfg, byte);
559 static G_GNUC_UNUSED void
560 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
565 guint8 b = value & 0x7f;
567 if (value != 0) /* more bytes to come */
575 static G_GNUC_UNUSED void
576 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
579 gboolean negative = (value < 0);
587 /* the following is unnecessary if the
588 * implementation of >>= uses an arithmetic rather
589 * than logical shift for a signed left operand
593 value |= - (1 <<(size - 7));
594 /* sign bit of byte is second high order bit (0x40) */
595 if ((value == 0 && !(byte & 0x40)) ||
596 (value == -1 && (byte & 0x40)))
607 emit_unset_mode (MonoAotCompile *acfg)
609 img_writer_emit_unset_mode (acfg->w);
612 static G_GNUC_UNUSED void
613 emit_set_thumb_mode (MonoAotCompile *acfg)
615 emit_unset_mode (acfg);
616 fprintf (acfg->fp, ".code 16\n");
619 static G_GNUC_UNUSED void
620 emit_set_arm_mode (MonoAotCompile *acfg)
622 emit_unset_mode (acfg);
623 fprintf (acfg->fp, ".code 32\n");
627 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
632 g_assert (size % 4 == 0);
633 emit_unset_mode (acfg);
634 for (i = 0; i < size; i += 4)
635 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
637 emit_bytes (acfg, buf, size);
641 /* ARCHITECTURE SPECIFIC CODE */
643 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
644 #define EMIT_DWARF_INFO 1
647 #if defined(TARGET_ARM)
648 #define AOT_FUNC_ALIGNMENT 4
650 #define AOT_FUNC_ALIGNMENT 16
652 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
653 #undef AOT_FUNC_ALIGNMENT
654 #define AOT_FUNC_ALIGNMENT 32
657 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
658 #define PPC_LD_OP "ld"
659 #define PPC_LDX_OP "ldx"
661 #define PPC_LD_OP "lwz"
662 #define PPC_LDX_OP "lwzx"
666 #define AOT_TARGET_STR "AMD64"
671 #define AOT_TARGET_STR "ARM (MACH)"
673 #define AOT_TARGET_STR "ARM (!MACH)"
679 #define AOT_TARGET_STR "ARM64 (MACH)"
681 #define AOT_TARGET_STR "ARM64 (!MACH)"
685 #ifdef TARGET_POWERPC64
686 #ifdef __mono_ilp32__
687 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
689 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
692 #ifdef TARGET_POWERPC
693 #ifdef __mono_ilp32__
694 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
696 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
703 #define AOT_TARGET_STR "X86 (WIN32)"
704 #elif defined(__native_client_codegen__)
705 #define AOT_TARGET_STR "X86 (native client codegen)"
707 #define AOT_TARGET_STR "X86 (!native client codegen)"
711 #ifndef AOT_TARGET_STR
712 #define AOT_TARGET_STR ""
716 arch_init (MonoAotCompile *acfg)
718 acfg->llc_args = g_string_new ("");
719 acfg->as_args = g_string_new ("");
722 * The prefix LLVM likes to put in front of symbol names on darwin.
723 * The mach-os specs require this for globals, but LLVM puts them in front of all
724 * symbols. We need to handle this, since we need to refer to LLVM generated
727 acfg->llvm_label_prefix = "";
728 acfg->user_symbol_prefix = "";
730 #if defined(TARGET_X86)
731 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
734 #if defined(TARGET_AMD64)
735 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
737 acfg->align_pad_value = 0x90;
741 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
742 g_string_append (acfg->llc_args, "-mattr=+v6");
745 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
746 g_string_append (acfg->as_args, " -mfpu=vfp3");
748 g_string_append (acfg->llc_args, " -soft-float");
751 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
752 acfg->thumb_mixed = TRUE;
754 if (acfg->aot_opts.mtriple)
755 mono_arch_set_target (acfg->aot_opts.mtriple);
759 acfg->inst_directive = ".inst";
760 if (acfg->aot_opts.mtriple)
761 mono_arch_set_target (acfg->aot_opts.mtriple);
765 acfg->user_symbol_prefix = "_";
766 acfg->llvm_label_prefix = "_";
767 acfg->inst_directive = ".word";
768 acfg->need_no_dead_strip = TRUE;
769 acfg->aot_opts.gnu_asm = TRUE;
772 #if defined(__linux__) && !defined(TARGET_ARM)
773 acfg->need_pt_gnu_stack = TRUE;
777 acfg->global_symbols = TRUE;
783 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
787 #ifdef MONO_ARCH_AOT_SUPPORTED
789 * arch_emit_direct_call:
791 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
795 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
797 #if defined(TARGET_X86) || defined(TARGET_AMD64)
798 /* Need to make sure this is exactly 5 bytes long */
799 if (!acfg->use_bin_writer) {
800 emit_unset_mode (acfg);
801 fprintf (acfg->fp, "call %s\n", target);
803 emit_byte (acfg, '\xe8');
804 emit_symbol_diff (acfg, target, ".", -4);
807 #elif defined(TARGET_ARM)
808 if (acfg->use_bin_writer) {
815 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
816 emit_bytes (acfg, buf, 4);
818 emit_unset_mode (acfg);
820 fprintf (acfg->fp, "blx %s\n", target);
822 fprintf (acfg->fp, "bl %s\n", target);
825 #elif defined(TARGET_ARM64)
826 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
827 #elif defined(TARGET_POWERPC)
828 if (acfg->use_bin_writer) {
829 g_assert_not_reached ();
831 emit_unset_mode (acfg);
832 fprintf (acfg->fp, "bl %s\n", target);
836 g_assert_not_reached ();
843 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
845 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
846 * in in the 2. slot of every GOT, and require every method to place the GOT
847 * address in r30, even when it doesn't access the GOT otherwise. This way,
848 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
853 * PPC64 uses function descriptors which greatly complicate all code, since
854 * these are used very inconsistently in the runtime. Some functions like
855 * mono_compile_method () return ftn descriptors, while others like the
856 * trampoline creation functions do not.
857 * We assume that all GOT slots contain function descriptors, and create
858 * descriptors in aot-runtime.c when needed.
859 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
860 * from function descriptors, we could do the same, but it would require
861 * rewriting all the ppc/aot code to handle function descriptors properly.
862 * So instead, we use the same approach as on PPC32.
863 * This is a horrible mess, but fixing it would probably lead to an even bigger
869 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
872 #ifdef MONO_ARCH_AOT_SUPPORTED
874 * arch_emit_got_offset:
876 * The memory pointed to by CODE should hold native code for computing the GOT
877 * address. Emit this code while patching it with the offset between code and
878 * the GOT. CODE_SIZE is set to the number of bytes emitted.
881 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
883 #if defined(TARGET_POWERPC64)
884 g_assert (!acfg->use_bin_writer);
885 emit_unset_mode (acfg);
887 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
888 * unsupported relocations. So we store the got address into the .Lgot_addr
889 * symbol which is in the text segment, compute its address, and load it.
891 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
892 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
893 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
894 fprintf (acfg->fp, "add 30, 30, 0\n");
895 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
896 acfg->label_generator ++;
898 #elif defined(TARGET_POWERPC)
899 g_assert (!acfg->use_bin_writer);
900 emit_unset_mode (acfg);
901 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
902 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
903 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
904 acfg->label_generator ++;
907 guint32 offset = mono_arch_get_patch_offset (code);
908 emit_bytes (acfg, code, offset);
909 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
911 *code_size = offset + 4;
916 * arch_emit_got_access:
918 * The memory pointed to by CODE should hold native code for loading a GOT
919 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
920 * CODE_SIZE is set to the number of bytes emitted.
923 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
925 /* This needs to emit the same code as OP_AOTCONST */
928 /* mov reg, got+offset(%rip) */
929 if (acfg->llvm_separate) {
930 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
934 /* Decode reg, see amd64_mov_reg_membase () */
935 rex_r = code [0] & AMD64_REX_R;
936 g_assert (code [0] == 0x49 + rex_r);
937 g_assert (code [1] == 0x8b);
938 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
940 emit_unset_mode (acfg);
941 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
944 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
945 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
946 *code_size = mono_arch_get_patch_offset (code) + 4;
948 #elif defined(TARGET_X86)
949 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
950 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
951 *code_size = mono_arch_get_patch_offset (code) + 4;
952 #elif defined(TARGET_ARM)
953 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
954 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
955 *code_size = mono_arch_get_patch_offset (code) + 4;
956 #elif defined(TARGET_ARM64)
957 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
958 arm64_emit_got_access (acfg, code, got_slot, code_size);
959 #elif defined(TARGET_POWERPC)
964 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
966 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
967 g_assert (code - buf == 8);
968 emit_bytes (acfg, buf, code - buf);
969 *code_size = code - buf;
972 g_assert_not_reached ();
978 #ifdef MONO_ARCH_AOT_SUPPORTED
980 * arch_emit_objc_selector_ref:
982 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
985 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
987 #if defined(TARGET_ARM)
990 int lindex = acfg->objc_selector_index_2 ++;
993 emit_bytes (acfg, code, 8);
995 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
996 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
998 emit_label (acfg, symbol1);
999 img_writer_emit_unset_mode (acfg->w);
1000 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1003 #elif defined(TARGET_ARM64)
1004 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1006 g_assert_not_reached ();
1012 * arch_emit_plt_entry:
1014 * Emit code for the PLT entry with index INDEX.
1017 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
1019 #if defined(TARGET_X86)
1020 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1021 #if defined(__default_codegen__)
1022 /* jmp *<offset>(%ebx) */
1023 emit_byte (acfg, 0xff);
1024 emit_byte (acfg, 0xa3);
1025 emit_int32 (acfg, offset);
1026 /* Used by mono_aot_get_plt_info_offset */
1027 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1028 #elif defined(__native_client_codegen__)
1029 const guint8 kSizeOfNaClJmp = 11;
1030 guint8 bytes[kSizeOfNaClJmp];
1031 guint8 *pbytes = &bytes[0];
1033 x86_jump_membase32 (pbytes, X86_EBX, offset);
1034 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1035 /* four bytes of data, used by mono_arch_patch_plt_entry */
1036 /* For Native Client, make this work with data embedded in push. */
1037 emit_byte (acfg, 0x68); /* hide data in a push */
1038 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1039 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1040 #endif /*__native_client_codegen__*/
1041 #elif defined(TARGET_AMD64)
1042 #if defined(__default_codegen__)
1043 if (acfg->use_bin_writer) {
1044 emit_byte (acfg, '\xff');
1045 emit_byte (acfg, '\x25');
1046 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1048 emit_unset_mode (acfg);
1049 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
1051 /* Used by mono_aot_get_plt_info_offset */
1052 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1053 acfg->stats.plt_size += 10;
1054 #elif defined(__native_client_codegen__)
1056 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1057 guint8 *code = buf_aligned;
1059 /* mov <OFFSET>(%rip), %r11d */
1060 emit_byte (acfg, '\x45');
1061 emit_byte (acfg, '\x8b');
1062 emit_byte (acfg, '\x1d');
1063 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1065 amd64_jump_reg (code, AMD64_R11);
1066 /* This should be constant for the plt patch */
1067 g_assert ((size_t)(code-buf_aligned) == 10);
1068 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1070 /* Hide data in a push imm32 so it passes validation */
1071 emit_byte (acfg, 0x68); /* push */
1072 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1073 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1074 #endif /*__native_client_codegen__*/
1075 #elif defined(TARGET_ARM)
1080 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1081 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1082 emit_bytes (acfg, buf, code - buf);
1083 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1084 /* Used by mono_aot_get_plt_info_offset */
1085 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1086 #elif defined(TARGET_ARM64)
1087 arm64_emit_plt_entry (acfg, index);
1088 #elif defined(TARGET_POWERPC)
1089 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1091 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1092 g_assert (!acfg->use_bin_writer);
1093 emit_unset_mode (acfg);
1094 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1095 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1096 fprintf (acfg->fp, "add 11, 11, 30\n");
1097 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1098 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1099 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1100 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1102 fprintf (acfg->fp, "mtctr 11\n");
1103 fprintf (acfg->fp, "bctr\n");
1104 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1106 g_assert_not_reached ();
1111 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1113 #if defined(TARGET_ARM)
1115 /* LLVM calls the PLT entries using bl, so emit a stub */
1116 /* FIXME: Too much overhead on every call */
1117 fprintf (acfg->fp, ".thumb_func\n");
1118 fprintf (acfg->fp, "bx pc\n");
1119 fprintf (acfg->fp, "nop\n");
1120 fprintf (acfg->fp, ".arm\n");
1122 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1123 /* The caller already transitioned to thumb */
1124 /* The code below should be 12 bytes long */
1125 /* clang has trouble encoding these instructions, so emit the binary */
1127 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1128 /* thumb can't encode ld pc, [pc, ip] */
1129 fprintf (acfg->fp, "add ip, pc, ip\n");
1130 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1131 fprintf (acfg->fp, "bx ip\n");
1133 emit_set_thumb_mode (acfg);
1134 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1135 fprintf (acfg->fp, ".2byte 0x44fc\n");
1136 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1137 fprintf (acfg->fp, ".2byte 0x4760\n");
1138 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1139 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1140 emit_unset_mode (acfg);
1141 emit_set_arm_mode (acfg);
1143 g_assert_not_reached ();
1148 * arch_emit_specific_trampoline_pages:
1150 * Emits a page full of trampolines: each trampoline uses its own address to
1151 * lookup both the generic trampoline code and the data argument.
1152 * This page can be remapped in process multiple times so we can get an
1153 * unlimited number of trampolines.
1154 * Specifically this implementation uses the following trick: two memory pages
1155 * are allocated, with the first containing the data and the second containing the trampolines.
1156 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1157 * implementation does all the lifting.
1158 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1159 * on the arm 32 bit system.
1162 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1164 #if defined(TARGET_ARM)
1167 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1169 #define COMMON_TRAMP_SIZE 16
1170 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1171 int imm8, rot_amount;
1174 if (!acfg->aot_opts.use_trampolines_page)
1177 acfg->tramp_page_size = mono_pagesize ();
1179 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1180 emit_alignment (acfg, mono_pagesize ());
1181 emit_global (acfg, symbol, TRUE);
1182 emit_label (acfg, symbol);
1184 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1186 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1187 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1188 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1189 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1191 g_assert (code - buf == COMMON_TRAMP_SIZE);
1194 emit_bytes (acfg, buf, code - buf);
1196 for (i = 0; i < count; ++i) {
1198 ARM_PUSH (code, 0x5fff);
1200 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1201 g_assert (code - buf == 8);
1202 emit_bytes (acfg, buf, code - buf);
1205 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1206 * the instruction pointer address, so the generic trampoline at the start of the page
1207 * subtracts 4096 to get to the data page and loads the values
1208 * We again fit the generic trampiline in 16 bytes.
1210 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1211 emit_global (acfg, symbol, TRUE);
1212 emit_label (acfg, symbol);
1214 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1215 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1216 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1217 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1219 g_assert (code - buf == COMMON_TRAMP_SIZE);
1222 emit_bytes (acfg, buf, code - buf);
1224 for (i = 0; i < count; ++i) {
1226 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1228 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1229 g_assert (code - buf == 8);
1230 emit_bytes (acfg, buf, code - buf);
1234 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1236 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1237 emit_global (acfg, symbol, TRUE);
1238 emit_label (acfg, symbol);
1240 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1241 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1242 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1243 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1244 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1245 g_assert (code - buf == COMMON_TRAMP_SIZE);
1247 emit_bytes (acfg, buf, code - buf);
1249 for (i = 0; i < count; ++i) {
1251 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1253 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1254 g_assert (code - buf == 8);
1255 emit_bytes (acfg, buf, code - buf);
1258 /* now the imt trampolines: each specific trampolines puts in the ip register
1259 * the instruction pointer address, so the generic trampoline at the start of the page
1260 * subtracts 4096 to get to the data page and loads the values
1261 * We again fit the generic trampiline in 16 bytes.
1263 #define IMT_TRAMP_SIZE 72
1264 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1265 emit_global (acfg, symbol, TRUE);
1266 emit_label (acfg, symbol);
1268 /* Need at least two free registers, plus a slot for storing the pc */
1269 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1271 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1272 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1273 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1275 /* The IMT method is in v5, r0 has the imt array address */
1278 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1279 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1280 imt_found_check = code;
1281 ARM_B_COND (code, ARMCOND_EQ, 0);
1283 /* End-of-loop check */
1284 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1285 loop_end_check = code;
1286 ARM_B_COND (code, ARMCOND_EQ, 0);
1289 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1290 loop_branch_back = code;
1292 arm_patch (loop_branch_back, loop_start);
1295 arm_patch (imt_found_check, code);
1296 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1297 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1298 /* Save it to the third stack slot */
1299 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1300 /* Restore the registers and branch */
1301 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1304 arm_patch (loop_end_check, code);
1305 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1306 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1307 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1311 g_assert (code - buf == IMT_TRAMP_SIZE);
1312 emit_bytes (acfg, buf, code - buf);
1314 for (i = 0; i < count; ++i) {
1316 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1318 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1319 g_assert (code - buf == 8);
1320 emit_bytes (acfg, buf, code - buf);
1323 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1326 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1327 #elif defined(TARGET_ARM64)
1328 arm64_emit_specific_trampoline_pages (acfg);
1333 * arch_emit_specific_trampoline:
1335 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1336 * two GOT slots which contain the generic trampoline address and the trampoline
1337 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1340 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1343 * The trampolines created here are variations of the specific
1344 * trampolines created in mono_arch_create_specific_trampoline (). The
1346 * - the generic trampoline address is taken from a got slot.
1347 * - the offset of the got slot where the trampoline argument is stored
1348 * is embedded in the instruction stream, and the generic trampoline
1349 * can load the argument by loading the offset, adding it to the
1350 * address of the trampoline to get the address of the got slot, and
1351 * loading the argument from there.
1352 * - all the trampolines should be of the same length.
1354 #if defined(TARGET_AMD64)
1355 #if defined(__default_codegen__)
1356 /* This should be exactly 8 bytes long */
1358 /* call *<offset>(%rip) */
1359 if (acfg->llvm_separate) {
1360 emit_unset_mode (acfg);
1361 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1362 emit_zero_bytes (acfg, 2);
1364 emit_byte (acfg, '\x41');
1365 emit_byte (acfg, '\xff');
1366 emit_byte (acfg, '\x15');
1367 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1368 emit_zero_bytes (acfg, 1);
1370 #elif defined(__native_client_codegen__)
1372 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1373 guint8 *code = buf_aligned;
1378 /* Emit this call in 'code' so we can find out how long it is. */
1379 amd64_call_reg (code, AMD64_R11);
1380 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1381 call_len = code - call_start;
1383 /* The tramp_size is twice the NaCl alignment because it starts with */
1384 /* a call which needs to be aligned to the end of the boundary. */
1385 *tramp_size = kNaClAlignment*2;
1387 /* Emit nops to align call site below which is 7 bytes plus */
1388 /* the length of the call sequence emitted above. */
1389 /* Note: this requires the specific trampoline starts on a */
1390 /* kNaclAlignedment aligned address, which it does because */
1391 /* it's its own function that is aligned. */
1392 guint8 nop_buf[256];
1393 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1394 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1395 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1397 /* The trampoline is stored at the offset'th pointer, the -4 is */
1398 /* present because RIP relative addressing starts at the end of */
1399 /* the current instruction, while the label "." is relative to */
1400 /* the beginning of the current asm location, which in this case */
1401 /* is not the mov instruction, but the offset itself, due to the */
1402 /* way the bytes and ints are emitted here. */
1403 got_offset = (offset * sizeof(gpointer)) - 4;
1405 /* mov <OFFSET>(%rip), %r11d */
1406 emit_byte (acfg, '\x45');
1407 emit_byte (acfg, '\x8b');
1408 emit_byte (acfg, '\x1d');
1409 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1412 emit_bytes (acfg, call_start, call_len);
1414 /* The arg is stored at the offset+1 pointer, relative to beginning */
1415 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1416 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1418 /* We can't emit this data directly, hide in a "push imm32" */
1419 emit_byte (acfg, '\x68'); /* push */
1420 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1421 emit_alignment (acfg, kNaClAlignment);
1422 #endif /*__native_client_codegen__*/
1423 #elif defined(TARGET_ARM)
1427 /* This should be exactly 20 bytes long */
1430 ARM_PUSH (code, 0x5fff);
1431 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1432 /* Load the value from the GOT */
1433 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1435 ARM_BLX_REG (code, ARMREG_R1);
1437 g_assert (code - buf == 16);
1440 emit_bytes (acfg, buf, code - buf);
1442 * Only one offset is needed, since the second one would be equal to the
1445 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1446 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1447 #elif defined(TARGET_ARM64)
1448 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1449 #elif defined(TARGET_POWERPC)
1456 g_assert (!acfg->use_bin_writer);
1459 * PPC has no ip relative addressing, so we need to compute the address
1460 * of the mscorlib got. That is slow and complex, so instead, we store it
1461 * in the second got slot of every aot image. The caller already computed
1462 * the address of its got and placed it into r30.
1464 emit_unset_mode (acfg);
1465 /* Load mscorlib got address */
1466 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1467 /* Load generic trampoline address */
1468 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1469 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1470 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1471 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1472 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1474 fprintf (acfg->fp, "mtctr 11\n");
1475 /* Load trampoline argument */
1476 /* On ppc, we pass it normally to the generic trampoline */
1477 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1478 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1479 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1480 /* Branch to generic trampoline */
1481 fprintf (acfg->fp, "bctr\n");
1483 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1484 *tramp_size = 10 * 4;
1486 *tramp_size = 9 * 4;
1488 #elif defined(TARGET_X86)
1492 /* Similar to the PPC code above */
1494 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1496 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1497 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1498 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1499 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1500 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1505 /* Load mscorlib got address */
1506 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1507 /* Push trampoline argument */
1508 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1509 /* Load generic trampoline address */
1510 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1511 /* Branch to generic trampoline */
1512 x86_jump_reg (code, X86_ECX);
1514 #ifdef __native_client_codegen__
1516 /* emit nops to next 32 byte alignment */
1517 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1518 while (code < (buf + a)) x86_nop(code);
1521 emit_bytes (acfg, buf, code - buf);
1523 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1524 g_assert (code - buf == *tramp_size);
1526 g_assert_not_reached ();
1531 * arch_emit_unbox_trampoline:
1533 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1534 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1537 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1539 #if defined(TARGET_AMD64)
1544 this_reg = mono_arch_get_this_arg_reg (NULL);
1546 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1548 emit_bytes (acfg, buf, code - buf);
1550 if (acfg->llvm_separate) {
1551 emit_unset_mode (acfg);
1552 fprintf (acfg->fp, "jmp %s\n", call_target);
1554 emit_byte (acfg, '\xe9');
1555 emit_symbol_diff (acfg, call_target, ".", -4);
1557 #elif defined(TARGET_X86)
1564 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1566 emit_bytes (acfg, buf, code - buf);
1569 emit_byte (acfg, '\xe9');
1570 emit_symbol_diff (acfg, call_target, ".", -4);
1571 #elif defined(TARGET_ARM)
1575 if (acfg->thumb_mixed && cfg->compile_llvm) {
1576 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1577 fprintf (acfg->fp, "b %s\n", call_target);
1578 fprintf (acfg->fp, ".arm\n");
1579 fprintf (acfg->fp, ".align 2\n");
1585 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1587 emit_bytes (acfg, buf, code - buf);
1588 /* jump to method */
1589 if (acfg->use_bin_writer) {
1596 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1597 emit_bytes (acfg, buf, 4);
1599 if (acfg->thumb_mixed && cfg->compile_llvm)
1600 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1602 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1604 #elif defined(TARGET_ARM64)
1605 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1606 #elif defined(TARGET_POWERPC)
1609 g_assert (!acfg->use_bin_writer);
1611 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1612 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1614 g_assert_not_reached ();
1619 * arch_emit_static_rgctx_trampoline:
1621 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1622 * two GOT slots which contain the rgctx argument, and the method to jump to.
1623 * TRAMP_SIZE is set to the size of the emitted trampoline.
1624 * These kinds of trampolines cannot be enumerated statically, since there could
1625 * be one trampoline per method instantiation, so we emit the same code for all
1626 * trampolines, and parameterize them using two GOT slots.
1629 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1631 #if defined(TARGET_AMD64)
1632 #if defined(__default_codegen__)
1633 /* This should be exactly 13 bytes long */
1636 if (acfg->llvm_separate) {
1637 emit_unset_mode (acfg);
1638 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1639 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1641 /* mov <OFFSET>(%rip), %r10 */
1642 emit_byte (acfg, '\x4d');
1643 emit_byte (acfg, '\x8b');
1644 emit_byte (acfg, '\x15');
1645 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1647 /* jmp *<offset>(%rip) */
1648 emit_byte (acfg, '\xff');
1649 emit_byte (acfg, '\x25');
1650 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1652 #elif defined(__native_client_codegen__)
1654 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1655 guint8 *code = buf_aligned;
1657 /* mov <OFFSET>(%rip), %r10d */
1658 emit_byte (acfg, '\x45');
1659 emit_byte (acfg, '\x8b');
1660 emit_byte (acfg, '\x15');
1661 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1663 /* mov <OFFSET>(%rip), %r11d */
1664 emit_byte (acfg, '\x45');
1665 emit_byte (acfg, '\x8b');
1666 emit_byte (acfg, '\x1d');
1667 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1670 amd64_jump_reg (code, AMD64_R11);
1671 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1673 emit_alignment (acfg, kNaClAlignment);
1674 *tramp_size = kNaClAlignment;
1675 #endif /*__native_client_codegen__*/
1677 #elif defined(TARGET_ARM)
1681 /* This should be exactly 24 bytes long */
1684 /* Load rgctx value */
1685 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1686 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1687 /* Load branch addr + branch */
1688 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1689 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1691 g_assert (code - buf == 16);
1694 emit_bytes (acfg, buf, code - buf);
1695 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1696 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1697 #elif defined(TARGET_ARM64)
1698 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1699 #elif defined(TARGET_POWERPC)
1706 g_assert (!acfg->use_bin_writer);
1709 * PPC has no ip relative addressing, so we need to compute the address
1710 * of the mscorlib got. That is slow and complex, so instead, we store it
1711 * in the second got slot of every aot image. The caller already computed
1712 * the address of its got and placed it into r30.
1714 emit_unset_mode (acfg);
1715 /* Load mscorlib got address */
1716 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1718 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1719 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1720 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1721 /* Load target address */
1722 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1723 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1724 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1725 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1726 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1727 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1729 fprintf (acfg->fp, "mtctr 11\n");
1730 /* Branch to the target address */
1731 fprintf (acfg->fp, "bctr\n");
1733 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1734 *tramp_size = 11 * 4;
1736 *tramp_size = 9 * 4;
1739 #elif defined(TARGET_X86)
1743 /* Similar to the PPC code above */
1745 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1748 /* Load mscorlib got address */
1749 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1751 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1752 /* Branch to the target address */
1753 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1755 #ifdef __native_client_codegen__
1757 /* emit nops to next 32 byte alignment */
1758 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1759 while (code < (buf + a)) x86_nop(code);
1763 emit_bytes (acfg, buf, code - buf);
1765 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1766 g_assert (code - buf == *tramp_size);
1768 g_assert_not_reached ();
1773 * arch_emit_imt_thunk:
1775 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1776 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1777 * key is the IMT key, and ptr holds the address of a memory location holding
1778 * the address to branch to if the IMT arg matches the key. The array is
1779 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1781 * TRAMP_SIZE is set to the size of the emitted trampoline.
1784 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1786 #if defined(TARGET_AMD64)
1788 #if defined(__native_client_codegen__)
1791 guint8 *labels [16];
1793 guint8 *mov_buf_ptr = mov_buf;
1795 const int kSizeOfMove = 7;
1796 #if defined(__default_codegen__)
1797 code = buf = g_malloc (256);
1798 #elif defined(__native_client_codegen__)
1799 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1800 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1801 /* The RIP relative move below is emitted first */
1806 /* FIXME: Optimize this, i.e. use binary search etc. */
1807 /* Maybe move the body into a separate function (slower, but much smaller) */
1809 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1811 if (acfg->llvm_separate) {
1812 emit_unset_mode (acfg);
1813 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1817 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1819 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1822 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1824 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1827 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1828 amd64_jump_code (code, labels [0]);
1831 mono_amd64_patch (labels [2], code);
1832 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1833 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1836 mono_amd64_patch (labels [1], code);
1837 /* Load fail tramp */
1838 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1839 /* Check if there is a fail tramp */
1840 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1842 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1843 /* Jump to fail tramp */
1844 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1847 mono_amd64_patch (labels [3], code);
1848 x86_breakpoint (code);
1850 if (!acfg->llvm_separate) {
1851 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1852 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1853 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1854 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1855 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1856 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1858 emit_bytes (acfg, buf, code - buf);
1860 *tramp_size = code - buf + kSizeOfMove;
1861 #if defined(__native_client_codegen__)
1862 /* The tramp will be padded to the next kNaClAlignment bundle. */
1863 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1866 #if defined(__default_codegen__)
1868 #elif defined(__native_client_codegen__)
1872 #elif defined(TARGET_X86)
1874 #ifdef __native_client_codegen__
1877 guint8 *labels [16];
1879 #if defined(__default_codegen__)
1880 code = buf = g_malloc (256);
1881 #elif defined(__native_client_codegen__)
1882 buf_alloc = g_malloc (256 + kNaClAlignment);
1883 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1886 /* Allocate a temporary stack slot */
1887 x86_push_reg (code, X86_EAX);
1889 x86_push_reg (code, X86_EAX);
1891 /* Load mscorlib got address */
1892 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1894 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1897 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1899 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1902 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1904 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1907 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1908 x86_jump_code (code, labels [0]);
1911 mono_x86_patch (labels [2], code);
1912 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1913 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1914 /* Save the target address to the temporary stack location */
1915 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1917 x86_pop_reg (code, X86_EAX);
1918 /* Jump to the target address */
1922 mono_x86_patch (labels [1], code);
1923 /* Load fail tramp */
1924 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1925 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1927 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1928 /* Jump to fail tramp */
1929 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1930 x86_pop_reg (code, X86_EAX);
1934 mono_x86_patch (labels [3], code);
1935 x86_breakpoint (code);
1937 #ifdef __native_client_codegen__
1939 /* emit nops to next 32 byte alignment */
1940 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1941 while (code < (buf + a)) x86_nop(code);
1944 emit_bytes (acfg, buf, code - buf);
1946 *tramp_size = code - buf;
1948 #if defined(__default_codegen__)
1950 #elif defined(__native_client_codegen__)
1954 #elif defined(TARGET_ARM)
1956 guint8 *code, *code2, *labels [16];
1960 /* The IMT method is in v5 */
1962 /* Need at least two free registers, plus a slot for storing the pc */
1963 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1965 /* Load the parameter from the GOT */
1966 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1967 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1970 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1971 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1973 ARM_B_COND (code, ARMCOND_EQ, 0);
1975 /* End-of-loop check */
1976 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1978 ARM_B_COND (code, ARMCOND_EQ, 0);
1981 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1984 arm_patch (labels [4], labels [1]);
1987 arm_patch (labels [2], code);
1988 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1989 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1990 /* Save it to the third stack slot */
1991 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1992 /* Restore the registers and branch */
1993 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1996 arm_patch (labels [3], code);
1997 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1998 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1999 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2003 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2005 emit_bytes (acfg, buf, code - buf);
2006 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2008 *tramp_size = code - buf + 4;
2009 #elif defined(TARGET_ARM64)
2010 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2011 #elif defined(TARGET_POWERPC)
2013 guint8 *code, *labels [16];
2017 /* Load the mscorlib got address */
2018 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2019 /* Load the parameter from the GOT */
2020 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2021 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2023 /* Load and check key */
2025 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2026 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2028 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2030 /* End-of-loop check */
2031 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2033 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2036 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2039 mono_ppc_patch (labels [4], labels [1]);
2042 mono_ppc_patch (labels [2], code);
2043 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2044 /* r12 now contains the value of the vtable slot */
2045 /* this is not a function descriptor on ppc64 */
2046 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2047 ppc_mtctr (code, ppc_r12);
2048 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2051 mono_ppc_patch (labels [3], code);
2055 *tramp_size = code - buf;
2057 emit_bytes (acfg, buf, code - buf);
2059 g_assert_not_reached ();
2064 * arch_emit_gsharedvt_arg_trampoline:
2066 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2067 * two GOT slots which contain the argument, and the code to jump to.
2068 * TRAMP_SIZE is set to the size of the emitted trampoline.
2069 * These kinds of trampolines cannot be enumerated statically, since there could
2070 * be one trampoline per method instantiation, so we emit the same code for all
2071 * trampolines, and parameterize them using two GOT slots.
2074 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2076 #if defined(TARGET_X86)
2080 /* Similar to the PPC code above */
2082 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2085 /* Load mscorlib got address */
2086 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2088 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2089 /* Branch to the target address */
2090 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2092 #ifdef __native_client_codegen__
2094 /* emit nops to next 32 byte alignment */
2095 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2096 while (code < (buf + a)) x86_nop(code);
2100 emit_bytes (acfg, buf, code - buf);
2102 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2103 g_assert (code - buf == *tramp_size);
2104 #elif defined(TARGET_ARM)
2108 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2109 /* Similar to arch_emit_specific_trampoline () */
2112 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2113 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2114 /* Load the arg value from the GOT */
2115 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2116 /* Load the addr from the GOT */
2117 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2119 ARM_BX (code, ARMREG_R1);
2121 g_assert (code - buf == 20);
2124 emit_bytes (acfg, buf, code - buf);
2125 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2126 #elif defined(TARGET_ARM64)
2127 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2129 g_assert_not_reached ();
2134 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2136 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2137 /* Based on code generated by gcc */
2138 emit_unset_mode (acfg);
2141 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2142 ".section .ctors,\"aw\",@progbits\n"
2146 ".section .opd,\"aw\"\n"
2149 ".long .%s,.TOC.@tocbase32\n"
2152 ".type .%s,@function\n"
2154 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2156 ".section .ctors,\"aw\",@progbits\n"
2160 ".section .opd,\"aw\"\n"
2163 ".long .%1$s,.TOC.@tocbase32\n"
2164 ".size %1$s,.-%1$s\n"
2166 ".type .%1$s,@function\n"
2168 ".%1$s:\n", symbol);
2179 "lis 3, .Lglobals@h\n"
2180 "ori 3, 3, .Lglobals@l\n"
2181 "bl .mono_aot_register_module\n"
2189 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2191 ".size .%s,.-.%s\n", symbol, symbol);
2194 ".size .%1$s,.-.%1$s\n", symbol);
2200 /* END OF ARCH SPECIFIC CODE */
2203 mono_get_field_token (MonoClassField *field)
2205 MonoClass *klass = field->parent;
2208 for (i = 0; i < klass->field.count; ++i) {
2209 if (field == &klass->fields [i])
2210 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2213 g_assert_not_reached ();
2218 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2222 //printf ("ENCODE: %d 0x%x.\n", value, value);
2225 * Same encoding as the one used in the metadata, extended to handle values
2226 * greater than 0x1fffffff.
2228 if ((value >= 0) && (value <= 127))
2230 else if ((value >= 0) && (value <= 16383)) {
2231 p [0] = 0x80 | (value >> 8);
2232 p [1] = value & 0xff;
2234 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2235 p [0] = (value >> 24) | 0xc0;
2236 p [1] = (value >> 16) & 0xff;
2237 p [2] = (value >> 8) & 0xff;
2238 p [3] = value & 0xff;
2243 p [1] = (value >> 24) & 0xff;
2244 p [2] = (value >> 16) & 0xff;
2245 p [3] = (value >> 8) & 0xff;
2246 p [4] = value & 0xff;
2254 stream_init (MonoDynamicStream *sh)
2257 sh->alloc_size = 4096;
2258 sh->data = g_malloc (4096);
2260 /* So offsets are > 0 */
2266 make_room_in_stream (MonoDynamicStream *stream, int size)
2268 if (size <= stream->alloc_size)
2271 while (stream->alloc_size <= size) {
2272 if (stream->alloc_size < 4096)
2273 stream->alloc_size = 4096;
2275 stream->alloc_size *= 2;
2278 stream->data = g_realloc (stream->data, stream->alloc_size);
2282 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2286 make_room_in_stream (stream, stream->index + len);
2287 memcpy (stream->data + stream->index, data, len);
2288 idx = stream->index;
2289 stream->index += len;
2296 * Add data to the binary blob inside the aot image. Returns the offset inside the
2297 * blob where the data was stored.
2300 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2302 if (acfg->blob.alloc_size == 0)
2303 stream_init (&acfg->blob);
2305 return add_stream_data (&acfg->blob, (char*)data, data_len);
2309 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2314 if (acfg->blob.alloc_size == 0)
2315 stream_init (&acfg->blob);
2317 count = acfg->blob.index % align;
2319 /* we assume the stream data will be aligned */
2321 add_stream_data (&acfg->blob, buf, 4 - count);
2323 return add_stream_data (&acfg->blob, (char*)data, data_len);
2327 * emit_offset_table:
2329 * Emit a table of increasing offsets in a compact form using differential encoding.
2330 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2331 * group size, the more compact the table becomes, but the slower it becomes to compute
2332 * a given entry. Returns the size of the table.
2335 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2337 gint32 current_offset;
2338 int i, buf_size, ngroups, index_entry_size;
2340 guint32 *index_offsets;
2342 ngroups = (noffsets + (group_size - 1)) / group_size;
2344 index_offsets = g_new0 (guint32, ngroups);
2346 buf_size = noffsets * 4;
2347 p = buf = g_malloc0 (buf_size);
2350 for (i = 0; i < noffsets; ++i) {
2351 //printf ("D: %d -> %d\n", i, offsets [i]);
2352 if ((i % group_size) == 0) {
2353 index_offsets [i / group_size] = p - buf;
2354 /* Emit the full value for these entries */
2355 encode_value (offsets [i], p, &p);
2357 /* The offsets are allowed to be non-increasing */
2358 //g_assert (offsets [i] >= current_offset);
2359 encode_value (offsets [i] - current_offset, p, &p);
2361 current_offset = offsets [i];
2364 if (ngroups && index_offsets [ngroups - 1] < 65000)
2365 index_entry_size = 2;
2367 index_entry_size = 4;
2369 /* Emit the header */
2370 emit_int32 (acfg, noffsets);
2371 emit_int32 (acfg, group_size);
2372 emit_int32 (acfg, ngroups);
2373 emit_int32 (acfg, index_entry_size);
2375 /* Emit the index */
2376 for (i = 0; i < ngroups; ++i) {
2377 if (index_entry_size == 2)
2378 emit_int16 (acfg, index_offsets [i]);
2380 emit_int32 (acfg, index_offsets [i]);
2384 emit_bytes (acfg, buf, p - buf);
2386 return (int)(p - buf) + (ngroups * 4);
2390 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2394 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2398 index = g_hash_table_size (cfg->image_hash);
2399 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2400 g_ptr_array_add (cfg->image_table, image);
2406 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2409 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2411 /* FIXME: Search referenced images as well */
2412 if (!acfg->typespec_classes) {
2413 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2414 for (i = 0; i < len; ++i) {
2416 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2417 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2420 for (i = 0; i < len; ++i) {
2421 if (acfg->typespec_classes [i] == klass)
2426 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2432 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2435 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2438 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2441 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2444 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2449 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2453 if (klass->generic_class) {
2455 g_assert (klass->type_token);
2457 /* Find a typespec for a class if possible */
2458 token = find_typespec_for_class (acfg, klass);
2460 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2461 encode_value (token, p, &p);
2463 MonoClass *gclass = klass->generic_class->container_class;
2464 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2465 static int count = 0;
2468 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2469 encode_klass_ref (acfg, gclass, p, &p);
2470 encode_ginst (acfg, inst, p, &p);
2474 } else if (klass->type_token) {
2475 int iindex = get_image_index (acfg, klass->image);
2477 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2479 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2480 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2482 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2483 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2484 encode_value (get_image_index (acfg, klass->image), p, &p);
2486 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2487 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2488 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2490 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2491 encode_value (klass->byval_arg.type, p, &p);
2492 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2494 encode_value (container ? 1 : 0, p, &p);
2496 encode_value (container->is_method, p, &p);
2497 g_assert (par->serial == 0);
2498 if (container->is_method)
2499 encode_method_ref (acfg, container->owner.method, p, &p);
2501 encode_klass_ref (acfg, container->owner.klass, p, &p);
2503 encode_value (par->serial, p, &p);
2505 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2506 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2507 encode_type (acfg, &klass->byval_arg, p, &p);
2510 g_assert (klass->rank > 0);
2511 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2512 encode_value (klass->rank, p, &p);
2513 encode_klass_ref (acfg, klass->element_class, p, &p);
2521 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2522 * standard metadata encoding.
2525 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2527 gboolean shared = FALSE;
2530 * The encoding of generic instances is large so emit them only once.
2532 if (klass->generic_class) {
2534 g_assert (klass->type_token);
2536 /* Find a typespec for a class if possible */
2537 token = find_typespec_for_class (acfg, klass);
2540 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2545 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2549 buf2 = g_malloc (1024);
2552 encode_klass_ref_inner (acfg, klass, p, &p);
2553 g_assert (p - buf2 < 1024);
2555 offset = add_to_blob (acfg, buf2, p - buf2);
2558 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2564 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2565 encode_value (offset, p, &p);
2570 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2574 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2576 guint32 token = mono_get_field_token (field);
2579 encode_klass_ref (cfg, field->parent, p, &p);
2580 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2581 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2586 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2591 encode_value (inst->type_argc, p, &p);
2592 for (i = 0; i < inst->type_argc; ++i)
2593 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2598 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2601 MonoGenericInst *inst;
2603 inst = context->class_inst;
2605 g_assert (inst->type_argc);
2606 encode_ginst (acfg, inst, p, &p);
2608 encode_value (0, p, &p);
2610 inst = context->method_inst;
2612 g_assert (inst->type_argc);
2613 encode_ginst (acfg, inst, p, &p);
2615 encode_value (0, p, &p);
2621 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2625 g_assert (t->num_mods == 0);
2626 /* t->attrs can be ignored */
2627 //g_assert (t->attrs == 0);
2630 *p = MONO_TYPE_PINNED;
2634 *p = MONO_TYPE_BYREF;
2642 case MONO_TYPE_VOID:
2643 case MONO_TYPE_BOOLEAN:
2644 case MONO_TYPE_CHAR:
2657 case MONO_TYPE_STRING:
2658 case MONO_TYPE_OBJECT:
2659 case MONO_TYPE_TYPEDBYREF:
2661 case MONO_TYPE_VALUETYPE:
2662 case MONO_TYPE_CLASS:
2663 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2665 case MONO_TYPE_SZARRAY:
2666 encode_klass_ref (acfg, t->data.klass, p, &p);
2669 encode_type (acfg, t->data.type, p, &p);
2671 case MONO_TYPE_GENERICINST: {
2672 MonoClass *gclass = t->data.generic_class->container_class;
2673 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2675 encode_klass_ref (acfg, gclass, p, &p);
2676 encode_ginst (acfg, inst, p, &p);
2679 case MONO_TYPE_ARRAY: {
2680 MonoArrayType *array = t->data.array;
2683 encode_klass_ref (acfg, array->eklass, p, &p);
2684 encode_value (array->rank, p, &p);
2685 encode_value (array->numsizes, p, &p);
2686 for (i = 0; i < array->numsizes; ++i)
2687 encode_value (array->sizes [i], p, &p);
2688 encode_value (array->numlobounds, p, &p);
2689 for (i = 0; i < array->numlobounds; ++i)
2690 encode_value (array->lobounds [i], p, &p);
2694 case MONO_TYPE_MVAR:
2695 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2698 g_assert_not_reached ();
2705 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2711 /* Similar to the metadata encoding */
2712 if (sig->generic_param_count)
2716 if (sig->explicit_this)
2718 flags |= (sig->call_convention & 0x0F);
2722 if (sig->generic_param_count)
2723 encode_value (sig->generic_param_count, p, &p);
2724 encode_value (sig->param_count, p, &p);
2726 encode_type (acfg, sig->ret, p, &p);
2727 for (i = 0; i < sig->param_count; ++i) {
2728 if (sig->sentinelpos == i) {
2729 *p = MONO_TYPE_SENTINEL;
2732 encode_type (acfg, sig->params [i], p, &p);
2738 #define MAX_IMAGE_INDEX 250
2741 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2743 guint32 image_index = get_image_index (acfg, method->klass->image);
2744 guint32 token = method->token;
2745 MonoJumpInfoToken *ji;
2749 * The encoding for most methods is as follows:
2750 * - image index encoded as a leb128
2751 * - token index encoded as a leb128
2752 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2753 * types of method encodings.
2756 /* Mark methods which can't use aot trampolines because they need the further
2757 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2759 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2760 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2761 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2763 if (method->wrapper_type) {
2764 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2766 encode_value (method->wrapper_type, p, &p);
2768 switch (method->wrapper_type) {
2769 case MONO_WRAPPER_REMOTING_INVOKE:
2770 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2771 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2774 m = mono_marshal_method_from_wrapper (method);
2776 encode_method_ref (acfg, m, p, &p);
2779 case MONO_WRAPPER_PROXY_ISINST:
2780 case MONO_WRAPPER_LDFLD:
2781 case MONO_WRAPPER_LDFLDA:
2782 case MONO_WRAPPER_STFLD:
2783 case MONO_WRAPPER_ISINST: {
2784 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2787 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2790 case MONO_WRAPPER_LDFLD_REMOTE:
2791 case MONO_WRAPPER_STFLD_REMOTE:
2793 case MONO_WRAPPER_ALLOC: {
2794 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2796 /* The GC name is saved once in MonoAotFileInfo */
2797 g_assert (info->alloc_type != -1);
2798 encode_value (info->alloc_type, p, &p);
2801 case MONO_WRAPPER_WRITE_BARRIER:
2803 case MONO_WRAPPER_STELEMREF: {
2804 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2807 encode_value (info->subtype, p, &p);
2808 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2809 encode_value (info->d.virtual_stelemref.kind, p, &p);
2812 case MONO_WRAPPER_UNKNOWN: {
2813 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2816 encode_value (info->subtype, p, &p);
2817 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2818 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2819 encode_klass_ref (acfg, method->klass, p, &p);
2820 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2821 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2822 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2823 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2826 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2827 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2830 encode_value (info->subtype, p, &p);
2831 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2832 strcpy ((char*)p, method->name);
2833 p += strlen (method->name) + 1;
2834 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2835 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2837 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2838 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2842 case MONO_WRAPPER_SYNCHRONIZED: {
2845 m = mono_marshal_method_from_wrapper (method);
2847 g_assert (m != method);
2848 encode_method_ref (acfg, m, p, &p);
2851 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2852 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2855 encode_value (info->subtype, p, &p);
2857 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2858 encode_value (info->d.element_addr.rank, p, &p);
2859 encode_value (info->d.element_addr.elem_size, p, &p);
2860 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2861 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2863 g_assert_not_reached ();
2867 case MONO_WRAPPER_CASTCLASS: {
2868 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2871 encode_value (info->subtype, p, &p);
2874 case MONO_WRAPPER_RUNTIME_INVOKE: {
2875 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2878 encode_value (info->subtype, p, &p);
2879 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2880 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2881 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2882 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2885 case MONO_WRAPPER_DELEGATE_INVOKE:
2886 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2887 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2888 if (method->is_inflated) {
2889 /* These wrappers are identified by their class */
2890 encode_value (1, p, &p);
2891 encode_klass_ref (acfg, method->klass, p, &p);
2893 MonoMethodSignature *sig = mono_method_signature (method);
2894 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2896 encode_value (0, p, &p);
2897 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2898 encode_value (info ? info->subtype : 0, p, &p);
2899 encode_signature (acfg, sig, p, &p);
2903 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2904 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2907 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2908 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2912 g_assert_not_reached ();
2914 } else if (mono_method_signature (method)->is_inflated) {
2916 * This is a generic method, find the original token which referenced it and
2918 * Obtain the token from information recorded by the JIT.
2920 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2922 image_index = get_image_index (acfg, ji->image);
2923 g_assert (image_index < MAX_IMAGE_INDEX);
2926 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2927 encode_value (image_index, p, &p);
2928 encode_value (token, p, &p);
2930 MonoMethod *declaring;
2931 MonoGenericContext *context = mono_method_get_context (method);
2933 g_assert (method->is_inflated);
2934 declaring = ((MonoMethodInflated*)method)->declaring;
2937 * This might be a non-generic method of a generic instance, which
2938 * doesn't have a token since the reference is generated by the JIT
2939 * like Nullable:Box/Unbox, or by generic sharing.
2941 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2942 /* Encode the klass */
2943 encode_klass_ref (acfg, method->klass, p, &p);
2944 /* Encode the method */
2945 image_index = get_image_index (acfg, method->klass->image);
2946 g_assert (image_index < MAX_IMAGE_INDEX);
2947 g_assert (declaring->token);
2948 token = declaring->token;
2949 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2950 encode_value (image_index, p, &p);
2951 encode_value (token, p, &p);
2952 encode_generic_context (acfg, context, p, &p);
2954 } else if (token == 0) {
2955 /* This might be a method of a constructed type like int[,].Set */
2956 /* Obtain the token from information recorded by the JIT */
2957 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2959 image_index = get_image_index (acfg, ji->image);
2960 g_assert (image_index < MAX_IMAGE_INDEX);
2963 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2964 encode_value (image_index, p, &p);
2965 encode_value (token, p, &p);
2968 g_assert (method->klass->rank);
2970 /* Encode directly */
2971 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2972 encode_klass_ref (acfg, method->klass, p, &p);
2973 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2974 encode_value (0, p, &p);
2975 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2976 encode_value (1, p, &p);
2977 else if (!strcmp (method->name, "Get"))
2978 encode_value (2, p, &p);
2979 else if (!strcmp (method->name, "Address"))
2980 encode_value (3, p, &p);
2981 else if (!strcmp (method->name, "Set"))
2982 encode_value (4, p, &p);
2984 g_assert_not_reached ();
2987 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2989 if (image_index >= MONO_AOT_METHODREF_MIN) {
2990 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2991 encode_value (image_index, p, &p);
2992 encode_value (mono_metadata_token_index (token), p, &p);
2994 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3001 compare_patches (gconstpointer a, gconstpointer b)
3005 i = (*(MonoJumpInfo**)a)->ip.i;
3006 j = (*(MonoJumpInfo**)b)->ip.i;
3017 static G_GNUC_UNUSED char*
3018 patch_to_string (MonoJumpInfo *patch_info)
3022 str = g_string_new ("");
3024 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3026 switch (patch_info->type) {
3027 case MONO_PATCH_INFO_VTABLE:
3028 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3033 g_string_append_printf (str, ")");
3034 return g_string_free (str, FALSE);
3040 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3043 static inline gboolean
3044 is_plt_patch (MonoJumpInfo *patch_info)
3046 switch (patch_info->type) {
3047 case MONO_PATCH_INFO_METHOD:
3048 case MONO_PATCH_INFO_INTERNAL_METHOD:
3049 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3050 case MONO_PATCH_INFO_ICALL_ADDR:
3051 case MONO_PATCH_INFO_CLASS_INIT:
3052 case MONO_PATCH_INFO_RGCTX_FETCH:
3053 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3054 case MONO_PATCH_INFO_MONITOR_ENTER:
3055 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3056 case MONO_PATCH_INFO_MONITOR_EXIT:
3057 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3067 * Return the symbol identifying the plt entry PLT_OFFSET.
3070 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3074 * The Apple linker reorganizes object files, so it doesn't like branches to local
3075 * labels, since those have no relocations.
3077 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3079 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3086 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3088 static MonoPltEntry*
3089 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3093 if (!is_plt_patch (patch_info))
3096 if (!acfg->patch_to_plt_entry [patch_info->type])
3097 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3098 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3100 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3102 * Allocate a separate PLT slot for each such patch, since some plt
3103 * entries will refer to the method itself, and some will refer to the
3110 MonoJumpInfo *new_ji;
3112 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3114 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3115 res->plt_offset = acfg->plt_offset;
3117 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3118 if (acfg->aot_opts.write_symbols)
3119 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3121 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3123 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3125 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3127 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3129 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3130 //mono_print_ji (patch_info); printf ("\n");
3131 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3133 acfg->plt_offset ++;
3142 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3143 * JI could be found if it exists, otherwise allocates a new one.
3146 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3149 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3151 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3153 return got_offset - 1;
3156 got_offset = acfg->llvm_got_offset;
3157 acfg->llvm_got_offset ++;
3159 got_offset = acfg->got_offset;
3160 acfg->got_offset ++;
3163 acfg->stats.got_slots ++;
3164 acfg->stats.got_slot_types [ji->type] ++;
3166 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3167 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3168 g_ptr_array_add (info->got_patches, ji);
3173 /* Add a method to the list of methods which need to be emitted */
3175 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3178 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3179 g_ptr_array_add (acfg->methods, method);
3180 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3181 acfg->nmethods = acfg->methods->len + 1;
3184 if (method->wrapper_type || extra)
3185 g_ptr_array_add (acfg->extra_methods, method);
3189 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3191 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3199 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3203 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3207 index = acfg->method_index;
3208 add_method_with_index (acfg, method, index, extra);
3210 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3212 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3214 acfg->method_index ++;
3220 add_method (MonoAotCompile *acfg, MonoMethod *method)
3222 return add_method_full (acfg, method, FALSE, 0);
3226 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3228 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3229 method = mini_get_shared_method (method);
3231 if (acfg->aot_opts.log_generics)
3232 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3234 add_method_full (acfg, method, TRUE, depth);
3238 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3240 add_extra_method_with_depth (acfg, method, 0);
3244 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3246 MonoAotCompile *acfg = user_data;
3247 MonoJitICallInfo *callinfo = value;
3248 MonoMethod *wrapper;
3254 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3255 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3258 add_method (acfg, wrapper);
3262 get_runtime_invoke_sig (MonoMethodSignature *sig)
3264 MonoMethodBuilder *mb;
3267 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3268 m = mono_mb_create_method (mb, sig, 16);
3269 return mono_marshal_get_runtime_invoke (m, FALSE);
3273 can_marshal_struct (MonoClass *klass)
3275 MonoClassField *field;
3276 gboolean can_marshal = TRUE;
3277 gpointer iter = NULL;
3278 MonoMarshalType *info;
3281 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3284 info = mono_marshal_load_type_info (klass);
3286 /* Only allow a few field types to avoid asserts in the marshalling code */
3287 while ((field = mono_class_get_fields (klass, &iter))) {
3288 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3291 switch (field->type->type) {
3296 case MONO_TYPE_BOOLEAN:
3299 case MONO_TYPE_CHAR:
3307 case MONO_TYPE_STRING:
3309 case MONO_TYPE_VALUETYPE:
3310 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3311 can_marshal = FALSE;
3313 case MONO_TYPE_SZARRAY: {
3314 gboolean has_mspec = FALSE;
3317 for (i = 0; i < info->num_fields; ++i) {
3318 if (info->fields [i].field == field && info->fields [i].mspec)
3323 can_marshal = FALSE;
3327 can_marshal = FALSE;
3333 /* Its hard to compute whenever these can be marshalled or not */
3334 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3341 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3343 /* Create a vtype instantiation */
3344 MonoGenericContext shared_context;
3346 MonoGenericInst *inst;
3347 MonoGenericContainer *container;
3348 MonoClass **constraints;
3351 memset (ctx, 0, sizeof (MonoGenericContext));
3353 if (method->klass->generic_container) {
3354 shared_context = method->klass->generic_container->context;
3355 inst = shared_context.class_inst;
3357 args = g_new0 (MonoType*, inst->type_argc);
3358 for (i = 0; i < inst->type_argc; ++i) {
3359 args [i] = &mono_defaults.int_class->byval_arg;
3361 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3363 if (method->is_generic) {
3364 container = mono_method_get_generic_container (method);
3365 shared_context = container->context;
3366 inst = shared_context.method_inst;
3368 args = g_new0 (MonoType*, inst->type_argc);
3369 for (i = 0; i < container->type_argc; ++i) {
3370 MonoGenericParamInfo *info = &container->type_params [i].info;
3371 gboolean ref_only = FALSE;
3373 if (info && info->constraints) {
3374 constraints = info->constraints;
3376 while (*constraints) {
3377 MonoClass *cklass = *constraints;
3378 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3379 /* Inflaring the method with our vtype would not be valid */
3386 args [i] = &mono_defaults.object_class->byval_arg;
3388 args [i] = &mono_defaults.int_class->byval_arg;
3390 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3395 add_wrappers (MonoAotCompile *acfg)
3397 MonoMethod *method, *m;
3399 MonoMethodSignature *sig, *csig;
3403 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3404 * so there is only one wrapper of a given type, or inlining their contents into their
3407 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3409 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3410 gboolean skip = FALSE;
3412 method = mono_get_method (acfg->image, token, NULL);
3414 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3415 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3416 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3419 /* Skip methods which can not be handled by get_runtime_invoke () */
3420 sig = mono_method_signature (method);
3423 if ((sig->ret->type == MONO_TYPE_PTR) ||
3424 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3426 if (mono_class_is_open_constructed_type (sig->ret))
3429 for (j = 0; j < sig->param_count; j++) {
3430 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3432 if (mono_class_is_open_constructed_type (sig->params [j]))
3436 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3437 if (!mono_class_is_contextbound (method->klass)) {
3438 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3439 gboolean has_nullable = FALSE;
3441 for (j = 0; j < sig->param_count; j++) {
3442 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3443 has_nullable = TRUE;
3446 if (info && !has_nullable) {
3447 /* Supported by the dynamic runtime-invoke wrapper */
3451 mono_arch_dyn_call_free (info);
3456 //printf ("%s\n", mono_method_full_name (method, TRUE));
3457 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3461 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3464 /* Runtime invoke wrappers */
3466 /* void runtime-invoke () [.cctor] */
3467 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3468 csig->ret = &mono_defaults.void_class->byval_arg;
3469 add_method (acfg, get_runtime_invoke_sig (csig));
3471 /* void runtime-invoke () [Finalize] */
3472 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3474 csig->ret = &mono_defaults.void_class->byval_arg;
3475 add_method (acfg, get_runtime_invoke_sig (csig));
3477 /* void runtime-invoke (string) [exception ctor] */
3478 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3480 csig->ret = &mono_defaults.void_class->byval_arg;
3481 csig->params [0] = &mono_defaults.string_class->byval_arg;
3482 add_method (acfg, get_runtime_invoke_sig (csig));
3484 /* void runtime-invoke (string, string) [exception ctor] */
3485 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3487 csig->ret = &mono_defaults.void_class->byval_arg;
3488 csig->params [0] = &mono_defaults.string_class->byval_arg;
3489 csig->params [1] = &mono_defaults.string_class->byval_arg;
3490 add_method (acfg, get_runtime_invoke_sig (csig));
3492 /* string runtime-invoke () [Exception.ToString ()] */
3493 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3495 csig->ret = &mono_defaults.string_class->byval_arg;
3496 add_method (acfg, get_runtime_invoke_sig (csig));
3498 /* void runtime-invoke (string, Exception) [exception ctor] */
3499 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3501 csig->ret = &mono_defaults.void_class->byval_arg;
3502 csig->params [0] = &mono_defaults.string_class->byval_arg;
3503 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3504 add_method (acfg, get_runtime_invoke_sig (csig));
3506 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3507 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3509 csig->ret = &(mono_class_from_name (
3510 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3511 csig->params [0] = &mono_defaults.string_class->byval_arg;
3512 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3513 add_method (acfg, get_runtime_invoke_sig (csig));
3515 /* runtime-invoke used by finalizers */
3516 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3518 /* This is used by mono_runtime_capture_context () */
3519 method = mono_get_context_capture_method ();
3521 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3523 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3524 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3528 add_method (acfg, mono_marshal_get_stelemref ());
3530 if (MONO_ARCH_HAVE_TLS_GET) {
3531 /* Managed Allocators */
3532 nallocators = mono_gc_get_managed_allocator_types ();
3533 for (i = 0; i < nallocators; ++i) {
3534 m = mono_gc_get_managed_allocator_by_type (i);
3536 add_method (acfg, m);
3540 /* Stelemref wrappers */
3542 MonoMethod **wrappers;
3545 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3546 for (i = 0; i < nwrappers; ++i)
3547 add_method (acfg, wrappers [i]);
3551 /* castclass_with_check wrapper */
3552 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3553 /* isinst_with_check wrapper */
3554 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3556 /* JIT icall wrappers */
3557 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3558 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3562 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3563 * we use the original method instead at runtime.
3564 * Since full-aot doesn't support remoting, this is not a problem.
3567 /* remoting-invoke wrappers */
3568 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3569 MonoMethodSignature *sig;
3571 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3572 method = mono_get_method (acfg->image, token, NULL);
3574 sig = mono_method_signature (method);
3576 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3577 m = mono_marshal_get_remoting_invoke_with_check (method);
3579 add_method (acfg, m);
3584 /* delegate-invoke wrappers */
3585 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3588 MonoCustomAttrInfo *cattr;
3590 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3591 klass = mono_class_get_checked (acfg->image, token, &error);
3594 mono_error_cleanup (&error);
3598 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3601 if (!klass->generic_container) {
3602 method = mono_get_delegate_invoke (klass);
3604 m = mono_marshal_get_delegate_invoke (method, NULL);
3606 add_method (acfg, m);
3608 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3610 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3612 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3614 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3616 cattr = mono_custom_attrs_from_class (klass);
3621 for (j = 0; j < cattr->num_attrs; ++j)
3622 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3624 if (j < cattr->num_attrs)
3625 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3627 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3629 MonoGenericContext ctx;
3630 MonoMethod *inst, *gshared;
3633 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3636 method = mono_get_delegate_invoke (klass);
3637 create_gsharedvt_inst (acfg, method, &ctx);
3639 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3640 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3642 m = mono_marshal_get_delegate_invoke (inst, NULL);
3643 g_assert (m->is_inflated);
3645 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3646 add_extra_method (acfg, gshared);
3649 method = mono_get_delegate_begin_invoke (klass);
3650 create_gsharedvt_inst (acfg, method, &ctx);
3652 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3653 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3655 m = mono_marshal_get_delegate_begin_invoke (inst);
3656 g_assert (m->is_inflated);
3658 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3659 add_extra_method (acfg, gshared);
3662 method = mono_get_delegate_end_invoke (klass);
3663 create_gsharedvt_inst (acfg, method, &ctx);
3665 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3666 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3668 m = mono_marshal_get_delegate_end_invoke (inst);
3669 g_assert (m->is_inflated);
3671 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3672 add_extra_method (acfg, gshared);
3677 /* array access wrappers */
3678 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3682 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3683 klass = mono_class_get_checked (acfg->image, token, &error);
3686 mono_error_cleanup (&error);
3690 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3691 MonoMethod *m, *wrapper;
3693 /* Add runtime-invoke wrappers too */
3695 m = mono_class_get_method_from_name (klass, "Get", -1);
3697 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3698 add_extra_method (acfg, wrapper);
3699 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3701 m = mono_class_get_method_from_name (klass, "Set", -1);
3703 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3704 add_extra_method (acfg, wrapper);
3705 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3709 /* Synchronized wrappers */
3710 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3711 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3712 method = mono_get_method (acfg->image, token, NULL);
3714 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3715 if (method->is_generic) {
3717 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3719 MonoGenericContext ctx;
3720 MonoMethod *inst, *gshared, *m;
3723 * Create a generic wrapper for a generic instance, and AOT that.
3725 create_gsharedvt_inst (acfg, method, &ctx);
3726 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3727 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3728 m = mono_marshal_get_synchronized_wrapper (inst);
3729 g_assert (m->is_inflated);
3730 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3731 add_method (acfg, gshared);
3733 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3738 /* pinvoke wrappers */
3739 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3741 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3743 method = mono_get_method (acfg->image, token, NULL);
3745 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3746 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3747 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3751 /* native-to-managed wrappers */
3752 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3754 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3755 MonoCustomAttrInfo *cattr;
3758 method = mono_get_method (acfg->image, token, NULL);
3761 * Only generate native-to-managed wrappers for methods which have an
3762 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3763 * name to avoid defining a new assembly to contain it.
3765 cattr = mono_custom_attrs_from_method (method);
3768 for (j = 0; j < cattr->num_attrs; ++j)
3769 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3771 if (j < cattr->num_attrs) {
3772 MonoCustomAttrEntry *e = &cattr->attrs [j];
3773 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3774 const char *p = (const char*)e->data;
3776 int slen, num_named, named_type, data_type;
3780 char *export_name = NULL;
3781 MonoMethod *wrapper;
3783 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3784 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3785 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3786 mono_method_full_name (method, TRUE));
3790 g_assert (sig->param_count == 1);
3791 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3794 * Decode the cattr manually since we can't create objects
3795 * during aot compilation.
3801 /* From load_cattr_value () in reflection.c */
3802 slen = mono_metadata_decode_value (p, &p);
3803 n = g_memdup (p, slen + 1);
3805 t = mono_reflection_type_from_name (n, acfg->image);
3809 klass = mono_class_from_mono_type (t);
3810 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3814 num_named = read16 (p);
3817 g_assert (num_named < 2);
3818 if (num_named == 1) {
3821 MonoType *prop_type;
3823 /* parse ExportSymbol attribute */
3825 named_type = *named;
3830 name_len = mono_metadata_decode_blob_size (named, &named);
3831 name = g_malloc (name_len + 1);
3832 memcpy (name, named, name_len);
3833 name [name_len] = 0;
3836 g_assert (named_type == 0x54);
3837 g_assert (!strcmp (name, "ExportSymbol"));
3839 prop_type = &mono_defaults.string_class->byval_arg;
3841 /* load_cattr_value (), string case */
3842 g_assert (*named != (char)0xff);
3843 slen = mono_metadata_decode_value (named, &named);
3844 export_name = g_malloc (slen + 1);
3845 memcpy (export_name, named, slen);
3846 export_name [slen] = 0;
3850 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3851 add_method (acfg, wrapper);
3853 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3857 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3858 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3859 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3863 /* StructureToPtr/PtrToStructure wrappers */
3864 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3868 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3869 klass = mono_class_get_checked (acfg->image, token, &error);
3872 mono_error_cleanup (&error);
3876 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3877 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3878 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3879 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3885 has_type_vars (MonoClass *klass)
3887 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3890 return has_type_vars (klass->element_class);
3891 if (klass->generic_class) {
3892 MonoGenericContext *context = &klass->generic_class->context;
3893 if (context->class_inst) {
3896 for (i = 0; i < context->class_inst->type_argc; ++i)
3897 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3901 if (klass->generic_container)
3907 is_vt_inst (MonoGenericInst *inst)
3911 for (i = 0; i < inst->type_argc; ++i) {
3912 MonoType *t = inst->type_argv [i];
3913 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3920 method_has_type_vars (MonoMethod *method)
3922 if (has_type_vars (method->klass))
3925 if (method->is_inflated) {
3926 MonoGenericContext *context = mono_method_get_context (method);
3927 if (context->method_inst) {
3930 for (i = 0; i < context->method_inst->type_argc; ++i)
3931 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3938 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3941 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3943 /* This might lead to a huge code blowup so only do it if neccesary */
3944 if (!acfg->aot_opts.full_aot && !force)
3947 add_generic_class_with_depth (acfg, klass, 0, ref);
3951 check_type_depth (MonoType *t, int depth)
3959 case MONO_TYPE_GENERICINST: {
3960 MonoGenericClass *gklass = t->data.generic_class;
3961 MonoGenericInst *ginst = gklass->context.class_inst;
3964 for (i = 0; i < ginst->type_argc; ++i) {
3965 if (check_type_depth (ginst->type_argv [i], depth + 1))
3979 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3982 * add_generic_class:
3984 * Add all methods of a generic class.
3987 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3990 MonoClassField *field;
3992 gboolean use_gsharedvt = FALSE;
3994 if (!acfg->ginst_hash)
3995 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3997 mono_class_init (klass);
3999 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4002 if (has_type_vars (klass))
4005 if (!klass->generic_class && !klass->rank)
4008 if (klass->exception_type)
4011 if (!acfg->ginst_hash)
4012 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4014 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4017 if (check_type_depth (&klass->byval_arg, 0))
4020 if (acfg->aot_opts.log_generics)
4021 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4023 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4026 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4027 * Enable this only for some classes since gsharedvt might not support all methods.
4029 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) &&
4030 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4031 use_gsharedvt = TRUE;
4034 while ((method = mono_class_get_methods (klass, &iter))) {
4035 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4037 * This is partial sharing, and we can't handle it yet
4042 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4044 add_types_from_method_header (acfg, method);
4048 if (method->is_generic)
4053 * FIXME: Instances which are referenced by these methods are not added,
4054 * for example Array.Resize<int> for List<int>.Add ().
4056 add_extra_method_with_depth (acfg, method, depth + 1);
4060 while ((field = mono_class_get_fields (klass, &iter))) {
4061 if (field->type->type == MONO_TYPE_GENERICINST)
4062 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4065 if (klass->delegate) {
4066 method = mono_get_delegate_invoke (klass);
4068 method = mono_marshal_get_delegate_invoke (method, NULL);
4070 if (acfg->aot_opts.log_generics)
4071 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4073 add_method (acfg, method);
4076 /* Add superclasses */
4078 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4081 * For ICollection<T>, add instances of the helper methods
4082 * in Array, since a T[] could be cast to ICollection<T>.
4084 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4085 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1") || !strcmp (klass->name, "IReadOnlyList`1"))) {
4086 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4087 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4091 if (!strcmp (klass->name, "IEnumerator`1"))
4092 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4094 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4096 /* Add the T[]/InternalEnumerator class */
4097 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4101 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4102 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4106 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4107 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4111 while ((method = mono_class_get_methods (array_class, &iter))) {
4112 if (strstr (method->name, name_prefix)) {
4113 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4115 add_extra_method_with_depth (acfg, m, depth);
4119 g_free (name_prefix);
4122 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4123 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4124 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4125 MonoClass *icomparable, *gcomparer;
4126 MonoGenericContext ctx;
4127 MonoType *args [16];
4129 memset (&ctx, 0, sizeof (ctx));
4131 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4132 g_assert (icomparable);
4133 args [0] = &tclass->byval_arg;
4134 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4136 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4137 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4138 g_assert (gcomparer);
4139 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4143 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4144 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4145 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4146 MonoClass *iface, *gcomparer;
4147 MonoGenericContext ctx;
4148 MonoType *args [16];
4150 memset (&ctx, 0, sizeof (ctx));
4152 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4154 args [0] = &tclass->byval_arg;
4155 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4157 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4158 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4159 g_assert (gcomparer);
4160 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4166 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4169 MonoGenericContext ctx;
4170 MonoType *args [16];
4172 if (acfg->aot_opts.no_instances)
4175 memset (&ctx, 0, sizeof (ctx));
4177 for (i = 0; i < ninsts; ++i) {
4178 args [0] = insts [i];
4179 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4180 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4185 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4187 MonoMethodHeader *header;
4188 MonoMethodSignature *sig;
4191 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4193 sig = mono_method_signature (method);
4196 for (j = 0; j < sig->param_count; ++j)
4197 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4198 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4201 header = mono_method_get_header (method);
4204 for (j = 0; j < header->num_locals; ++j)
4205 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4206 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4208 mono_loader_clear_error ();
4213 * add_generic_instances:
4215 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4218 add_generic_instances (MonoAotCompile *acfg)
4223 MonoGenericContext *context;
4225 if (acfg->aot_opts.no_instances)
4228 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4229 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4230 method = mono_get_method (acfg->image, token, NULL);
4235 if (method->klass->image != acfg->image)
4238 context = mono_method_get_context (method);
4240 if (context && ((context->class_inst && context->class_inst->is_open)))
4244 * For open methods, create an instantiation which can be passed to the JIT.
4245 * FIXME: Handle class_inst as well.
4247 if (context && context->method_inst && context->method_inst->is_open) {
4249 MonoGenericContext shared_context;
4250 MonoGenericInst *inst;
4251 MonoType **type_argv;
4253 MonoMethod *declaring_method;
4254 gboolean supported = TRUE;
4256 /* Check that the context doesn't contain open constructed types */
4257 if (context->class_inst) {
4258 inst = context->class_inst;
4259 for (i = 0; i < inst->type_argc; ++i) {
4260 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)
4262 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4266 if (context->method_inst) {
4267 inst = context->method_inst;
4268 for (i = 0; i < inst->type_argc; ++i) {
4269 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)
4271 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4279 memset (&shared_context, 0, sizeof (MonoGenericContext));
4281 inst = context->class_inst;
4283 type_argv = g_new0 (MonoType*, inst->type_argc);
4284 for (i = 0; i < inst->type_argc; ++i) {
4285 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)
4286 type_argv [i] = &mono_defaults.object_class->byval_arg;
4288 type_argv [i] = inst->type_argv [i];
4291 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4295 inst = context->method_inst;
4297 type_argv = g_new0 (MonoType*, inst->type_argc);
4298 for (i = 0; i < inst->type_argc; ++i) {
4299 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)
4300 type_argv [i] = &mono_defaults.object_class->byval_arg;
4302 type_argv [i] = inst->type_argv [i];
4305 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4309 if (method->is_generic || method->klass->generic_container)
4310 declaring_method = method;
4312 declaring_method = mono_method_get_declaring_generic_method (method);
4314 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4315 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4319 * If the method is fully sharable, it was already added in place of its
4320 * generic definition.
4322 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4326 * FIXME: Partially shared methods are not shared here, so we end up with
4327 * many identical methods.
4329 add_extra_method (acfg, method);
4332 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4336 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4338 klass = mono_class_get_checked (acfg->image, token, &error);
4339 if (!klass || klass->rank) {
4340 mono_error_cleanup (&error);
4344 add_generic_class (acfg, klass, FALSE, "typespec");
4347 /* Add types of args/locals */
4348 for (i = 0; i < acfg->methods->len; ++i) {
4349 method = g_ptr_array_index (acfg->methods, i);
4350 add_types_from_method_header (acfg, method);
4353 if (acfg->image == mono_defaults.corlib) {
4355 MonoType *insts [256];
4358 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4359 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4360 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4361 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4362 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4363 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4364 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4365 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4366 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4367 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4368 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4369 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4371 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4372 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4374 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4375 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4377 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4379 /* Add instances of the array generic interfaces for primitive types */
4380 /* This will add instances of the InternalArray_ helper methods in Array too */
4381 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4383 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4384 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4386 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4387 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4389 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4392 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4393 * used for all instances of GetGenericValueImpl by the AOT runtime.
4396 MonoGenericContext ctx;
4397 MonoType *args [16];
4398 MonoMethod *get_method;
4399 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4401 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4405 memset (&ctx, 0, sizeof (ctx));
4406 args [0] = &mono_defaults.object_class->byval_arg;
4407 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4408 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4409 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4413 /* Same for CompareExchange<T>/Exchange<T> */
4415 MonoGenericContext ctx;
4416 MonoType *args [16];
4418 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4419 gpointer iter = NULL;
4421 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4422 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4424 memset (&ctx, 0, sizeof (ctx));
4425 args [0] = &mono_defaults.object_class->byval_arg;
4426 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4427 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4428 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4433 /* Same for Volatile.Read/Write<T> */
4435 MonoGenericContext ctx;
4436 MonoType *args [16];
4438 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4439 gpointer iter = NULL;
4441 if (volatile_klass) {
4442 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4443 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4445 memset (&ctx, 0, sizeof (ctx));
4446 args [0] = &mono_defaults.object_class->byval_arg;
4447 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4448 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4449 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4458 * is_direct_callable:
4460 * Return whenever the method identified by JI is directly callable without
4461 * going through the PLT.
4464 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4466 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4467 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4469 gboolean direct_callable = TRUE;
4471 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4472 direct_callable = FALSE;
4473 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4474 // FIXME: Maybe call the wrapper directly ?
4475 direct_callable = FALSE;
4477 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4478 /* Disable this so all calls go through load_method (), see the
4479 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4480 * mono_debugger_agent_init ().
4482 direct_callable = FALSE;
4485 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4486 /* sgen does some initialization when the allocator method is created */
4487 direct_callable = FALSE;
4489 if (direct_callable)
4492 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4493 if (acfg->aot_opts.direct_pinvoke)
4495 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4496 if (acfg->aot_opts.direct_icalls)
4504 #ifdef MONO_ARCH_AOT_SUPPORTED
4506 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4508 MonoImage *image = method->klass->image;
4509 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4510 MonoTableInfo *tables = image->tables;
4511 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4512 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4513 guint32 im_cols [MONO_IMPLMAP_SIZE];
4516 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4520 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4523 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4525 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4528 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4530 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4537 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4539 if (a->native_offset == b->native_offset)
4540 return a->il_offset - b->il_offset;
4542 return a->native_offset - b->native_offset;
4546 * compute_line_numbers:
4548 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4551 static MonoDebugSourceLocation**
4552 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4554 MonoDebugMethodInfo *minfo;
4555 MonoDebugLineNumberEntry *ln_array;
4556 MonoDebugSourceLocation *loc;
4557 int i, prev_line, prev_il_offset;
4558 int *native_to_il_offset = NULL;
4559 MonoDebugSourceLocation **res;
4562 minfo = mono_debug_lookup_method (method);
4565 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4566 if (debug_info->code_size != code_size)
4569 g_assert (code_size);
4571 /* Compute the native->IL offset mapping */
4573 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4574 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4576 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4578 native_to_il_offset = g_new0 (int, code_size + 1);
4580 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4582 MonoDebugLineNumberEntry *lne = &ln_array [i];
4585 for (j = 0; j < lne->native_offset; ++j)
4586 native_to_il_offset [j] = -1;
4589 if (i < debug_info->num_line_numbers - 1) {
4590 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4592 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4593 native_to_il_offset [j] = lne->il_offset;
4595 for (j = lne->native_offset; j < code_size; ++j)
4596 native_to_il_offset [j] = lne->il_offset;
4601 /* Compute the native->line number mapping */
4602 res = g_new0 (MonoDebugSourceLocation*, code_size);
4603 prev_il_offset = -1;
4606 for (i = 0; i < code_size; ++i) {
4607 int il_offset = native_to_il_offset [i];
4609 if (il_offset == -1 || il_offset == prev_il_offset)
4611 prev_il_offset = il_offset;
4612 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4613 if (!(loc && loc->source_file))
4615 if (loc->row == prev_line) {
4616 mono_debug_symfile_free_location (loc);
4619 prev_line = loc->row;
4620 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4622 /* This will cover the prolog too */
4632 get_file_index (MonoAotCompile *acfg, const char *source_file)
4636 // FIXME: Free these
4637 if (!acfg->dwarf_ln_filenames)
4638 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4639 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4641 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4642 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4643 emit_unset_mode (acfg);
4644 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4656 * emit_and_reloc_code:
4658 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4659 * is true, calls are made through the GOT too. This is used for emitting trampolines
4660 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4661 * since trampolines are needed to make PTL work.
4664 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4666 int i, pindex, start_index, method_index;
4668 MonoJumpInfo *patch_info;
4669 MonoMethodHeader *header;
4670 MonoDebugSourceLocation **locs = NULL;
4672 #ifdef MONO_ARCH_AOT_SUPPORTED
4673 gboolean direct_call, external_call;
4675 const char *direct_call_target = 0;
4676 const char *direct_pinvoke;
4680 header = mono_method_get_header (method);
4682 method_index = get_method_index (acfg, method);
4685 if (acfg->gas_line_numbers && method && debug_info) {
4686 locs = compute_line_numbers (method, code_len, debug_info);
4688 int findex = get_file_index (acfg, "<unknown>");
4689 emit_unset_mode (acfg);
4690 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4694 /* Collect and sort relocations */
4695 patches = g_ptr_array_new ();
4696 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4697 g_ptr_array_add (patches, patch_info);
4698 g_ptr_array_sort (patches, compare_patches);
4701 for (i = 0; i < code_len; i += INST_LEN) {
4703 for (pindex = start_index; pindex < patches->len; ++pindex) {
4704 patch_info = g_ptr_array_index (patches, pindex);
4705 if (patch_info->ip.i >= i)
4709 if (locs && locs [i]) {
4710 MonoDebugSourceLocation *loc = locs [i];
4713 findex = get_file_index (acfg, loc->source_file);
4714 emit_unset_mode (acfg);
4715 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4716 mono_debug_symfile_free_location (loc);
4720 #ifdef MONO_ARCH_AOT_SUPPORTED
4721 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4722 start_index = pindex;
4724 switch (patch_info->type) {
4725 case MONO_PATCH_INFO_NONE:
4727 case MONO_PATCH_INFO_GOT_OFFSET: {
4730 arch_emit_got_offset (acfg, code + i, &code_size);
4731 i += code_size - INST_LEN;
4733 patch_info->type = MONO_PATCH_INFO_NONE;
4736 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4737 int code_size, index;
4738 char *selector = (void*)patch_info->data.target;
4740 if (!acfg->objc_selector_to_index)
4741 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4742 if (!acfg->objc_selectors)
4743 acfg->objc_selectors = g_ptr_array_new ();
4744 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4748 index = acfg->objc_selector_index;
4749 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4750 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4751 acfg->objc_selector_index ++;
4754 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4755 i += code_size - INST_LEN;
4757 patch_info->type = MONO_PATCH_INFO_NONE;
4762 * If this patch is a call, try emitting a direct call instead of
4763 * through a PLT entry. This is possible if the called method is in
4764 * the same assembly and requires no initialization.
4766 direct_call = FALSE;
4767 external_call = FALSE;
4768 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4769 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4770 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4771 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4773 direct_call_target = callee_cfg->asm_symbol;
4774 patch_info->type = MONO_PATCH_INFO_NONE;
4775 acfg->stats.direct_calls ++;
4778 acfg->stats.all_calls ++;
4779 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4780 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4781 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4782 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4784 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4785 if (direct_pinvoke) {
4787 g_assert (strlen (direct_pinvoke) < 1000);
4788 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4791 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4792 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4793 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4794 /* Call to a C function implementing a jit icall */
4796 external_call = TRUE;
4797 g_assert (strlen (sym) < 1000);
4798 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4800 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4801 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4802 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4803 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4804 /* Call to a jit icall without a wrapper */
4806 external_call = TRUE;
4807 g_assert (strlen (sym) < 1000);
4808 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4813 patch_info->type = MONO_PATCH_INFO_NONE;
4814 acfg->stats.direct_calls ++;
4817 if (!got_only && !direct_call) {
4818 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4820 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4822 direct_call_target = plt_entry->symbol;
4824 /* Nullify the patch */
4825 patch_info->type = MONO_PATCH_INFO_NONE;
4826 plt_entry->jit_used = TRUE;
4833 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4834 i += call_size - INST_LEN;
4838 got_slot = get_got_offset (acfg, FALSE, patch_info);
4840 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4841 i += code_size - INST_LEN;
4847 #endif /* MONO_ARCH_AOT_SUPPORTED */
4850 /* Find next patch */
4852 for (pindex = start_index; pindex < patches->len; ++pindex) {
4853 patch_info = g_ptr_array_index (patches, pindex);
4854 if (patch_info->ip.i >= i)
4858 /* Try to emit multiple bytes at once */
4859 if (pindex < patches->len && patch_info->ip.i > i) {
4862 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4863 if (locs && locs [limit])
4867 emit_code_bytes (acfg, code + i, limit - i);
4868 i = limit - INST_LEN;
4870 emit_code_bytes (acfg, code + i, INST_LEN);
4881 * Return a modified version of S which only includes characters permissible in symbols.
4884 sanitize_symbol (MonoAotCompile *acfg, char *s)
4886 gboolean process = FALSE;
4895 for (i = 0; i < len; ++i)
4896 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4901 gs = g_string_sized_new (len);
4902 for (i = 0; i < len; ++i) {
4904 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4905 g_string_append_c (gs, c);
4906 } else if (c > 0x7f) {
4907 /* multi-byte utf8 */
4908 g_string_append_printf (gs, "_0x%x", c);
4911 while (c >> 6 == 0x2) {
4912 g_string_append_printf (gs, "%x", c);
4916 g_string_append_printf (gs, "_");
4919 g_string_append_c (gs, '_');
4923 res = mono_mempool_strdup (acfg->mempool, gs->str);
4924 g_string_free (gs, TRUE);
4929 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4931 char *name1, *name2, *cached;
4932 int i, j, len, count;
4933 MonoMethod *cached_method;
4935 name1 = mono_method_full_name (method, TRUE);
4938 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4939 if ((!prefix || !*prefix) && name1 [0] == 'L')
4943 len = strlen (name1);
4944 name2 = malloc (strlen (prefix) + len + 16);
4945 memcpy (name2, prefix, strlen (prefix));
4946 j = strlen (prefix);
4947 for (i = 0; i < len; ++i) {
4948 if (isalnum (name1 [i])) {
4949 name2 [j ++] = name1 [i];
4950 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4952 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4955 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4965 cached_method = g_hash_table_lookup (cache, name2);
4966 if (!(cached_method && cached_method != method))
4968 sprintf (name2 + j, "_%d", count);
4972 cached = g_strdup (name2);
4973 g_hash_table_insert (cache, cached, method);
4979 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4984 char *debug_sym = NULL;
4985 char *symbol = NULL;
4986 int func_alignment = AOT_FUNC_ALIGNMENT;
4987 MonoMethodHeader *header;
4990 method = cfg->orig_method;
4991 code = cfg->native_code;
4992 header = cfg->header;
4994 method_index = get_method_index (acfg, method);
4995 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4997 /* Make the labels local */
4998 emit_section_change (acfg, ".text", 0);
4999 emit_alignment_code (acfg, func_alignment);
5001 if (acfg->global_symbols && acfg->need_no_dead_strip)
5002 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5004 emit_label (acfg, cfg->asm_symbol);
5006 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm_separate) {
5008 * Write a C style symbol for every method, this has two uses:
5009 * - it works on platforms where the dwarf debugging info is not
5011 * - it allows the setting of breakpoints of aot-ed methods.
5013 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5015 if (acfg->need_no_dead_strip)
5016 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5017 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5018 emit_label (acfg, debug_sym);
5021 export_name = g_hash_table_lookup (acfg->export_names, method);
5023 /* Emit a global symbol for the method */
5024 emit_global_inner (acfg, export_name, TRUE);
5025 emit_label (acfg, export_name);
5028 if (cfg->verbose_level > 0)
5029 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5031 acfg->stats.code_size += cfg->code_len;
5033 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5035 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
5039 if (acfg->aot_opts.write_symbols) {
5041 emit_symbol_size (acfg, debug_sym, ".");
5043 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5047 emit_label (acfg, symbol);
5054 * Encode PATCH_INFO into its disk representation.
5057 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5061 switch (patch_info->type) {
5062 case MONO_PATCH_INFO_NONE:
5064 case MONO_PATCH_INFO_IMAGE:
5065 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5067 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5068 case MONO_PATCH_INFO_JIT_TLS_ID:
5069 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5071 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5072 encode_value (patch_info->data.index, p, &p);
5074 case MONO_PATCH_INFO_METHOD_REL:
5075 encode_value ((gint)patch_info->data.offset, p, &p);
5077 case MONO_PATCH_INFO_SWITCH: {
5078 gpointer *table = (gpointer *)patch_info->data.table->table;
5081 encode_value (patch_info->data.table->table_size, p, &p);
5082 for (k = 0; k < patch_info->data.table->table_size; k++)
5083 encode_value ((int)(gssize)table [k], p, &p);
5086 case MONO_PATCH_INFO_METHODCONST:
5087 case MONO_PATCH_INFO_METHOD:
5088 case MONO_PATCH_INFO_METHOD_JUMP:
5089 case MONO_PATCH_INFO_ICALL_ADDR:
5090 case MONO_PATCH_INFO_METHOD_RGCTX:
5091 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5092 encode_method_ref (acfg, patch_info->data.method, p, &p);
5094 case MONO_PATCH_INFO_INTERNAL_METHOD:
5095 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5096 guint32 len = strlen (patch_info->data.name);
5098 encode_value (len, p, &p);
5100 memcpy (p, patch_info->data.name, len);
5105 case MONO_PATCH_INFO_LDSTR: {
5106 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5107 guint32 token = patch_info->data.token->token;
5108 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5109 encode_value (image_index, p, &p);
5110 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5113 case MONO_PATCH_INFO_RVA:
5114 case MONO_PATCH_INFO_DECLSEC:
5115 case MONO_PATCH_INFO_LDTOKEN:
5116 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5117 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5118 encode_value (patch_info->data.token->token, p, &p);
5119 encode_value (patch_info->data.token->has_context, p, &p);
5120 if (patch_info->data.token->has_context)
5121 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5123 case MONO_PATCH_INFO_EXC_NAME: {
5124 MonoClass *ex_class;
5127 mono_class_from_name (mono_defaults.exception_class->image,
5128 "System", patch_info->data.target);
5129 g_assert (ex_class);
5130 encode_klass_ref (acfg, ex_class, p, &p);
5133 case MONO_PATCH_INFO_R4:
5134 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5136 case MONO_PATCH_INFO_R8:
5137 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5138 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5140 case MONO_PATCH_INFO_VTABLE:
5141 case MONO_PATCH_INFO_CLASS:
5142 case MONO_PATCH_INFO_IID:
5143 case MONO_PATCH_INFO_ADJUSTED_IID:
5144 case MONO_PATCH_INFO_CLASS_INIT:
5145 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5147 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5148 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5149 if (patch_info->data.del_tramp->method) {
5150 encode_value (1, p, &p);
5151 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5153 encode_value (0, p, &p);
5155 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5157 case MONO_PATCH_INFO_FIELD:
5158 case MONO_PATCH_INFO_SFLDA:
5159 encode_field_info (acfg, patch_info->data.field, p, &p);
5161 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5163 case MONO_PATCH_INFO_RGCTX_FETCH: {
5164 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5169 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5170 * reference the same method, so encode the method only once.
5172 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5174 buf2 = g_malloc (1024);
5177 encode_method_ref (acfg, entry->method, p2, &p2);
5178 g_assert (p2 - buf2 < 1024);
5180 offset = add_to_blob (acfg, buf2, p2 - buf2);
5183 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5188 encode_value (offset, p, &p);
5189 g_assert ((int)entry->info_type < 256);
5190 g_assert (entry->data->type < 256);
5191 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5192 encode_patch (acfg, entry->data, p, &p);
5195 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5196 case MONO_PATCH_INFO_MONITOR_ENTER:
5197 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5198 case MONO_PATCH_INFO_MONITOR_EXIT:
5199 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5201 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5202 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5203 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5205 case MONO_PATCH_INFO_SIGNATURE:
5206 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5208 case MONO_PATCH_INFO_TLS_OFFSET:
5209 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5211 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5212 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5213 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5215 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5216 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5219 encode_method_ref (acfg, info->method, p, &p);
5220 encode_value (info->num_entries, p, &p);
5221 for (i = 0; i < info->num_entries; ++i) {
5222 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5224 encode_value (template->info_type, p, &p);
5225 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5226 case MONO_PATCH_INFO_CLASS:
5227 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5229 case MONO_PATCH_INFO_FIELD:
5230 encode_field_info (acfg, template->data, p, &p);
5233 g_assert_not_reached ();
5239 case MONO_PATCH_INFO_LDSTR_LIT: {
5240 const char *s = patch_info->data.target;
5242 encode_value (strlen (s), p, &p);
5243 memcpy (p, s, strlen (s) + 1);
5247 g_warning ("unable to handle jump info %d", patch_info->type);
5248 g_assert_not_reached ();
5255 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5258 guint32 pindex, offset;
5259 MonoJumpInfo *patch_info;
5261 encode_value (n_patches, p, &p);
5263 for (pindex = 0; pindex < patches->len; ++pindex) {
5264 patch_info = g_ptr_array_index (patches, pindex);
5266 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5270 offset = get_got_offset (acfg, llvm, patch_info);
5271 encode_value (offset, p, &p);
5278 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5282 int pindex, buf_size, n_patches;
5284 MonoJumpInfo *patch_info;
5285 MonoMethodHeader *header;
5286 guint32 method_index;
5288 guint32 first_got_offset;
5290 method = cfg->orig_method;
5291 header = mono_method_get_header (method);
5293 method_index = get_method_index (acfg, method);
5295 /* Sort relocations */
5296 patches = g_ptr_array_new ();
5297 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5298 g_ptr_array_add (patches, patch_info);
5299 g_ptr_array_sort (patches, compare_patches);
5301 first_got_offset = acfg->cfgs [method_index]->got_offset;
5303 /**********************/
5304 /* Encode method info */
5305 /**********************/
5307 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5308 p = buf = g_malloc (buf_size);
5310 if (mono_class_get_cctor (method->klass))
5311 encode_klass_ref (acfg, method->klass, p, &p);
5313 /* Not needed when loading the method */
5314 encode_value (0, p, &p);
5317 if (cfg->opt & MONO_OPT_SHARED) {
5318 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5319 for (l = cfg->ldstr_list; l; l = l->next) {
5320 encode_value ((long)l->data, p, &p);
5324 /* Used only in shared mode */
5325 g_assert (!cfg->ldstr_list);
5328 for (pindex = 0; pindex < patches->len; ++pindex) {
5329 patch_info = g_ptr_array_index (patches, pindex);
5331 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5332 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5333 patch_info->type = MONO_PATCH_INFO_NONE;
5338 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5339 /* Stored in a GOT slot initialized at module load time */
5340 patch_info->type = MONO_PATCH_INFO_NONE;
5344 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5345 /* Stored in a GOT slot initialized at module load time */
5346 patch_info->type = MONO_PATCH_INFO_NONE;
5350 if (is_plt_patch (patch_info)) {
5351 /* Calls are made through the PLT */
5352 patch_info->type = MONO_PATCH_INFO_NONE;
5360 g_assert (cfg->has_got_slots);
5362 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5364 acfg->stats.info_size += p - buf;
5366 g_assert (p - buf < buf_size);
5368 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5373 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5375 guint32 cache_index;
5378 /* Reuse the unwind module to canonize and store unwind info entries */
5379 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5381 /* Use +/- 1 to distinguish 0s from missing entries */
5382 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5390 * It would be easier to use assembler symbols, but the caller needs an
5393 offset = acfg->unwind_info_offset;
5394 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5395 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5398 encode_value (encoded_len, p, &p);
5400 acfg->unwind_info_offset += encoded_len + (p - buf);
5406 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5409 int i, k, buf_size, method_index;
5410 guint32 debug_info_size, seq_points_size;
5412 MonoMethodHeader *header;
5413 guint8 *p, *buf, *debug_info;
5414 MonoJitInfo *jinfo = cfg->jit_info;
5416 gboolean use_unwind_ops = FALSE;
5417 MonoSeqPointInfo *seq_points;
5419 method = cfg->orig_method;
5420 code = cfg->native_code;
5421 header = cfg->header;
5423 method_index = get_method_index (acfg, method);
5425 if (!acfg->aot_opts.nodebug) {
5426 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5429 debug_info_size = 0;
5432 seq_points = cfg->seq_point_info;
5434 seq_points_size = (cfg->gen_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5436 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5437 p = buf = g_malloc (buf_size);
5439 use_unwind_ops = cfg->unwind_ops != NULL;
5441 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);
5443 encode_value (flags, p, &p);
5445 if (use_unwind_ops) {
5446 guint32 encoded_len;
5448 guint32 unwind_desc;
5450 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5452 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5453 encode_value (unwind_desc, p, &p);
5455 encode_value (jinfo->unwind_info, p, &p);
5458 /*Encode the number of holes before the number of clauses to make decoding easier*/
5459 if (jinfo->has_try_block_holes) {
5460 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5461 encode_value (table->num_holes, p, &p);
5464 if (jinfo->has_arch_eh_info) {
5466 * In AOT mode, the code length is calculated from the address of the previous method,
5467 * which could include alignment padding, so calculating the start of the epilog as
5468 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5470 encode_value (jinfo->code_size, p, &p);
5473 /* Exception table */
5474 if (cfg->compile_llvm) {
5476 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5477 * since the information is only available to llc. Instead, we let llc save the data
5478 * into the LSDA, and read it from there at runtime.
5480 /* The assembly might be CIL stripped so emit the data ourselves */
5481 if (header->num_clauses)
5482 encode_value (header->num_clauses, p, &p);
5484 for (k = 0; k < header->num_clauses; ++k) {
5485 MonoExceptionClause *clause;
5487 clause = &header->clauses [k];
5489 encode_value (clause->flags, p, &p);
5490 if (clause->data.catch_class) {
5491 encode_value (1, p, &p);
5492 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5494 encode_value (0, p, &p);
5497 /* Emit a list of nesting clauses */
5498 for (i = 0; i < header->num_clauses; ++i) {
5500 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5502 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5504 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5505 encode_value (i, p, &p);
5507 encode_value (-1, p, &p);
5510 if (jinfo->num_clauses)
5511 encode_value (jinfo->num_clauses, p, &p);
5513 for (k = 0; k < jinfo->num_clauses; ++k) {
5514 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5516 encode_value (ei->flags, p, &p);
5517 encode_value (ei->exvar_offset, p, &p);
5519 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5520 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5522 if (ei->data.catch_class) {
5526 buf2 = g_malloc (4096);
5528 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5530 g_assert (len < 4096);
5531 encode_value (len, p, &p);
5532 memcpy (p, buf2, len);
5536 encode_value (0, p, &p);
5540 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5541 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5542 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5546 if (jinfo->has_try_block_holes) {
5547 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5548 for (i = 0; i < table->num_holes; ++i) {
5549 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5550 encode_value (hole->clause, p, &p);
5551 encode_value (hole->length, p, &p);
5552 encode_value (hole->offset, p, &p);
5556 if (jinfo->has_arch_eh_info) {
5557 MonoArchEHJitInfo *eh_info;
5559 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5560 encode_value (eh_info->stack_size, p, &p);
5561 encode_value (eh_info->epilog_size, p, &p);
5564 if (jinfo->has_generic_jit_info) {
5565 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5566 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5572 encode_value (gi->nlocs, p, &p);
5574 for (i = 0; i < gi->nlocs; ++i) {
5575 MonoDwarfLocListEntry *entry = &gi->locations [i];
5577 encode_value (entry->is_reg ? 1 : 0, p, &p);
5578 encode_value (entry->reg, p, &p);
5580 encode_value (entry->offset, p, &p);
5582 g_assert (entry->from == 0);
5584 encode_value (entry->from, p, &p);
5585 encode_value (entry->to, p, &p);
5588 if (!cfg->compile_llvm) {
5589 encode_value (gi->has_this ? 1 : 0, p, &p);
5590 encode_value (gi->this_reg, p, &p);
5591 encode_value (gi->this_offset, p, &p);
5596 * Need to encode jinfo->method too, since it is not equal to 'method'
5597 * when using generic sharing.
5599 buf2 = g_malloc (4096);
5601 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5603 g_assert (len < 4096);
5604 encode_value (len, p, &p);
5605 memcpy (p, buf2, len);
5609 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5610 MonoMethodInflated *inflated;
5611 MonoGenericContext *context;
5612 MonoGenericInst *inst;
5614 g_assert (jinfo->d.method->is_inflated);
5615 inflated = (MonoMethodInflated*)jinfo->d.method;
5616 context = &inflated->context;
5618 encode_value (1, p, &p);
5619 if (context->class_inst) {
5620 inst = context->class_inst;
5622 encode_value (inst->type_argc, p, &p);
5623 for (i = 0; i < inst->type_argc; ++i)
5624 encode_value (gsctx->var_is_vt [i], p, &p);
5626 encode_value (0, p, &p);
5628 if (context->method_inst) {
5629 inst = context->method_inst;
5631 encode_value (inst->type_argc, p, &p);
5632 for (i = 0; i < inst->type_argc; ++i)
5633 encode_value (gsctx->mvar_is_vt [i], p, &p);
5635 encode_value (0, p, &p);
5638 encode_value (0, p, &p);
5643 p += seq_point_info_write (seq_points, p);
5645 g_assert (debug_info_size < buf_size);
5647 encode_value (debug_info_size, p, &p);
5648 if (debug_info_size) {
5649 memcpy (p, debug_info, debug_info_size);
5650 p += debug_info_size;
5651 g_free (debug_info);
5656 encode_value (cfg->gc_map_size, p, &p);
5657 /* The GC map requires 4 bytes of alignment */
5658 while ((gsize)p % 4)
5660 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5661 p += cfg->gc_map_size;
5664 acfg->stats.ex_info_size += p - buf;
5666 g_assert (p - buf < buf_size);
5669 /* The GC Map requires 4 byte alignment */
5670 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5675 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5678 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5680 int i, buf_size, res;
5681 gboolean no_special_static, cant_encode;
5682 gpointer iter = NULL;
5685 mono_error_cleanup (&error);
5689 p = buf = g_malloc (buf_size);
5691 /* Mark as unusable */
5692 encode_value (-1, p, &p);
5694 res = add_to_blob (acfg, buf, p - buf);
5700 buf_size = 10240 + (klass->vtable_size * 16);
5701 p = buf = g_malloc (buf_size);
5705 mono_class_init (klass);
5707 mono_class_get_nested_types (klass, &iter);
5708 g_assert (klass->nested_classes_inited);
5710 mono_class_setup_vtable (klass);
5713 * Emit all the information which is required for creating vtables so
5714 * the runtime does not need to create the MonoMethod structures which
5715 * take up a lot of space.
5718 no_special_static = !mono_class_has_special_static_fields (klass);
5720 /* Check whenever we have enough info to encode the vtable */
5721 cant_encode = FALSE;
5722 for (i = 0; i < klass->vtable_size; ++i) {
5723 MonoMethod *cm = klass->vtable [i];
5725 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5729 mono_class_has_finalizer (klass);
5731 if (klass->generic_container || cant_encode) {
5732 encode_value (-1, p, &p);
5734 encode_value (klass->vtable_size, p, &p);
5735 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);
5736 if (klass->has_cctor)
5737 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5738 if (klass->has_finalize)
5739 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5741 encode_value (klass->instance_size, p, &p);
5742 encode_value (mono_class_data_size (klass), p, &p);
5743 encode_value (klass->packing_size, p, &p);
5744 encode_value (klass->min_align, p, &p);
5746 for (i = 0; i < klass->vtable_size; ++i) {
5747 MonoMethod *cm = klass->vtable [i];
5750 encode_method_ref (acfg, cm, p, &p);
5752 encode_value (0, p, &p);
5756 acfg->stats.class_info_size += p - buf;
5758 g_assert (p - buf < buf_size);
5759 res = add_to_blob (acfg, buf, p - buf);
5766 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5768 char *debug_sym = NULL;
5772 if (acfg->llvm_separate && llvm_acfg->aot_opts.static_link) {
5773 /* Need to add a prefix to create unique symbols */
5774 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5776 prefix = g_strdup ("plt_");
5780 case MONO_PATCH_INFO_METHOD:
5781 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5783 case MONO_PATCH_INFO_INTERNAL_METHOD:
5784 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5786 case MONO_PATCH_INFO_CLASS_INIT:
5787 s = mono_type_get_name (&ji->data.klass->byval_arg);
5788 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5791 case MONO_PATCH_INFO_RGCTX_FETCH:
5792 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5794 case MONO_PATCH_INFO_ICALL_ADDR: {
5795 char *s = get_debug_sym (ji->data.method, "", cache);
5797 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5801 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5802 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5804 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5805 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5813 return sanitize_symbol (acfg, debug_sym);
5817 * Calls made from AOTed code are routed through a table of jumps similar to the
5818 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5819 * control to the AOT runtime through a trampoline.
5822 emit_plt (MonoAotCompile *acfg)
5828 sprintf (symbol, "plt");
5830 emit_section_change (acfg, ".text", 0);
5831 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5832 emit_label (acfg, symbol);
5833 emit_label (acfg, acfg->plt_symbol);
5835 for (i = 0; i < acfg->plt_offset; ++i) {
5836 char *debug_sym = NULL;
5837 MonoPltEntry *plt_entry = NULL;
5842 * The first plt entry is unused.
5846 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5849 debug_sym = plt_entry->debug_sym;
5851 if (acfg->thumb_mixed && !plt_entry->jit_used)
5852 /* Emit only a thumb version */
5855 /* Skip plt entries not actually called */
5856 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5859 if (acfg->llvm && !acfg->thumb_mixed) {
5860 emit_label (acfg, plt_entry->llvm_symbol);
5861 if (acfg->llvm_separate) {
5862 emit_global (acfg, plt_entry->llvm_symbol, TRUE);
5863 #if defined(TARGET_MACH)
5864 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5870 if (acfg->need_no_dead_strip) {
5871 emit_unset_mode (acfg);
5872 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5874 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5875 emit_label (acfg, debug_sym);
5878 emit_label (acfg, plt_entry->symbol);
5880 arch_emit_plt_entry (acfg, i);
5883 emit_symbol_size (acfg, debug_sym, ".");
5886 if (acfg->thumb_mixed) {
5887 /* Make sure the ARM symbols don't alias the thumb ones */
5888 emit_zero_bytes (acfg, 16);
5891 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5894 for (i = 0; i < acfg->plt_offset; ++i) {
5895 char *debug_sym = NULL;
5896 MonoPltEntry *plt_entry = NULL;
5902 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5905 /* Skip plt entries not actually called by LLVM code */
5906 if (!plt_entry->llvm_used)
5909 if (acfg->aot_opts.write_symbols) {
5910 if (plt_entry->debug_sym)
5911 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5915 #if defined(TARGET_MACH)
5916 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5917 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5919 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5920 emit_label (acfg, debug_sym);
5922 fprintf (acfg->fp, "\n.thumb_func\n");
5924 emit_label (acfg, plt_entry->llvm_symbol);
5926 arch_emit_llvm_plt_entry (acfg, i);
5929 emit_symbol_size (acfg, debug_sym, ".");
5935 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5937 sprintf (symbol, "plt_end");
5938 emit_label (acfg, symbol);
5942 * emit_trampoline_full:
5944 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5945 * create_jit_info_for_trampoline ().
5947 static G_GNUC_UNUSED void
5948 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5950 char start_symbol [256];
5951 char end_symbol [256];
5953 guint32 buf_size, info_offset;
5954 MonoJumpInfo *patch_info;
5967 code_size = info->code_size;
5969 unwind_ops = info->unwind_ops;
5971 #ifdef __native_client_codegen__
5972 mono_nacl_fix_patches (code, ji);
5977 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5979 emit_section_change (acfg, ".text", 0);
5980 emit_global (acfg, start_symbol, TRUE);
5981 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
5982 emit_label (acfg, start_symbol);
5984 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5985 emit_label (acfg, symbol);
5988 * The code should access everything through the GOT, so we pass
5991 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5993 emit_symbol_size (acfg, start_symbol, ".");
5996 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5997 emit_label (acfg, end_symbol);
6002 /* Sort relocations */
6003 patches = g_ptr_array_new ();
6004 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6005 if (patch_info->type != MONO_PATCH_INFO_NONE)
6006 g_ptr_array_add (patches, patch_info);
6007 g_ptr_array_sort (patches, compare_patches);
6009 buf_size = patches->len * 128 + 128;
6010 buf = g_malloc (buf_size);
6013 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6014 g_assert (p - buf < buf_size);
6016 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6018 info_offset = add_to_blob (acfg, buf, p - buf);
6020 emit_section_change (acfg, RODATA_SECT, 0);
6021 emit_global (acfg, symbol, FALSE);
6022 emit_label (acfg, symbol);
6024 emit_int32 (acfg, info_offset);
6028 guint32 encoded_len;
6032 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6034 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6035 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6038 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6039 emit_int32 (acfg, uw_offset);
6042 /* Emit debug info */
6046 sprintf (symbol, "%s", name);
6047 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6050 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6054 static G_GNUC_UNUSED void
6055 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6057 emit_trampoline_full (acfg, got_offset, info, FALSE);
6061 emit_trampolines (MonoAotCompile *acfg)
6064 char end_symbol [256];
6065 int i, tramp_got_offset;
6066 MonoAotTrampoline ntype;
6067 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6071 if (!acfg->aot_opts.full_aot)
6074 g_assert (acfg->image->assembly);
6076 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6077 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6078 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6079 MonoTrampInfo *info;
6082 * Emit the generic trampolines.
6084 * We could save some code by treating the generic trampolines as a wrapper
6085 * method, but that approach has its own complexities, so we choose the simpler
6088 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6089 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6090 #ifdef DISABLE_REMOTING
6091 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6094 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6095 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6098 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6099 emit_trampoline (acfg, acfg->got_offset, info);
6102 mono_arch_get_nullified_class_init_trampoline (&info);
6103 emit_trampoline (acfg, acfg->got_offset, info);
6104 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6105 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6106 emit_trampoline (acfg, acfg->got_offset, info);
6107 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6108 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6109 emit_trampoline (acfg, acfg->got_offset, info);
6111 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6112 emit_trampoline (acfg, acfg->got_offset, info);
6115 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6116 emit_trampoline (acfg, acfg->got_offset, info);
6118 /* Emit the exception related code pieces */
6119 mono_arch_get_restore_context (&info, TRUE);
6120 emit_trampoline (acfg, acfg->got_offset, info);
6121 mono_arch_get_call_filter (&info, TRUE);
6122 emit_trampoline (acfg, acfg->got_offset, info);
6123 mono_arch_get_throw_exception (&info, TRUE);
6124 emit_trampoline (acfg, acfg->got_offset, info);
6125 mono_arch_get_rethrow_exception (&info, TRUE);
6126 emit_trampoline (acfg, acfg->got_offset, info);
6127 mono_arch_get_throw_corlib_exception (&info, TRUE);
6128 emit_trampoline (acfg, acfg->got_offset, info);
6130 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6131 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6133 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6135 /* Create a separate out trampoline for more information in stack traces */
6136 info->name = g_strdup ("gsharedvt_out_trampoline");
6137 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6141 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6143 GSList *l = mono_arch_get_trampolines (TRUE);
6146 MonoTrampInfo *info = l->data;
6148 emit_trampoline (acfg, acfg->got_offset, info);
6154 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6157 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6158 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6159 emit_trampoline (acfg, acfg->got_offset, info);
6161 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6162 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6163 emit_trampoline (acfg, acfg->got_offset, info);
6166 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6167 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6168 emit_trampoline (acfg, acfg->got_offset, info);
6174 /* delegate_invoke_impl trampolines */
6175 l = mono_arch_get_delegate_invoke_impls ();
6177 MonoTrampInfo *info = l->data;
6179 emit_trampoline (acfg, acfg->got_offset, info);
6184 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6186 /* Emit trampolines which are numerous */
6189 * These include the following:
6190 * - specific trampolines
6191 * - static rgctx invoke trampolines
6193 * These trampolines have the same code, they are parameterized by GOT
6195 * They are defined in this file, in the arch_... routines instead of
6196 * in tramp-<ARCH>.c, since it is easier to do it this way.
6200 * When running in aot-only mode, we can't create specific trampolines at
6201 * runtime, so we create a few, and save them in the AOT file.
6202 * Normal trampolines embed their argument as a literal inside the
6203 * trampoline code, we can't do that here, so instead we embed an offset
6204 * which needs to be added to the trampoline address to get the address of
6205 * the GOT slot which contains the argument value.
6206 * The generated trampolines jump to the generic trampolines using another
6207 * GOT slot, which will be setup by the AOT loader to point to the
6208 * generic trampoline code of the given type.
6212 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6216 emit_section_change (acfg, ".text", 0);
6218 tramp_got_offset = acfg->got_offset;
6220 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6222 case MONO_AOT_TRAMP_SPECIFIC:
6223 sprintf (symbol, "specific_trampolines");
6225 case MONO_AOT_TRAMP_STATIC_RGCTX:
6226 sprintf (symbol, "static_rgctx_trampolines");
6228 case MONO_AOT_TRAMP_IMT_THUNK:
6229 sprintf (symbol, "imt_thunks");
6231 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6232 sprintf (symbol, "gsharedvt_arg_trampolines");
6235 g_assert_not_reached ();
6238 sprintf (end_symbol, "%s_e", symbol);
6240 if (acfg->aot_opts.write_symbols)
6241 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6243 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6244 emit_label (acfg, symbol);
6246 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6248 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6252 case MONO_AOT_TRAMP_SPECIFIC:
6253 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6254 tramp_got_offset += 2;
6256 case MONO_AOT_TRAMP_STATIC_RGCTX:
6257 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6258 tramp_got_offset += 2;
6260 case MONO_AOT_TRAMP_IMT_THUNK:
6261 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6262 tramp_got_offset += 1;
6264 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6265 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6266 tramp_got_offset += 2;
6269 g_assert_not_reached ();
6271 #ifdef __native_client_codegen__
6272 /* align to avoid 32-byte boundary crossings */
6273 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6276 if (!acfg->trampoline_size [ntype]) {
6277 g_assert (tramp_size);
6278 acfg->trampoline_size [ntype] = tramp_size;
6282 emit_label (acfg, end_symbol);
6283 emit_int32 (acfg, 0);
6286 arch_emit_specific_trampoline_pages (acfg);
6288 /* Reserve some entries at the end of the GOT for our use */
6289 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6292 acfg->got_offset += acfg->num_trampoline_got_entries;
6296 str_begins_with (const char *str1, const char *str2)
6298 int len = strlen (str2);
6299 return strncmp (str1, str2, len) == 0;
6303 mono_aot_readonly_field_override (MonoClassField *field)
6306 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6307 char *p = rdv->name;
6309 len = strlen (field->parent->name_space);
6310 if (strncmp (p, field->parent->name_space, len))
6315 len = strlen (field->parent->name);
6316 if (strncmp (p, field->parent->name, len))
6321 if (strcmp (p, field->name))
6323 switch (rdv->type) {
6325 return &rdv->value.i1;
6327 return &rdv->value.i2;
6329 return &rdv->value.i4;
6338 add_readonly_value (MonoAotOptions *opts, const char *val)
6343 /* the format of val is:
6344 * namespace.typename.fieldname=type/value
6345 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6347 fval = strrchr (val, '/');
6349 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6352 tval = strrchr (val, '=');
6354 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6357 rdv = g_new0 (ReadOnlyValue, 1);
6358 rdv->name = g_malloc0 (tval - val + 1);
6359 memcpy (rdv->name, val, tval - val);
6362 if (strncmp (tval, "i1", 2) == 0) {
6363 rdv->value.i1 = atoi (fval);
6364 rdv->type = MONO_TYPE_I1;
6365 } else if (strncmp (tval, "i2", 2) == 0) {
6366 rdv->value.i2 = atoi (fval);
6367 rdv->type = MONO_TYPE_I2;
6368 } else if (strncmp (tval, "i4", 2) == 0) {
6369 rdv->value.i4 = atoi (fval);
6370 rdv->type = MONO_TYPE_I4;
6372 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6375 rdv->next = readonly_values;
6376 readonly_values = rdv;
6380 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6382 gchar **args, **ptr;
6384 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6385 for (ptr = args; ptr && *ptr; ptr ++) {
6386 const char *arg = *ptr;
6388 if (str_begins_with (arg, "outfile=")) {
6389 opts->outfile = g_strdup (arg + strlen ("outfile="));
6390 } else if (str_begins_with (arg, "llvm-outfile=")) {
6391 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6392 } else if (str_begins_with (arg, "save-temps")) {
6393 opts->save_temps = TRUE;
6394 } else if (str_begins_with (arg, "keep-temps")) {
6395 opts->save_temps = TRUE;
6396 } else if (str_begins_with (arg, "write-symbols")) {
6397 opts->write_symbols = TRUE;
6398 } else if (str_begins_with (arg, "no-write-symbols")) {
6399 opts->write_symbols = FALSE;
6400 } else if (str_begins_with (arg, "metadata-only")) {
6401 opts->metadata_only = TRUE;
6402 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6403 opts->bind_to_runtime_version = TRUE;
6404 } else if (str_begins_with (arg, "full")) {
6405 opts->full_aot = TRUE;
6406 } else if (str_begins_with (arg, "threads=")) {
6407 opts->nthreads = atoi (arg + strlen ("threads="));
6408 } else if (str_begins_with (arg, "static")) {
6409 opts->static_link = TRUE;
6410 opts->no_dlsym = TRUE;
6411 } else if (str_begins_with (arg, "asmonly")) {
6412 opts->asm_only = TRUE;
6413 } else if (str_begins_with (arg, "asmwriter")) {
6414 opts->asm_writer = TRUE;
6415 } else if (str_begins_with (arg, "nodebug")) {
6416 opts->nodebug = TRUE;
6417 } else if (str_begins_with (arg, "dwarfdebug")) {
6418 opts->dwarf_debug = TRUE;
6419 } else if (str_begins_with (arg, "nopagetrampolines")) {
6420 opts->use_trampolines_page = FALSE;
6421 } else if (str_begins_with (arg, "ntrampolines=")) {
6422 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6423 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6424 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6425 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6426 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6427 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6428 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6429 } else if (str_begins_with (arg, "autoreg")) {
6430 opts->autoreg = TRUE;
6431 } else if (str_begins_with (arg, "tool-prefix=")) {
6432 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6433 } else if (str_begins_with (arg, "soft-debug")) {
6434 opts->soft_debug = TRUE;
6435 } else if (str_begins_with (arg, "direct-pinvoke")) {
6436 opts->direct_pinvoke = TRUE;
6437 } else if (str_begins_with (arg, "direct-icalls")) {
6438 opts->direct_icalls = TRUE;
6439 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6440 } else if (str_begins_with (arg, "iphone-abi")) {
6441 // older full-aot users did depend on this.
6443 } else if (str_begins_with (arg, "no-direct-calls")) {
6444 opts->no_direct_calls = TRUE;
6445 } else if (str_begins_with (arg, "print-skipped")) {
6446 opts->print_skipped_methods = TRUE;
6447 } else if (str_begins_with (arg, "stats")) {
6449 } else if (str_begins_with (arg, "no-instances")) {
6450 opts->no_instances = TRUE;
6451 } else if (str_begins_with (arg, "log-generics")) {
6452 opts->log_generics = TRUE;
6453 } else if (str_begins_with (arg, "log-instances=")) {
6454 opts->log_instances = TRUE;
6455 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6456 } else if (str_begins_with (arg, "log-instances")) {
6457 opts->log_instances = TRUE;
6458 } else if (str_begins_with (arg, "internal-logfile=")) {
6459 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6460 } else if (str_begins_with (arg, "mtriple=")) {
6461 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6462 } else if (str_begins_with (arg, "llvm-path=")) {
6463 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6464 } else if (!strcmp (arg, "llvm")) {
6466 } else if (str_begins_with (arg, "readonly-value=")) {
6467 add_readonly_value (opts, arg + strlen ("readonly-value="));
6468 } else if (str_begins_with (arg, "info")) {
6469 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6471 } else if (str_begins_with (arg, "gc-maps")) {
6472 mini_gc_enable_gc_maps_for_aot ();
6473 } else if (str_begins_with (arg, "dump")) {
6474 opts->dump_json = TRUE;
6475 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6476 printf ("Supported options for --aot:\n");
6477 printf (" outfile=\n");
6478 printf (" llvm-outfile=\n");
6479 printf (" save-temps\n");
6480 printf (" keep-temps\n");
6481 printf (" write-symbols\n");
6482 printf (" metadata-only\n");
6483 printf (" bind-to-runtime-version\n");
6485 printf (" threads=\n");
6486 printf (" static\n");
6487 printf (" asmonly\n");
6488 printf (" asmwriter\n");
6489 printf (" nodebug\n");
6490 printf (" dwarfdebug\n");
6491 printf (" ntrampolines=\n");
6492 printf (" nrgctx-trampolines=\n");
6493 printf (" nimt-trampolines=\n");
6494 printf (" ngsharedvt-trampolines=\n");
6495 printf (" autoreg\n");
6496 printf (" tool-prefix=\n");
6497 printf (" readonly-value=\n");
6498 printf (" soft-debug\n");
6499 printf (" gc-maps\n");
6500 printf (" print-skipped\n");
6501 printf (" no-instances\n");
6502 printf (" stats\n");
6505 printf (" help/?\n");
6508 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6513 if (opts->use_trampolines_page) {
6514 opts->ntrampolines = 0;
6515 opts->nrgctx_trampolines = 0;
6516 opts->nimt_trampolines = 0;
6517 opts->ngsharedvt_arg_trampolines = 0;
6523 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6525 MonoMethod *method = (MonoMethod*)key;
6526 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6527 MonoAotCompile *acfg = user_data;
6528 MonoJumpInfoToken *new_ji;
6530 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6531 new_ji->image = ji->image;
6532 new_ji->token = ji->token;
6533 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6537 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6539 if (klass->type_token)
6541 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6544 return can_encode_class (acfg, klass->element_class);
6549 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6551 if (method->wrapper_type) {
6552 switch (method->wrapper_type) {
6553 case MONO_WRAPPER_NONE:
6554 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6555 case MONO_WRAPPER_XDOMAIN_INVOKE:
6556 case MONO_WRAPPER_STFLD:
6557 case MONO_WRAPPER_LDFLD:
6558 case MONO_WRAPPER_LDFLDA:
6559 case MONO_WRAPPER_LDFLD_REMOTE:
6560 case MONO_WRAPPER_STFLD_REMOTE:
6561 case MONO_WRAPPER_STELEMREF:
6562 case MONO_WRAPPER_ISINST:
6563 case MONO_WRAPPER_PROXY_ISINST:
6564 case MONO_WRAPPER_ALLOC:
6565 case MONO_WRAPPER_REMOTING_INVOKE:
6566 case MONO_WRAPPER_UNKNOWN:
6567 case MONO_WRAPPER_WRITE_BARRIER:
6568 case MONO_WRAPPER_DELEGATE_INVOKE:
6569 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6570 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6571 case MONO_WRAPPER_SYNCHRONIZED:
6573 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6574 case MONO_WRAPPER_CASTCLASS: {
6575 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6584 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6588 if (!method->token) {
6589 /* The method is part of a constructed type like Int[,].Set (). */
6590 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6591 if (method->klass->rank)
6601 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6603 switch (patch_info->type) {
6604 case MONO_PATCH_INFO_METHOD:
6605 case MONO_PATCH_INFO_METHODCONST:
6606 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6607 MonoMethod *method = patch_info->data.method;
6609 return can_encode_method (acfg, method);
6611 case MONO_PATCH_INFO_VTABLE:
6612 case MONO_PATCH_INFO_CLASS_INIT:
6613 case MONO_PATCH_INFO_CLASS:
6614 case MONO_PATCH_INFO_IID:
6615 case MONO_PATCH_INFO_ADJUSTED_IID:
6616 if (!can_encode_class (acfg, patch_info->data.klass)) {
6617 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6621 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6622 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6623 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6628 case MONO_PATCH_INFO_RGCTX_FETCH: {
6629 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6631 if (!can_encode_method (acfg, entry->method))
6633 if (!can_encode_patch (acfg, entry->data))
6647 * AOT compile a given method.
6648 * This function might be called by multiple threads, so it must be thread-safe.
6651 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6654 MonoJumpInfo *patch_info;
6657 MonoMethod *wrapped;
6660 if (acfg->aot_opts.metadata_only)
6663 mono_acfg_lock (acfg);
6664 index = get_method_index (acfg, method);
6665 mono_acfg_unlock (acfg);
6667 /* fixme: maybe we can also precompile wrapper methods */
6668 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6669 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6670 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6671 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6675 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6678 wrapped = mono_marshal_method_from_wrapper (method);
6679 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6680 // FIXME: The wrapper should be generic too, but it is not
6683 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6686 InterlockedIncrement (&acfg->stats.mcount);
6689 if (method->is_generic || method->klass->generic_container) {
6690 InterlockedIncrement (&acfg->stats.genericcount);
6695 //acfg->aot_opts.print_skipped_methods = TRUE;
6698 * Since these methods are the only ones which are compiled with
6699 * AOT support, and they are not used by runtime startup/shutdown code,
6700 * the runtime will not see AOT methods during AOT compilation,so it
6701 * does not need to support them by creating a fake GOT etc.
6703 flags = JIT_FLAG_AOT;
6704 if (acfg->aot_opts.full_aot)
6705 flags |= JIT_FLAG_FULL_AOT;
6707 flags |= JIT_FLAG_LLVM;
6708 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6709 mono_loader_clear_error ();
6711 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6712 if (acfg->aot_opts.print_skipped_methods)
6713 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6714 InterlockedIncrement (&acfg->stats.genericcount);
6717 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6718 if (acfg->aot_opts.print_skipped_methods)
6719 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6720 /* Let the exception happen at runtime */
6724 if (cfg->disable_aot) {
6725 if (acfg->aot_opts.print_skipped_methods)
6726 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6727 InterlockedIncrement (&acfg->stats.ocount);
6728 mono_destroy_compile (cfg);
6731 cfg->method_index = index;
6733 /* Nullify patches which need no aot processing */
6734 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6735 switch (patch_info->type) {
6736 case MONO_PATCH_INFO_LABEL:
6737 case MONO_PATCH_INFO_BB:
6738 patch_info->type = MONO_PATCH_INFO_NONE;
6745 /* Collect method->token associations from the cfg */
6746 mono_acfg_lock (acfg);
6747 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6748 mono_acfg_unlock (acfg);
6749 g_hash_table_destroy (cfg->token_info_hash);
6750 cfg->token_info_hash = NULL;
6753 * Check for absolute addresses.
6756 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6757 switch (patch_info->type) {
6758 case MONO_PATCH_INFO_ABS:
6759 /* unable to handle this */
6768 if (acfg->aot_opts.print_skipped_methods)
6769 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6770 InterlockedIncrement (&acfg->stats.abscount);
6771 mono_destroy_compile (cfg);
6775 /* Lock for the rest of the code */
6776 mono_acfg_lock (acfg);
6779 * Check for methods/klasses we can't encode.
6782 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6783 if (!can_encode_patch (acfg, patch_info))
6788 if (acfg->aot_opts.print_skipped_methods)
6789 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6790 acfg->stats.ocount++;
6791 mono_destroy_compile (cfg);
6792 mono_acfg_unlock (acfg);
6796 if (method->is_inflated && acfg->aot_opts.log_instances) {
6797 if (acfg->instances_logfile)
6798 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6800 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6803 /* Adds generic instances referenced by this method */
6805 * The depth is used to avoid infinite loops when generic virtual recursion is
6808 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6809 if (!acfg->aot_opts.no_instances && depth < 32) {
6810 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6811 switch (patch_info->type) {
6812 case MONO_PATCH_INFO_METHOD: {
6813 MonoMethod *m = patch_info->data.method;
6814 if (m->is_inflated) {
6815 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6816 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6817 !method_has_type_vars (m)) {
6818 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6819 if (acfg->aot_opts.full_aot)
6820 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6822 add_extra_method_with_depth (acfg, m, depth + 1);
6823 add_types_from_method_header (acfg, m);
6826 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6828 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6829 add_extra_method_with_depth (acfg, m, depth + 1);
6832 case MONO_PATCH_INFO_VTABLE: {
6833 MonoClass *klass = patch_info->data.klass;
6835 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6836 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6839 case MONO_PATCH_INFO_SFLDA: {
6840 MonoClass *klass = patch_info->data.field->parent;
6842 /* The .cctor needs to run at runtime. */
6843 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6844 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6853 /* Determine whenever the method has GOT slots */
6854 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6855 switch (patch_info->type) {
6856 case MONO_PATCH_INFO_GOT_OFFSET:
6857 case MONO_PATCH_INFO_NONE:
6858 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6860 case MONO_PATCH_INFO_IMAGE:
6861 /* The assembly is stored in GOT slot 0 */
6862 if (patch_info->data.image != acfg->image)
6863 cfg->has_got_slots = TRUE;
6866 if (!is_plt_patch (patch_info))
6867 cfg->has_got_slots = TRUE;
6872 if (!cfg->has_got_slots)
6873 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6876 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6878 /* Make a copy of the patch info which is in the mempool */
6880 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6882 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6883 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6886 patches = new_patch_info;
6888 patches_end->next = new_patch_info;
6889 patches_end = new_patch_info;
6891 cfg->patch_info = patches;
6893 /* Make a copy of the unwind info */
6895 GSList *l, *unwind_ops;
6899 for (l = cfg->unwind_ops; l; l = l->next) {
6900 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6901 memcpy (op, l->data, sizeof (MonoUnwindOp));
6902 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6904 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6906 /* Make a copy of the argument/local info */
6908 MonoInst **args, **locals;
6909 MonoMethodSignature *sig;
6910 MonoMethodHeader *header;
6913 sig = mono_method_signature (method);
6914 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6915 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6916 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6917 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6921 header = mono_method_get_header (method);
6922 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6923 for (i = 0; i < header->num_locals; ++i) {
6924 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6925 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6927 cfg->locals = locals;
6930 /* Free some fields used by cfg to conserve memory */
6931 mono_mempool_destroy (cfg->mempool);
6932 cfg->mempool = NULL;
6933 g_free (cfg->varinfo);
6934 cfg->varinfo = NULL;
6938 mono_regstate_free (cfg->rs);
6942 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6944 while (index >= acfg->cfgs_size) {
6945 MonoCompile **new_cfgs;
6948 new_size = acfg->cfgs_size * 2;
6949 new_cfgs = g_new0 (MonoCompile*, new_size);
6950 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6951 g_free (acfg->cfgs);
6952 acfg->cfgs = new_cfgs;
6953 acfg->cfgs_size = new_size;
6955 acfg->cfgs [index] = cfg;
6957 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6960 if (cfg->orig_method->wrapper_type)
6961 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6964 mono_acfg_unlock (acfg);
6966 InterlockedIncrement (&acfg->stats.ccount);
6970 compile_thread_main (gpointer *user_data)
6972 MonoDomain *domain = user_data [0];
6973 MonoAotCompile *acfg = user_data [1];
6974 GPtrArray *methods = user_data [2];
6977 mono_thread_attach (domain);
6979 for (i = 0; i < methods->len; ++i)
6980 compile_method (acfg, g_ptr_array_index (methods, i));
6984 load_profile_files (MonoAotCompile *acfg)
6988 int file_index, res, method_index, i;
6991 GList *unordered, *l;
6996 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6998 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7003 infile = fopen (tmp, "r");
7006 printf ("Using profile data file '%s'\n", tmp);
7011 res = fscanf (infile, "%32s\n", ver);
7012 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7013 printf ("Profile file has wrong version or invalid.\n");
7020 MonoMethodDesc *desc;
7023 if (fgets (name, 1023, infile) == NULL)
7026 /* Kill the newline */
7027 if (strlen (name) > 0)
7028 name [strlen (name) - 1] = '\0';
7030 desc = mono_method_desc_new (name, TRUE);
7032 method = mono_method_desc_search_in_image (desc, acfg->image);
7034 if (method && mono_method_get_token (method)) {
7035 token = mono_method_get_token (method);
7036 method_index = mono_metadata_token_index (token) - 1;
7039 for (i = 0; i < acfg->method_order->len; ++i) {
7040 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7046 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7048 //printf ("No method found matching '%s'.\n", name);
7054 /* Add missing methods */
7056 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7058 for (i = 0; i < acfg->method_order->len; ++i) {
7059 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7065 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7067 unordered = g_list_reverse (unordered);
7068 for (l = unordered; l; l = l->next)
7069 g_ptr_array_add (acfg->method_order, l->data);
7072 /* Used by the LLVM backend */
7074 mono_aot_get_got_offset (MonoJumpInfo *ji)
7076 return get_got_offset (llvm_acfg, TRUE, ji);
7080 mono_aot_get_method_name (MonoCompile *cfg)
7082 if (llvm_acfg->aot_opts.static_link)
7083 /* Include the assembly name too to avoid duplicate symbol errors */
7084 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7086 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7090 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7092 return is_direct_callable (llvm_acfg, NULL, patch_info);
7096 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7098 MonoPltEntry *plt_entry;
7100 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7101 plt_entry->llvm_used = FALSE;
7105 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7107 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7108 MonoPltEntry *plt_entry;
7111 ji->data.target = data;
7113 if (!can_encode_patch (llvm_acfg, ji))
7116 plt_entry = get_plt_entry (llvm_acfg, ji);
7117 plt_entry->llvm_used = TRUE;
7119 #if defined(TARGET_MACH)
7120 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7122 return g_strdup_printf (plt_entry->llvm_symbol);
7127 mono_aot_get_method_index (MonoMethod *method)
7129 g_assert (llvm_acfg);
7130 return get_method_index (llvm_acfg, method);
7134 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7138 mono_acfg_lock (llvm_acfg);
7139 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7140 mono_acfg_unlock (llvm_acfg);
7150 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7154 emit_llvm_file (MonoAotCompile *acfg)
7156 char *command, *opts, *tempbc, *output_fname;
7158 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7159 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7163 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7164 * a lot of time, and doesn't seem to save much space.
7165 * The following optimizations cannot be enabled:
7167 * - 'jump-threading' changes our blockaddress references to int constants.
7168 * - 'basiccg' fails because it contains:
7169 * if (CS && !isa<IntrinsicInst>(II)) {
7170 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7171 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7172 * The opt list below was produced by taking the output of:
7173 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7174 * then removing tailcallelim + the global opts.
7175 * strip-dead-prototypes deletes unused intrinsics definitions.
7177 opts = g_strdup ("-instcombine -simplifycfg");
7178 //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 -domtree -verify");
7179 /* The dse pass is disabled because of #13734 and #17616 */
7181 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7182 * // If we have no DataLayout information around, then the size of the store
7183 * // is inferrable from the pointee type. If they are the same type, then
7184 * // we know that the store is safe.
7185 * if (AA.getDataLayout() == 0 &&
7186 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7187 * return OverwriteComplete;
7188 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7190 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7192 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7193 aot_printf (acfg, "Executing opt: %s\n", command);
7194 if (system (command) != 0)
7199 if (!acfg->llc_args)
7200 acfg->llc_args = g_string_new ("");
7202 /* Verbose asm slows down llc greatly */
7203 g_string_append (acfg->llc_args, " -asm-verbose=false");
7205 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7207 if (acfg->aot_opts.mtriple)
7208 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7210 if (acfg->llvm_separate)
7211 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7213 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7214 /* ios requires PIC code now */
7215 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7217 if (llvm_acfg->aot_opts.static_link)
7218 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7220 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7222 unlink (acfg->tmpfname);
7224 if (acfg->llvm_separate) {
7225 if (acfg->llvm_owriter) {
7226 /* Emit an object file directly */
7227 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7228 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7230 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7233 output_fname = g_strdup (acfg->tmpfname);
7235 command = g_strdup_printf ("%sllc %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7237 aot_printf (acfg, "Executing llc: %s\n", command);
7239 if (system (command) != 0)
7246 emit_code (MonoAotCompile *acfg)
7248 int oindex, i, prev_index;
7251 #if defined(TARGET_POWERPC64)
7252 sprintf (symbol, ".Lgot_addr");
7253 emit_section_change (acfg, ".text", 0);
7254 emit_alignment (acfg, 8);
7255 emit_label (acfg, symbol);
7256 emit_pointer (acfg, acfg->got_symbol);
7260 * This global symbol is used to compute the address of each method using the
7261 * code_offsets array. It is also used to compute the memory ranges occupied by
7262 * AOT code, so it must be equal to the address of the first emitted method.
7264 emit_section_change (acfg, ".text", 0);
7265 emit_alignment_code (acfg, 8);
7267 for (i = 0; i < acfg->nmethods; ++i) {
7268 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7269 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7274 if (!acfg->methods_symbol) {
7275 sprintf (symbol, "methods");
7276 emit_label (acfg, symbol);
7277 acfg->methods_symbol = g_strdup (symbol);
7279 emit_label (acfg, "jit_code_start");
7282 * Emit some padding so the local symbol for the first method doesn't have the
7283 * same address as 'methods'.
7285 #if defined(__default_codegen__)
7286 emit_padding (acfg, 16);
7287 #elif defined(__native_client_codegen__)
7289 const int kPaddingSize = 16;
7290 guint8 pad_buffer[kPaddingSize];
7291 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7292 emit_bytes (acfg, pad_buffer, kPaddingSize);
7296 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7300 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7302 cfg = acfg->cfgs [i];
7307 method = cfg->orig_method;
7309 /* Emit unbox trampoline */
7310 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7311 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7313 emit_section_change (acfg, ".text", 0);
7314 #ifdef __native_client_codegen__
7315 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7318 if (acfg->thumb_mixed && cfg->compile_llvm) {
7319 emit_set_thumb_mode (acfg);
7320 fprintf (acfg->fp, "\n.thumb_func\n");
7323 emit_label (acfg, symbol);
7325 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7327 if (acfg->thumb_mixed && cfg->compile_llvm)
7328 emit_set_arm_mode (acfg);
7331 if (cfg->compile_llvm)
7332 acfg->stats.llvm_count ++;
7334 emit_method_code (acfg, cfg);
7337 sprintf (symbol, "methods_end");
7338 emit_section_change (acfg, ".text", 0);
7339 emit_alignment_code (acfg, 8);
7340 emit_label (acfg, symbol);
7342 emit_label (acfg, "jit_code_end");
7344 /* To distinguish it from the next symbol */
7345 emit_padding (acfg, 4);
7348 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7349 * from optimizing them away, since it doesn't see that code_offsets references them.
7350 * JITted methods don't need this since they are referenced using assembler local
7352 * FIXME: This is why write-symbols doesn't work on OSX ?
7354 if (acfg->llvm && acfg->need_no_dead_strip) {
7355 fprintf (acfg->fp, "\n");
7356 for (i = 0; i < acfg->nmethods; ++i) {
7357 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7358 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7363 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7364 * This is PIE code, and the linker can update it if needed.
7366 sprintf (symbol, "method_addresses");
7367 emit_section_change (acfg, ".text", 1);
7368 emit_alignment_code (acfg, 8);
7369 emit_label (acfg, symbol);
7370 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7371 emit_unset_mode (acfg);
7372 if (acfg->need_no_dead_strip)
7373 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7375 for (i = 0; i < acfg->nmethods; ++i) {
7376 #ifdef MONO_ARCH_AOT_SUPPORTED
7380 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7382 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7386 sprintf (symbol, "method_addresses_end");
7387 emit_label (acfg, symbol);
7390 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7391 sprintf (symbol, "unbox_trampolines");
7392 emit_section_change (acfg, RODATA_SECT, 0);
7393 emit_alignment (acfg, 8);
7394 emit_label (acfg, symbol);
7397 for (i = 0; i < acfg->nmethods; ++i) {
7402 cfg = acfg->cfgs [i];
7406 method = cfg->orig_method;
7408 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7409 index = get_method_index (acfg, method);
7411 emit_int32 (acfg, index);
7412 /* Make sure the table is sorted by index */
7413 g_assert (index > prev_index);
7417 sprintf (symbol, "unbox_trampolines_end");
7418 emit_label (acfg, symbol);
7419 emit_int32 (acfg, 0);
7421 /* Emit a separate table with the trampoline addresses/offsets */
7422 sprintf (symbol, "unbox_trampoline_addresses");
7423 emit_section_change (acfg, ".text", 0);
7424 emit_alignment_code (acfg, 8);
7425 emit_label (acfg, symbol);
7427 for (i = 0; i < acfg->nmethods; ++i) {
7432 cfg = acfg->cfgs [i];
7436 method = cfg->orig_method;
7438 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7439 #ifdef MONO_ARCH_AOT_SUPPORTED
7442 index = get_method_index (acfg, method);
7443 sprintf (symbol, "ut_%d", index);
7445 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7452 emit_info (MonoAotCompile *acfg)
7458 offsets = g_new0 (gint32, acfg->nmethods);
7460 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7461 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7463 if (acfg->cfgs [i]) {
7464 emit_method_info (acfg, acfg->cfgs [i]);
7465 offsets [i] = acfg->cfgs [i]->method_info_offset;
7471 sprintf (symbol, "method_info_offsets");
7472 emit_section_change (acfg, RODATA_SECT, 1);
7473 emit_alignment (acfg, 8);
7474 emit_label (acfg, symbol);
7476 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7481 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7483 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7484 #define mix(a,b,c) { \
7485 a -= c; a ^= rot(c, 4); c += b; \
7486 b -= a; b ^= rot(a, 6); a += c; \
7487 c -= b; c ^= rot(b, 8); b += a; \
7488 a -= c; a ^= rot(c,16); c += b; \
7489 b -= a; b ^= rot(a,19); a += c; \
7490 c -= b; c ^= rot(b, 4); b += a; \
7492 #define final(a,b,c) { \
7493 c ^= b; c -= rot(b,14); \
7494 a ^= c; a -= rot(c,11); \
7495 b ^= a; b -= rot(a,25); \
7496 c ^= b; c -= rot(b,16); \
7497 a ^= c; a -= rot(c,4); \
7498 b ^= a; b -= rot(a,14); \
7499 c ^= b; c -= rot(b,24); \
7503 mono_aot_type_hash (MonoType *t1)
7505 guint hash = t1->type;
7507 hash |= t1->byref << 6; /* do not collide with t1->type values */
7509 case MONO_TYPE_VALUETYPE:
7510 case MONO_TYPE_CLASS:
7511 case MONO_TYPE_SZARRAY:
7512 /* check if the distribution is good enough */
7513 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7515 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7516 case MONO_TYPE_ARRAY:
7517 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7518 case MONO_TYPE_GENERICINST:
7519 return ((hash << 5) - hash) ^ 0;
7526 * mono_aot_method_hash:
7528 * Return a hash code for methods which only depends on metadata.
7531 mono_aot_method_hash (MonoMethod *method)
7533 MonoMethodSignature *sig;
7537 guint32 *hashes_start, *hashes;
7539 MonoGenericInst *ginst = NULL;
7541 /* Similar to the hash in mono_method_get_imt_slot () */
7543 sig = mono_method_signature (method);
7545 if (method->is_inflated)
7546 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7548 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7549 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7550 hashes = hashes_start;
7552 /* Some wrappers are assigned to random classes */
7553 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7554 klass = method->klass;
7556 klass = mono_defaults.object_class;
7558 if (!method->wrapper_type) {
7559 char *full_name = mono_type_full_name (&klass->byval_arg);
7561 hashes [0] = mono_metadata_str_hash (full_name);
7565 hashes [0] = mono_metadata_str_hash (klass->name);
7566 hashes [1] = mono_metadata_str_hash (klass->name_space);
7568 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7569 /* The method name includes a stringified pointer */
7572 hashes [2] = mono_metadata_str_hash (method->name);
7573 hashes [3] = method->wrapper_type;
7574 hashes [4] = mono_aot_type_hash (sig->ret);
7576 for (i = 0; i < sig->param_count; i++) {
7577 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7580 for (i = 0; i < ginst->type_argc; ++i)
7581 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7583 g_assert (hindex == hashes_count);
7585 /* Setup internal state */
7586 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7588 /* Handle most of the hashes */
7589 while (hashes_count > 3) {
7598 /* Handle the last 3 hashes (all the case statements fall through) */
7599 switch (hashes_count) {
7600 case 3 : c += hashes [2];
7601 case 2 : b += hashes [1];
7602 case 1 : a += hashes [0];
7604 case 0: /* nothing left to add */
7608 free (hashes_start);
7617 * mono_aot_get_array_helper_from_wrapper;
7619 * Get the helper method in Array called by an array wrapper method.
7622 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7626 MonoGenericContext ctx;
7627 MonoType *args [16];
7628 char *mname, *iname, *s, *s2, *helper_name = NULL;
7630 prefix = "System.Collections.Generic";
7631 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7632 s2 = strstr (s, "`1.");
7638 //printf ("X: %s %s\n", iname, mname);
7640 if (!strcmp (iname, "IList"))
7641 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7643 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7644 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7646 g_free (helper_name);
7649 if (m->is_generic) {
7651 memset (&ctx, 0, sizeof (ctx));
7652 args [0] = &method->klass->element_class->byval_arg;
7653 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7654 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7655 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7661 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7663 typedef struct HashEntry {
7664 guint32 key, value, index;
7665 struct HashEntry *next;
7669 * emit_extra_methods:
7671 * Emit methods which are not in the METHOD table, like wrappers.
7674 emit_extra_methods (MonoAotCompile *acfg)
7676 int i, table_size, buf_size;
7679 guint32 *info_offsets;
7682 HashEntry *entry, *new_entry;
7683 int nmethods, max_chain_length;
7686 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7688 /* Emit method info */
7690 for (i = 0; i < acfg->extra_methods->len; ++i) {
7691 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7692 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7698 p = buf = g_malloc (buf_size);
7702 method = cfg->method_to_register;
7704 encode_method_ref (acfg, method, p, &p);
7706 g_assert ((p - buf) < buf_size);
7708 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7713 * Construct a chained hash table for mapping indexes in extra_method_info to
7716 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7717 table = g_ptr_array_sized_new (table_size);
7718 for (i = 0; i < table_size; ++i)
7719 g_ptr_array_add (table, NULL);
7720 chain_lengths = g_new0 (int, table_size);
7721 max_chain_length = 0;
7722 for (i = 0; i < acfg->extra_methods->len; ++i) {
7723 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7724 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7730 key = info_offsets [i];
7731 value = get_method_index (acfg, method);
7733 hash = mono_aot_method_hash (method) % table_size;
7734 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7736 chain_lengths [hash] ++;
7737 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7739 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7740 new_entry->key = key;
7741 new_entry->value = value;
7743 entry = g_ptr_array_index (table, hash);
7744 if (entry == NULL) {
7745 new_entry->index = hash;
7746 g_ptr_array_index (table, hash) = new_entry;
7749 entry = entry->next;
7751 entry->next = new_entry;
7752 new_entry->index = table->len;
7753 g_ptr_array_add (table, new_entry);
7757 //printf ("MAX: %d\n", max_chain_length);
7759 /* Emit the table */
7760 sprintf (symbol, "extra_method_table");
7761 emit_section_change (acfg, RODATA_SECT, 0);
7762 emit_alignment (acfg, 8);
7763 emit_label (acfg, symbol);
7765 emit_int32 (acfg, table_size);
7766 for (i = 0; i < table->len; ++i) {
7767 HashEntry *entry = g_ptr_array_index (table, i);
7769 if (entry == NULL) {
7770 emit_int32 (acfg, 0);
7771 emit_int32 (acfg, 0);
7772 emit_int32 (acfg, 0);
7774 //g_assert (entry->key > 0);
7775 emit_int32 (acfg, entry->key);
7776 emit_int32 (acfg, entry->value);
7778 emit_int32 (acfg, entry->next->index);
7780 emit_int32 (acfg, 0);
7785 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7786 * This is used by mono_aot_find_jit_info ().
7788 sprintf (symbol, "extra_method_info_offsets");
7789 emit_section_change (acfg, RODATA_SECT, 0);
7790 emit_alignment (acfg, 8);
7791 emit_label (acfg, symbol);
7793 emit_int32 (acfg, acfg->extra_methods->len);
7794 for (i = 0; i < acfg->extra_methods->len; ++i) {
7795 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7797 emit_int32 (acfg, get_method_index (acfg, method));
7798 emit_int32 (acfg, info_offsets [i]);
7803 emit_exception_info (MonoAotCompile *acfg)
7809 offsets = g_new0 (gint32, acfg->nmethods);
7810 for (i = 0; i < acfg->nmethods; ++i) {
7811 if (acfg->cfgs [i]) {
7812 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7813 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7819 sprintf (symbol, "ex_info_offsets");
7820 emit_section_change (acfg, RODATA_SECT, 1);
7821 emit_alignment (acfg, 8);
7822 emit_label (acfg, symbol);
7824 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7829 emit_unwind_info (MonoAotCompile *acfg)
7835 * The unwind info contains a lot of duplicates so we emit each unique
7836 * entry once, and only store the offset from the start of the table in the
7840 sprintf (symbol, "unwind_info");
7841 emit_section_change (acfg, RODATA_SECT, 1);
7842 emit_alignment (acfg, 8);
7843 emit_label (acfg, symbol);
7845 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7846 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7847 guint8 *unwind_info;
7848 guint32 unwind_info_len;
7852 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7855 encode_value (unwind_info_len, p, &p);
7856 emit_bytes (acfg, buf, p - buf);
7857 emit_bytes (acfg, unwind_info, unwind_info_len);
7859 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7864 emit_class_info (MonoAotCompile *acfg)
7870 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7871 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7872 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7874 sprintf (symbol, "class_info_offsets");
7875 emit_section_change (acfg, RODATA_SECT, 1);
7876 emit_alignment (acfg, 8);
7877 emit_label (acfg, symbol);
7879 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7883 typedef struct ClassNameTableEntry {
7884 guint32 token, index;
7885 struct ClassNameTableEntry *next;
7886 } ClassNameTableEntry;
7889 emit_class_name_table (MonoAotCompile *acfg)
7892 guint32 token, hash;
7897 ClassNameTableEntry *entry, *new_entry;
7900 * Construct a chained hash table for mapping class names to typedef tokens.
7902 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7903 table = g_ptr_array_sized_new (table_size);
7904 for (i = 0; i < table_size; ++i)
7905 g_ptr_array_add (table, NULL);
7906 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7908 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7909 klass = mono_class_get_checked (acfg->image, token, &error);
7911 mono_error_cleanup (&error);
7914 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7915 hash = mono_metadata_str_hash (full_name) % table_size;
7918 /* FIXME: Allocate from the mempool */
7919 new_entry = g_new0 (ClassNameTableEntry, 1);
7920 new_entry->token = token;
7922 entry = g_ptr_array_index (table, hash);
7923 if (entry == NULL) {
7924 new_entry->index = hash;
7925 g_ptr_array_index (table, hash) = new_entry;
7928 entry = entry->next;
7930 entry->next = new_entry;
7931 new_entry->index = table->len;
7932 g_ptr_array_add (table, new_entry);
7936 /* Emit the table */
7937 sprintf (symbol, "class_name_table");
7938 emit_section_change (acfg, RODATA_SECT, 0);
7939 emit_alignment (acfg, 8);
7940 emit_label (acfg, symbol);
7942 /* FIXME: Optimize memory usage */
7943 g_assert (table_size < 65000);
7944 emit_int16 (acfg, table_size);
7945 g_assert (table->len < 65000);
7946 for (i = 0; i < table->len; ++i) {
7947 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7949 if (entry == NULL) {
7950 emit_int16 (acfg, 0);
7951 emit_int16 (acfg, 0);
7953 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7955 emit_int16 (acfg, entry->next->index);
7957 emit_int16 (acfg, 0);
7963 emit_image_table (MonoAotCompile *acfg)
7969 * The image table is small but referenced in a lot of places.
7970 * So we emit it at once, and reference its elements by an index.
7973 sprintf (symbol, "image_table");
7974 emit_section_change (acfg, RODATA_SECT, 1);
7975 emit_alignment (acfg, 8);
7976 emit_label (acfg, symbol);
7978 emit_int32 (acfg, acfg->image_table->len);
7979 for (i = 0; i < acfg->image_table->len; i++) {
7980 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7981 MonoAssemblyName *aname = &image->assembly->aname;
7983 /* FIXME: Support multi-module assemblies */
7984 g_assert (image->assembly->image == image);
7986 emit_string (acfg, image->assembly_name);
7987 emit_string (acfg, image->guid);
7988 emit_string (acfg, aname->culture ? aname->culture : "");
7989 emit_string (acfg, (const char*)aname->public_key_token);
7991 emit_alignment (acfg, 8);
7992 emit_int32 (acfg, aname->flags);
7993 emit_int32 (acfg, aname->major);
7994 emit_int32 (acfg, aname->minor);
7995 emit_int32 (acfg, aname->build);
7996 emit_int32 (acfg, aname->revision);
8001 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8004 int i, first_plt_got_patch = 0, buf_size;
8006 guint32 *got_info_offsets;
8007 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8009 /* Add the patches needed by the PLT to the GOT */
8011 acfg->plt_got_offset_base = acfg->got_offset;
8012 first_plt_got_patch = info->got_patches->len;
8013 for (i = 1; i < acfg->plt_offset; ++i) {
8014 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8016 g_ptr_array_add (info->got_patches, plt_entry->ji);
8018 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8021 acfg->got_offset += acfg->plt_offset;
8026 * - optimize offsets table.
8027 * - reduce number of exported symbols.
8028 * - emit info for a klass only once.
8029 * - determine when a method uses a GOT slot which is guaranteed to be already
8031 * - clean up and document the code.
8032 * - use String.Empty in class libs.
8035 /* Encode info required to decode shared GOT entries */
8036 buf_size = info->got_patches->len * 128;
8037 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8038 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8040 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8042 if (acfg->plt_offset)
8043 acfg->plt_got_info_offsets [0] = 0;
8045 for (i = 0; i < info->got_patches->len; ++i) {
8046 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8051 encode_value (ji->type, p, &p);
8053 encode_patch (acfg, ji, p, &p);
8054 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8055 g_assert (p - buf <= buf_size);
8056 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8058 if (!llvm && i >= first_plt_got_patch)
8059 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8060 acfg->stats.got_info_size += p - buf;
8063 /* Emit got_info_offsets table */
8065 sprintf (symbol, "llvm_got_info_offsets");
8067 sprintf (symbol, "got_info_offsets");
8068 emit_section_change (acfg, RODATA_SECT, 1);
8069 emit_alignment (acfg, 8);
8070 emit_label (acfg, symbol);
8072 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8073 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8077 emit_got (MonoAotCompile *acfg)
8081 /* Don't make GOT global so accesses to it don't need relocations */
8082 sprintf (symbol, "%s", acfg->got_symbol);
8083 emit_section_change (acfg, ".bss", 0);
8084 emit_alignment (acfg, 8);
8085 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8086 emit_label (acfg, symbol);
8087 if (acfg->got_offset > 0)
8088 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8090 sprintf (symbol, "got_end");
8091 emit_label (acfg, symbol);
8094 typedef struct GlobalsTableEntry {
8095 guint32 value, index;
8096 struct GlobalsTableEntry *next;
8097 } GlobalsTableEntry;
8100 emit_globals (MonoAotCompile *acfg)
8106 GlobalsTableEntry *entry, *new_entry;
8108 if (!acfg->aot_opts.static_link)
8112 * When static linking, we emit a table containing our globals.
8116 * Construct a chained hash table for mapping global names to their index in
8117 * the globals table.
8119 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8120 table = g_ptr_array_sized_new (table_size);
8121 for (i = 0; i < table_size; ++i)
8122 g_ptr_array_add (table, NULL);
8123 for (i = 0; i < acfg->globals->len; ++i) {
8124 char *name = g_ptr_array_index (acfg->globals, i);
8126 hash = mono_metadata_str_hash (name) % table_size;
8128 /* FIXME: Allocate from the mempool */
8129 new_entry = g_new0 (GlobalsTableEntry, 1);
8130 new_entry->value = i;
8132 entry = g_ptr_array_index (table, hash);
8133 if (entry == NULL) {
8134 new_entry->index = hash;
8135 g_ptr_array_index (table, hash) = new_entry;
8138 entry = entry->next;
8140 entry->next = new_entry;
8141 new_entry->index = table->len;
8142 g_ptr_array_add (table, new_entry);
8146 /* Emit the table */
8147 sprintf (symbol, ".Lglobals_hash");
8148 emit_section_change (acfg, RODATA_SECT, 0);
8149 emit_alignment (acfg, 8);
8150 emit_label (acfg, symbol);
8152 /* FIXME: Optimize memory usage */
8153 g_assert (table_size < 65000);
8154 emit_int16 (acfg, table_size);
8155 for (i = 0; i < table->len; ++i) {
8156 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8158 if (entry == NULL) {
8159 emit_int16 (acfg, 0);
8160 emit_int16 (acfg, 0);
8162 emit_int16 (acfg, entry->value + 1);
8164 emit_int16 (acfg, entry->next->index);
8166 emit_int16 (acfg, 0);
8170 /* Emit the names */
8171 for (i = 0; i < acfg->globals->len; ++i) {
8172 char *name = g_ptr_array_index (acfg->globals, i);
8174 sprintf (symbol, "name_%d", i);
8175 emit_section_change (acfg, RODATA_SECT, 1);
8177 emit_alignment (acfg, 4);
8179 emit_label (acfg, symbol);
8180 emit_string (acfg, name);
8183 /* Emit the globals table */
8184 sprintf (symbol, "globals");
8185 emit_section_change (acfg, ".data", 0);
8186 /* This is not a global, since it is accessed by the init function */
8187 emit_alignment (acfg, 8);
8188 emit_label (acfg, symbol);
8190 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8191 emit_pointer (acfg, symbol);
8193 for (i = 0; i < acfg->globals->len; ++i) {
8194 char *name = g_ptr_array_index (acfg->globals, i);
8196 sprintf (symbol, "name_%d", i);
8197 emit_pointer (acfg, symbol);
8199 g_assert (strlen (name) < sizeof (symbol));
8200 sprintf (symbol, "%s", name);
8201 emit_pointer (acfg, symbol);
8203 /* Null terminate the table */
8204 emit_int32 (acfg, 0);
8205 emit_int32 (acfg, 0);
8209 emit_autoreg (MonoAotCompile *acfg)
8214 * Emit a function into the .ctor section which will be called by the ELF
8215 * loader to register this module with the runtime.
8217 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8220 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8222 arch_emit_autoreg (acfg, symbol);
8228 emit_mem_end (MonoAotCompile *acfg)
8232 sprintf (symbol, "mem_end");
8233 emit_section_change (acfg, ".text", 1);
8234 emit_alignment_code (acfg, 8);
8235 emit_label (acfg, symbol);
8239 * Emit a structure containing all the information not stored elsewhere.
8242 emit_file_info (MonoAotCompile *acfg)
8247 const char *gc_name;
8250 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8252 if (acfg->aot_opts.bind_to_runtime_version) {
8253 build_info = mono_get_runtime_build_info ();
8254 emit_string_symbol (acfg, "runtime_version", build_info);
8255 g_free (build_info);
8257 emit_string_symbol (acfg, "runtime_version", "");
8260 /* Emit a string holding the assembly name */
8261 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8264 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8267 gc_name = mono_gc_get_gc_name ();
8268 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8270 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8271 emit_section_change (acfg, ".data", 0);
8272 emit_alignment (acfg, 8);
8273 emit_label (acfg, symbol);
8274 if (!acfg->aot_opts.static_link)
8275 emit_global (acfg, symbol, FALSE);
8277 /* The data emitted here must match MonoAotFileInfo. */
8279 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8280 emit_int32 (acfg, 0);
8283 * We emit pointers to our data structures instead of emitting global symbols which
8284 * point to them, to reduce the number of globals, and because using globals leads to
8285 * various problems (i.e. arm/thumb).
8287 emit_pointer (acfg, acfg->got_symbol);
8289 emit_pointer (acfg, acfg->llvm_got_symbol);
8291 emit_pointer (acfg, NULL);
8292 emit_pointer (acfg, acfg->methods_symbol);
8293 emit_pointer (acfg, "jit_code_start");
8294 emit_pointer (acfg, "jit_code_end");
8297 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8299 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8301 emit_pointer (acfg, NULL);
8303 emit_pointer (acfg, "blob");
8304 emit_pointer (acfg, "class_name_table");
8305 emit_pointer (acfg, "class_info_offsets");
8306 emit_pointer (acfg, "method_info_offsets");
8307 emit_pointer (acfg, "ex_info_offsets");
8308 emit_pointer (acfg, "method_addresses");
8309 emit_pointer (acfg, "extra_method_info_offsets");
8310 emit_pointer (acfg, "extra_method_table");
8311 emit_pointer (acfg, "got_info_offsets");
8313 emit_pointer (acfg, "llvm_got_info_offsets");
8315 emit_pointer (acfg, NULL);
8316 emit_pointer (acfg, "methods_end");
8317 emit_pointer (acfg, "unwind_info");
8318 emit_pointer (acfg, "mem_end");
8319 emit_pointer (acfg, "image_table");
8320 emit_pointer (acfg, "plt");
8321 emit_pointer (acfg, "plt_end");
8322 emit_pointer (acfg, "assembly_guid");
8323 emit_pointer (acfg, "runtime_version");
8324 if (acfg->num_trampoline_got_entries) {
8325 emit_pointer (acfg, "specific_trampolines");
8326 emit_pointer (acfg, "static_rgctx_trampolines");
8327 emit_pointer (acfg, "imt_thunks");
8328 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8330 emit_pointer (acfg, NULL);
8331 emit_pointer (acfg, NULL);
8332 emit_pointer (acfg, NULL);
8333 emit_pointer (acfg, NULL);
8335 if (acfg->thumb_mixed) {
8336 emit_pointer (acfg, "thumb_end");
8338 emit_pointer (acfg, NULL);
8340 if (acfg->aot_opts.static_link) {
8341 emit_pointer (acfg, "globals");
8343 emit_pointer (acfg, NULL);
8345 emit_pointer (acfg, "assembly_name");
8346 emit_pointer (acfg, "unbox_trampolines");
8347 emit_pointer (acfg, "unbox_trampolines_end");
8348 emit_pointer (acfg, "unbox_trampoline_addresses");
8350 emit_int32 (acfg, acfg->plt_got_offset_base);
8351 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8352 emit_int32 (acfg, acfg->plt_offset);
8353 emit_int32 (acfg, acfg->nmethods);
8354 emit_int32 (acfg, acfg->flags);
8355 emit_int32 (acfg, acfg->opts);
8356 emit_int32 (acfg, acfg->simd_opts);
8357 emit_int32 (acfg, gc_name_offset);
8359 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8360 emit_int32 (acfg, acfg->num_trampolines [i]);
8361 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8362 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8363 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8364 emit_int32 (acfg, acfg->trampoline_size [i]);
8365 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8367 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8372 memset (&t, 0, sizeof (MonoType));
8373 t.type = MONO_TYPE_R8;
8374 mono_type_size (&t, &align);
8375 emit_int32 (acfg, align);
8377 memset (&t, 0, sizeof (MonoType));
8378 t.type = MONO_TYPE_I8;
8379 mono_type_size (&t, &align);
8381 emit_int32 (acfg, align);
8384 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8385 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8387 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8388 emit_int32 (acfg, acfg->tramp_page_size);
8389 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8390 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8392 if (acfg->aot_opts.static_link) {
8396 * Emit a global symbol which can be passed by an embedding app to
8397 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8400 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8402 /* Get rid of characters which cannot occur in symbols */
8404 for (p = symbol; *p; ++p) {
8405 if (!(isalnum (*p) || *p == '_'))
8408 acfg->static_linking_symbol = g_strdup (symbol);
8409 emit_global_inner (acfg, symbol, FALSE);
8410 emit_alignment (acfg, sizeof (gpointer));
8411 emit_label (acfg, symbol);
8412 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8417 emit_blob (MonoAotCompile *acfg)
8421 sprintf (symbol, "blob");
8422 emit_section_change (acfg, RODATA_SECT, 1);
8423 emit_alignment (acfg, 8);
8424 emit_label (acfg, symbol);
8426 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8430 emit_objc_selectors (MonoAotCompile *acfg)
8434 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8439 * cat > foo.m << EOF
8442 * return @selector(print:);
8447 img_writer_emit_unset_mode (acfg->w);
8448 g_assert (acfg->fp);
8449 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8450 fprintf (acfg->fp, ".align 3\n");
8451 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8452 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8453 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8455 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8456 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8457 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8458 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8461 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8462 fprintf (acfg->fp, ".align 3\n");
8463 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8464 fprintf (acfg->fp, ".long 0\n");
8465 fprintf (acfg->fp, ".long 16\n");
8469 emit_dwarf_info (MonoAotCompile *acfg)
8471 #ifdef EMIT_DWARF_INFO
8475 /* DIEs for methods */
8476 for (i = 0; i < acfg->nmethods; ++i) {
8477 MonoCompile *cfg = acfg->cfgs [i];
8482 // FIXME: LLVM doesn't define .Lme_...
8483 if (cfg->compile_llvm)
8486 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8488 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8494 collect_methods (MonoAotCompile *acfg)
8497 MonoImage *image = acfg->image;
8499 /* Collect methods */
8500 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8502 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8504 method = mono_get_method (acfg->image, token, NULL);
8507 aot_printerrf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8508 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8512 /* Load all methods eagerly to skip the slower lazy loading code */
8513 mono_class_setup_methods (method->klass);
8515 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8516 /* Compile the wrapper instead */
8517 /* We do this here instead of add_wrappers () because it is easy to do it here */
8518 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8522 /* FIXME: Some mscorlib methods don't have debug info */
8524 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8525 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8526 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8527 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8528 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8529 if (!mono_debug_lookup_method (method)) {
8530 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8537 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8538 add_method_with_index (acfg, method, i, FALSE);
8539 acfg->method_index ++;
8542 /* gsharedvt methods */
8543 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8545 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8547 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8550 method = mono_get_method (acfg->image, token, NULL);
8554 if (strcmp (method->name, "gshared2"))
8558 if (!strstr (method->klass->image->name, "mini"))
8561 if (method->is_generic || method->klass->generic_container) {
8562 MonoMethod *gshared;
8564 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8565 add_extra_method (acfg, gshared);
8569 add_generic_instances (acfg);
8571 if (acfg->aot_opts.full_aot)
8572 add_wrappers (acfg);
8577 compile_methods (MonoAotCompile *acfg)
8581 if (acfg->aot_opts.nthreads > 0) {
8586 gpointer *user_data;
8587 MonoMethod **methods;
8589 methods_len = acfg->methods->len;
8591 len = acfg->methods->len / acfg->aot_opts.nthreads;
8594 * Partition the list of methods into fragments, and hand it to threads to
8597 threads = g_ptr_array_new ();
8598 /* Make a copy since acfg->methods is modified by compile_method () */
8599 methods = g_new0 (MonoMethod*, methods_len);
8600 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8601 for (i = 0; i < methods_len; ++i)
8602 methods [i] = g_ptr_array_index (acfg->methods, i);
8604 while (i < methods_len) {
8605 frag = g_ptr_array_new ();
8606 for (j = 0; j < len; ++j) {
8607 if (i < methods_len) {
8608 g_ptr_array_add (frag, methods [i]);
8613 user_data = g_new0 (gpointer, 3);
8614 user_data [0] = mono_domain_get ();
8615 user_data [1] = acfg;
8616 user_data [2] = frag;
8618 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8619 g_ptr_array_add (threads, handle);
8623 for (i = 0; i < threads->len; ++i) {
8624 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8630 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8631 for (i = methods_len; i < acfg->methods->len; ++i) {
8632 /* This can new methods to acfg->methods */
8633 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8638 compile_asm (MonoAotCompile *acfg)
8640 char *command, *objfile;
8641 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8642 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8644 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8645 #define AS_OPTIONS "--64"
8646 #elif defined(TARGET_POWERPC64)
8647 #define AS_OPTIONS "-a64 -mppc64"
8648 #define LD_OPTIONS "-m elf64ppc"
8649 #elif defined(sparc) && SIZEOF_VOID_P == 8
8650 #define AS_OPTIONS "-xarch=v9"
8651 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8652 #define AS_OPTIONS "-arch i386"
8654 #define AS_OPTIONS ""
8657 #ifdef __native_client_codegen__
8658 #if defined(TARGET_AMD64)
8659 #define AS_NAME "nacl64-as"
8661 #define AS_NAME "nacl-as"
8663 #elif defined(TARGET_OSX)
8664 #define AS_NAME "clang -c -x assembler"
8666 #define AS_NAME "as"
8670 #define LD_OPTIONS ""
8674 #define LD_NAME "ld -shared -G"
8675 #elif defined(__ppc__) && defined(TARGET_MACH)
8676 #define LD_NAME "gcc -dynamiclib"
8677 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8678 #define LD_NAME "clang --shared"
8679 #elif defined(HOST_WIN32)
8680 #define LD_NAME "gcc -shared --dll"
8681 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8682 #define LD_NAME "clang -m32 -dynamiclib"
8685 if (acfg->aot_opts.asm_only) {
8686 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8687 if (acfg->aot_opts.static_link)
8688 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8689 if (acfg->llvm_separate)
8690 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8694 if (acfg->aot_opts.static_link) {
8695 if (acfg->aot_opts.outfile)
8696 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8698 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8700 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8702 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);
8703 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8704 if (system (command) != 0) {
8710 if (acfg->llvm_separate && !acfg->llvm_owriter) {
8711 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
8712 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8713 if (system (command) != 0) {
8722 if (acfg->aot_opts.static_link) {
8723 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8724 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8729 if (acfg->aot_opts.outfile)
8730 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8732 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8734 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8736 if (acfg->llvm_separate) {
8737 llvm_ofile = g_strdup (acfg->llvm_ofile);
8739 llvm_ofile = g_strdup ("");
8743 command = g_strdup_printf ("%s -o %s %s %s.o", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8745 command = g_strdup_printf ("%sld %s -shared -o %s %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8747 aot_printf (acfg, "Executing the native linker: %s\n", command);
8748 if (system (command) != 0) {
8749 g_free (tmp_outfile_name);
8750 g_free (outfile_name);
8758 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8759 printf ("Stripping the binary: %s\n", com);
8763 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8765 * gas generates 'mapping symbols' each time code and data is mixed, which
8766 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8768 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8769 aot_printf (acfg, "Stripping the binary: %s\n", command);
8770 if (system (command) != 0) {
8771 g_free (tmp_outfile_name);
8772 g_free (outfile_name);
8779 rename (tmp_outfile_name, outfile_name);
8781 #if defined(TARGET_MACH)
8782 command = g_strdup_printf ("dsymutil %s", outfile_name);
8783 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8784 if (system (command) != 0) {
8789 if (!acfg->aot_opts.save_temps)
8792 g_free (tmp_outfile_name);
8793 g_free (outfile_name);
8796 if (acfg->aot_opts.save_temps)
8797 aot_printf (acfg, "Retained input file.\n");
8799 unlink (acfg->tmpfname);
8804 static void init_got_info (GotInfo *info)
8808 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8809 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8810 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8811 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8812 info->got_patches = g_ptr_array_new ();
8815 static MonoAotCompile*
8816 acfg_create (MonoAssembly *ass, guint32 opts)
8818 MonoImage *image = ass->image;
8819 MonoAotCompile *acfg;
8821 acfg = g_new0 (MonoAotCompile, 1);
8822 acfg->methods = g_ptr_array_new ();
8823 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8824 acfg->method_depth = g_hash_table_new (NULL, NULL);
8825 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8826 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8827 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8828 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8829 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8830 acfg->image_hash = g_hash_table_new (NULL, NULL);
8831 acfg->image_table = g_ptr_array_new ();
8832 acfg->globals = g_ptr_array_new ();
8833 acfg->image = image;
8835 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8836 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8837 acfg->mempool = mono_mempool_new ();
8838 acfg->extra_methods = g_ptr_array_new ();
8839 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8840 acfg->unwind_ops = g_ptr_array_new ();
8841 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8842 acfg->method_order = g_ptr_array_new ();
8843 acfg->export_names = g_hash_table_new (NULL, NULL);
8844 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8845 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8846 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8847 mono_mutex_init_recursive (&acfg->mutex);
8849 init_got_info (&acfg->got_info);
8850 init_got_info (&acfg->llvm_got_info);
8856 got_info_free (GotInfo *info)
8860 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8861 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8862 g_free (info->patch_to_got_offset_by_type);
8863 g_hash_table_destroy (info->patch_to_got_offset);
8864 g_ptr_array_free (info->got_patches, TRUE);
8868 acfg_free (MonoAotCompile *acfg)
8872 img_writer_destroy (acfg->w);
8873 for (i = 0; i < acfg->nmethods; ++i)
8875 g_free (acfg->cfgs [i]);
8876 g_free (acfg->cfgs);
8877 g_free (acfg->static_linking_symbol);
8878 g_free (acfg->got_symbol);
8879 g_free (acfg->plt_symbol);
8880 g_ptr_array_free (acfg->methods, TRUE);
8881 g_ptr_array_free (acfg->image_table, TRUE);
8882 g_ptr_array_free (acfg->globals, TRUE);
8883 g_ptr_array_free (acfg->unwind_ops, TRUE);
8884 g_hash_table_destroy (acfg->method_indexes);
8885 g_hash_table_destroy (acfg->method_depth);
8886 g_hash_table_destroy (acfg->plt_offset_to_entry);
8887 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8888 if (acfg->patch_to_plt_entry [i])
8889 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8891 g_free (acfg->patch_to_plt_entry);
8892 g_hash_table_destroy (acfg->method_to_cfg);
8893 g_hash_table_destroy (acfg->token_info_hash);
8894 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8895 g_hash_table_destroy (acfg->image_hash);
8896 g_hash_table_destroy (acfg->unwind_info_offsets);
8897 g_hash_table_destroy (acfg->method_label_hash);
8898 g_hash_table_destroy (acfg->export_names);
8899 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8900 g_hash_table_destroy (acfg->klass_blob_hash);
8901 g_hash_table_destroy (acfg->method_blob_hash);
8902 got_info_free (&acfg->got_info);
8903 got_info_free (&acfg->llvm_got_info);
8904 mono_mempool_destroy (acfg->mempool);
8908 #define WRAPPER(e,n) n,
8909 static const char* const
8910 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
8911 #include "mono/metadata/wrapper-types.h"
8915 static G_GNUC_UNUSED const char*
8916 get_wrapper_type_name (int type)
8918 return wrapper_type_names [type];
8924 static void aot_dump (MonoAotCompile *acfg)
8930 json_writer_init (&writer);
8932 json_writer_object_begin(&writer);
8935 json_writer_indent (&writer);
8936 json_writer_object_key(&writer, "methods");
8937 json_writer_array_begin (&writer);
8940 for (i = 0; i < acfg->nmethods; ++i) {
8946 cfg = acfg->cfgs [i];
8950 method = cfg->orig_method;
8952 json_writer_indent (&writer);
8953 json_writer_object_begin(&writer);
8955 json_writer_indent (&writer);
8956 json_writer_object_key(&writer, "name");
8957 json_writer_printf (&writer, "\"%s\",\n", method->name);
8959 json_writer_indent (&writer);
8960 json_writer_object_key(&writer, "signature");
8961 json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
8962 /*signature=*/TRUE));
8964 json_writer_indent (&writer);
8965 json_writer_object_key(&writer, "code_size");
8966 json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
8968 klass = method->klass;
8970 json_writer_indent (&writer);
8971 json_writer_object_key(&writer, "class");
8972 json_writer_printf (&writer, "\"%s\",\n", klass->name);
8974 json_writer_indent (&writer);
8975 json_writer_object_key(&writer, "namespace");
8976 json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
8978 json_writer_indent (&writer);
8979 json_writer_object_key(&writer, "wrapper_type");
8980 json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
8982 json_writer_indent_pop (&writer);
8983 json_writer_indent (&writer);
8984 json_writer_object_end (&writer);
8985 json_writer_printf (&writer, ",\n");
8988 json_writer_indent_pop (&writer);
8989 json_writer_indent (&writer);
8990 json_writer_array_end (&writer);
8991 json_writer_printf (&writer, ",\n");
8995 json_writer_indent_push (&writer);
8996 json_writer_indent (&writer);
8997 json_writer_object_key(&writer, "plt");
8998 json_writer_array_begin (&writer);
9000 for (i = 0; i < acfg->plt_offset; ++i) {
9001 MonoPltEntry *plt_entry = NULL;
9006 * The first plt entry is unused.
9010 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9013 json_writer_indent (&writer);
9014 json_writer_printf (&writer, "{ ");
9015 json_writer_object_key(&writer, "symbol");
9016 json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9019 json_writer_indent_pop (&writer);
9020 json_writer_indent (&writer);
9021 json_writer_array_end (&writer);
9022 json_writer_printf (&writer, ",\n");
9027 json_writer_indent_push (&writer);
9028 json_writer_indent (&writer);
9029 json_writer_object_key(&writer, "got");
9030 json_writer_array_begin (&writer);
9032 json_writer_indent_push (&writer);
9033 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9034 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9036 json_writer_indent (&writer);
9037 json_writer_printf (&writer, "{ ");
9038 json_writer_object_key(&writer, "patch_name");
9039 json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9042 json_writer_indent_pop (&writer);
9043 json_writer_indent (&writer);
9044 json_writer_array_end (&writer);
9045 json_writer_printf (&writer, ",\n");
9048 json_writer_indent_pop (&writer);
9049 json_writer_indent (&writer);
9050 json_writer_object_end (&writer);
9052 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9053 dumpfile = fopen (dumpname, "w+");
9056 fprintf (dumpfile, "%s", writer.text->str);
9059 json_writer_destroy (&writer);
9063 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9065 MonoImage *image = ass->image;
9066 int i, res, all_sizes;
9067 MonoAotCompile *acfg;
9068 char *outfile_name, *tmp_outfile_name, *p;
9069 char llvm_stats_msg [256];
9073 acfg = acfg_create (ass, opts);
9075 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9076 acfg->aot_opts.write_symbols = TRUE;
9077 acfg->aot_opts.ntrampolines = 1024;
9078 acfg->aot_opts.nrgctx_trampolines = 1024;
9079 acfg->aot_opts.nimt_trampolines = 128;
9080 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9081 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9082 acfg->aot_opts.llvm_path = g_strdup ("");
9084 acfg->aot_opts.use_trampolines_page = TRUE;
9087 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9089 if (acfg->aot_opts.logfile) {
9090 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9093 if (acfg->aot_opts.static_link)
9094 acfg->aot_opts.autoreg = TRUE;
9096 //acfg->aot_opts.print_skipped_methods = TRUE;
9098 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9099 if (opts & MONO_OPT_GSHAREDVT) {
9100 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9105 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9107 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9108 if (acfg->aot_opts.full_aot) {
9109 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9114 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9115 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9119 if (acfg->aot_opts.static_link)
9120 acfg->aot_opts.asm_writer = TRUE;
9122 if (acfg->aot_opts.soft_debug) {
9123 MonoDebugOptions *opt = mini_get_debug_options ();
9125 opt->mdb_optimizations = TRUE;
9126 opt->gen_seq_points_debug_data = TRUE;
9128 if (!mono_debug_enabled ()) {
9129 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9132 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9135 if (mono_use_llvm || acfg->aot_opts.llvm) {
9137 acfg->aot_opts.asm_writer = TRUE;
9138 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9140 if (acfg->aot_opts.soft_debug) {
9141 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9147 if (!acfg->aot_opts.asm_only || acfg->aot_opts.llvm_outfile) {
9149 * Emit all LLVM code into a separate assembly/object file and link with it
9152 #if LLVM_API_VERSION >= 3
9153 acfg->llvm_separate = TRUE;
9154 if (!acfg->aot_opts.asm_only)
9155 acfg->llvm_owriter = TRUE;
9158 if (acfg->aot_opts.llvm_outfile && !acfg->llvm_separate) {
9159 aot_printerrf (acfg, "The llvm-outputfile= option is not supported on this platform.\n");
9164 if (acfg->aot_opts.full_aot)
9165 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9167 if (acfg->aot_opts.instances_logfile_path) {
9168 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9169 if (!acfg->instances_logfile) {
9170 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9175 load_profile_files (acfg);
9177 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9178 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9179 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9181 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9182 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9183 if (acfg->opts & MONO_OPT_GSHAREDVT)
9184 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9187 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9191 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9192 /* Get rid of characters which cannot occur in symbols */
9193 for (p = acfg->assembly_name_sym; *p; ++p) {
9194 if (!(isalnum (*p) || *p == '_'))
9198 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9199 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9200 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9202 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9204 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9205 if (acfg->llvm_separate)
9206 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9208 acfg->llvm_eh_frame_symbol = g_strdup ("mono_eh_frame");
9211 acfg->method_index = 1;
9215 if (acfg->aot_opts.full_aot)
9216 mono_set_partial_sharing_supported (TRUE);
9219 res = collect_methods (acfg);
9223 acfg->cfgs_size = acfg->methods->len + 32;
9224 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9226 /* PLT offset 0 is reserved for the PLT trampoline */
9227 acfg->plt_offset = 1;
9232 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, acfg->llvm_separate, acfg->llvm_separate);
9236 /* GOT offset 0 is reserved for the address of the current assembly */
9240 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9241 ji->type = MONO_PATCH_INFO_IMAGE;
9242 ji->data.image = acfg->image;
9244 get_got_offset (acfg, FALSE, ji);
9245 get_got_offset (acfg, TRUE, ji);
9247 /* Slot 1 is reserved for the mscorlib got addr */
9248 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9249 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9250 get_got_offset (acfg, FALSE, ji);
9251 get_got_offset (acfg, TRUE, ji);
9253 /* This is very common */
9254 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9255 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9256 get_got_offset (acfg, FALSE, ji);
9257 get_got_offset (acfg, TRUE, ji);
9259 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9260 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9261 get_got_offset (acfg, FALSE, ji);
9262 get_got_offset (acfg, TRUE, ji);
9267 compile_methods (acfg);
9271 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9279 if (acfg->aot_opts.asm_only) {
9280 if (acfg->aot_opts.outfile) {
9281 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9282 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9284 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9285 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9287 if (acfg->llvm_separate) {
9288 g_assert (acfg->aot_opts.llvm_outfile);
9289 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9292 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9293 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9294 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9295 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9298 res = emit_llvm_file (acfg);
9304 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9305 if (acfg->aot_opts.outfile)
9306 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9308 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9311 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9312 * it might be in another file system so the rename () won't work.
9314 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9316 acfg->fp = fopen (tmp_outfile_name, "w");
9318 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9322 acfg->w = img_writer_create (acfg->fp, TRUE);
9323 acfg->use_bin_writer = TRUE;
9325 if (acfg->llvm && !acfg->llvm_separate) {
9326 /* Append to the .s file created by llvm */
9327 /* FIXME: Use multiple files instead */
9328 acfg->fp = fopen (acfg->tmpfname, "a+");
9330 if (acfg->aot_opts.asm_only) {
9331 if (acfg->aot_opts.outfile)
9332 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9334 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9335 acfg->fp = fopen (acfg->tmpfname, "w+");
9337 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9338 acfg->fp = fdopen (i, "w+");
9341 if (acfg->fp == 0) {
9342 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9345 acfg->w = img_writer_create (acfg->fp, FALSE);
9347 tmp_outfile_name = NULL;
9348 outfile_name = NULL;
9351 /* Compute symbols for methods */
9352 for (i = 0; i < acfg->nmethods; ++i) {
9353 if (acfg->cfgs [i]) {
9354 MonoCompile *cfg = acfg->cfgs [i];
9355 int method_index = get_method_index (acfg, cfg->orig_method);
9357 if (COMPILE_LLVM (cfg))
9358 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9359 else if (acfg->global_symbols || acfg->llvm_separate)
9360 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9362 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9366 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9368 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9369 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9372 //acfg->gas_line_numbers = TRUE;
9375 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9376 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9377 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9380 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9383 img_writer_emit_start (acfg->w);
9386 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9388 if (acfg->thumb_mixed) {
9391 * This global symbol marks the end of THUMB code, and the beginning of ARM
9392 * code generated by our JIT.
9394 sprintf (symbol, "thumb_end");
9395 emit_section_change (acfg, ".text", 0);
9396 emit_alignment_code (acfg, 8);
9397 emit_label (acfg, symbol);
9398 emit_zero_bytes (acfg, 16);
9400 fprintf (acfg->fp, ".arm\n");
9407 emit_extra_methods (acfg);
9409 emit_trampolines (acfg);
9411 emit_class_name_table (acfg);
9413 emit_got_info (acfg, FALSE);
9415 emit_got_info (acfg, TRUE);
9417 emit_exception_info (acfg);
9419 emit_unwind_info (acfg);
9421 emit_class_info (acfg);
9425 emit_image_table (acfg);
9429 emit_file_info (acfg);
9433 emit_objc_selectors (acfg);
9435 emit_globals (acfg);
9437 emit_autoreg (acfg);
9440 emit_dwarf_info (acfg);
9441 mono_dwarf_writer_close (acfg->dwarf);
9444 emit_mem_end (acfg);
9446 if (acfg->need_pt_gnu_stack) {
9447 /* This is required so the .so doesn't have an executable stack */
9448 /* The bin writer already emits this */
9449 if (!acfg->use_bin_writer)
9450 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9455 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9458 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9460 strcpy (llvm_stats_msg, "");
9462 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
9464 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
9465 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9466 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9467 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9468 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9469 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9470 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9471 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9472 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9473 (int)(acfg->got_offset * sizeof (gpointer)));
9474 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9475 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9477 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9478 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9479 if (acfg->stats.genericcount)
9480 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9481 if (acfg->stats.abscount)
9482 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9483 if (acfg->stats.lmfcount)
9484 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9485 if (acfg->stats.ocount)
9486 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9489 res = img_writer_emit_writeout (acfg->w);
9494 if (acfg->use_bin_writer) {
9495 int err = rename (tmp_outfile_name, outfile_name);
9498 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9502 res = compile_asm (acfg);
9509 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9511 if (acfg->aot_opts.stats) {
9514 aot_printf (acfg, "GOT slot distribution:\n");
9515 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9516 if (acfg->stats.got_slot_types [i])
9517 aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9520 aot_printf (acfg, "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);
9522 if (acfg->aot_opts.dump_json)
9535 mono_aot_readonly_field_override (MonoClassField *field)
9541 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)