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>
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
60 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
62 #if defined(__linux__) || defined(__native_client_codegen__)
63 #define RODATA_SECT ".rodata"
64 #elif defined(TARGET_MACH)
65 #define RODATA_SECT ".section __TEXT, __const"
67 #define RODATA_SECT ".text"
70 #define TV_DECLARE(name) gint64 name
71 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
72 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
74 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
75 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
76 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
78 /* predefined values for static readonly fields without needed to run the .cctor */
79 typedef struct _ReadOnlyValue ReadOnlyValue;
80 struct _ReadOnlyValue {
83 int type; /* to be used later for typechecking to prevent user errors */
92 static ReadOnlyValue *readonly_values;
94 typedef struct MonoAotOptions {
98 gboolean write_symbols;
99 gboolean metadata_only;
100 gboolean bind_to_runtime_version;
103 gboolean static_link;
107 gboolean dwarf_debug;
109 gboolean log_generics;
110 gboolean log_instances;
111 gboolean direct_pinvoke;
112 gboolean direct_icalls;
113 gboolean no_direct_calls;
114 gboolean use_trampolines_page;
115 gboolean no_instances;
120 int nrgctx_trampolines;
121 int nimt_trampolines;
122 int ngsharedvt_arg_trampolines;
123 int nrgctx_fetch_trampolines;
124 gboolean print_skipped_methods;
130 char *instances_logfile_path;
135 typedef struct MonoAotStats {
136 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
137 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
138 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
139 int got_slots, offsets_size;
140 int got_slot_types [MONO_PATCH_INFO_NONE];
141 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
142 int jit_time, gen_time, link_time;
145 typedef struct GotInfo {
146 GHashTable *patch_to_got_offset;
147 GHashTable **patch_to_got_offset_by_type;
148 GPtrArray *got_patches;
151 typedef struct MonoAotCompile {
154 GHashTable *method_indexes;
155 GHashTable *method_depth;
158 GHashTable **patch_to_plt_entry;
159 GHashTable *plt_offset_to_entry;
160 //GHashTable *patch_to_got_offset;
161 //GHashTable **patch_to_got_offset_by_type;
162 //GPtrArray *got_patches;
163 GotInfo got_info, llvm_got_info;
164 GHashTable *image_hash;
165 GHashTable *method_to_cfg;
166 GHashTable *token_info_hash;
167 GHashTable *method_to_pinvoke_import;
168 GPtrArray *extra_methods;
169 GPtrArray *image_table;
171 GPtrArray *method_order;
172 GHashTable *export_names;
173 /* Maps MonoClass* -> blob offset */
174 GHashTable *klass_blob_hash;
175 /* Maps MonoMethod* -> blob offset */
176 GHashTable *method_blob_hash;
177 guint32 *plt_got_info_offsets;
178 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
179 /* Number of GOT entries reserved for trampolines */
180 guint32 num_trampoline_got_entries;
181 guint32 tramp_page_size;
183 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
184 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
185 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
186 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
188 MonoAotOptions aot_opts;
192 MonoMemPool *mempool;
195 char *static_linking_symbol;
197 gboolean use_bin_writer;
198 gboolean gas_line_numbers;
199 /* Whenever to emit LLVM code into a separate object file */
200 gboolean llvm_separate;
201 /* Whenever to emit an object file directly from llc */
202 gboolean llvm_owriter;
204 MonoDwarfWriter *dwarf;
211 GHashTable *unwind_info_offsets;
212 GPtrArray *unwind_ops;
213 guint32 unwind_info_offset;
214 char *got_symbol_base;
215 char *llvm_got_symbol_base;
217 char *llvm_got_symbol;
219 char *methods_symbol;
220 char *llvm_eh_frame_symbol;
221 GHashTable *method_label_hash;
222 const char *temp_prefix;
223 const char *user_symbol_prefix;
224 const char *llvm_label_prefix;
225 const char *inst_directive;
227 guint32 label_generator;
229 MonoAotFileFlags flags;
230 MonoDynamicStream blob;
231 MonoClass **typespec_classes;
234 char *assembly_name_sym;
235 GHashTable *plt_entry_debug_sym_cache;
236 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
237 GHashTable *ginst_hash;
238 GHashTable *dwarf_ln_filenames;
239 gboolean global_symbols;
240 int objc_selector_index, objc_selector_index_2;
241 GPtrArray *objc_selectors;
242 GHashTable *objc_selector_to_index;
244 FILE *instances_logfile;
249 char *symbol, *llvm_symbol, *debug_sym;
251 gboolean jit_used, llvm_used;
254 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
255 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
257 /* This points to the current acfg in LLVM mode */
258 static MonoAotCompile *llvm_acfg;
260 #ifdef HAVE_ARRAY_ELEM_INIT
261 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
262 #define MSGSTRFIELD1(line) str##line
263 static const struct msgstr_t {
264 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
265 #include "patch-info.h"
268 #define PATCH_INFO(a,b) b,
269 #include "patch-info.h"
272 static const gint16 opidx [] = {
273 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
274 #include "patch-info.h"
278 static G_GNUC_UNUSED const char*
279 get_patch_name (int info)
281 return (const char*)&opstr + opidx [info];
285 #define PATCH_INFO(a,b) b,
286 static const char* const
287 patch_types [MONO_PATCH_INFO_NUM + 1] = {
288 #include "patch-info.h"
292 static G_GNUC_UNUSED const char*
293 get_patch_name (int info)
295 return patch_types [info];
301 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
304 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
310 output = acfg->logfile;
314 va_start (args, format);
315 vfprintf (output, format, args);
320 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
326 output = acfg->logfile;
330 va_start (args, format);
331 vfprintf (output, format, args);
335 /* Wrappers around the image writer functions */
338 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
340 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
344 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
346 img_writer_emit_push_section (acfg->w, section_name, subsection);
350 emit_pop_section (MonoAotCompile *acfg)
352 img_writer_emit_pop_section (acfg->w);
356 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
358 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
362 emit_label (MonoAotCompile *acfg, const char *name)
364 img_writer_emit_label (acfg->w, name);
368 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
370 img_writer_emit_bytes (acfg->w, buf, size);
374 emit_string (MonoAotCompile *acfg, const char *value)
376 img_writer_emit_string (acfg->w, value);
380 emit_line (MonoAotCompile *acfg)
382 img_writer_emit_line (acfg->w);
386 emit_alignment (MonoAotCompile *acfg, int size)
388 img_writer_emit_alignment (acfg->w, size);
392 emit_alignment_code (MonoAotCompile *acfg, int size)
394 if (acfg->align_pad_value)
395 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
397 img_writer_emit_alignment (acfg->w, size);
401 emit_padding (MonoAotCompile *acfg, int size)
406 if (acfg->align_pad_value) {
407 for (i = 0; i < 16; ++i)
408 buf [i] = acfg->align_pad_value;
410 memset (buf, 0, sizeof (buf));
413 for (i = 0; i < size; i += 16) {
415 emit_bytes (acfg, buf, size - i);
417 emit_bytes (acfg, buf, 16);
422 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
424 img_writer_emit_pointer_unaligned (acfg->w, target);
428 emit_pointer (MonoAotCompile *acfg, const char *target)
430 img_writer_emit_pointer (acfg->w, target);
434 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
436 if (prefix [0] != '\0') {
437 char *s = g_strdup_printf ("%s%s", prefix, target);
438 img_writer_emit_pointer (acfg->w, s);
441 img_writer_emit_pointer (acfg->w, target);
446 emit_int16 (MonoAotCompile *acfg, int value)
448 img_writer_emit_int16 (acfg->w, value);
452 emit_int32 (MonoAotCompile *acfg, int value)
454 img_writer_emit_int32 (acfg->w, value);
458 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
460 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
464 emit_zero_bytes (MonoAotCompile *acfg, int num)
466 img_writer_emit_zero_bytes (acfg->w, num);
470 emit_byte (MonoAotCompile *acfg, guint8 val)
472 img_writer_emit_byte (acfg->w, val);
475 #ifdef __native_client_codegen__
477 emit_nacl_call_alignment (MonoAotCompile *acfg)
479 img_writer_emit_nacl_call_alignment (acfg->w);
483 static G_GNUC_UNUSED void
484 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
486 img_writer_emit_global (acfg->w, name, func);
490 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
492 if (acfg->aot_opts.no_dlsym) {
493 g_ptr_array_add (acfg->globals, g_strdup (name));
494 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
496 img_writer_emit_global (acfg->w, name, func);
501 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
503 img_writer_emit_symbol_size (acfg->w, name, end_label);
507 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
509 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
511 /* On apple, all symbols need to be aligned to avoid warnings from ld */
512 emit_alignment (acfg, 4);
514 img_writer_emit_label (acfg->w, name);
515 img_writer_emit_string (acfg->w, value);
518 static G_GNUC_UNUSED void
519 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
522 guint8 b = value & 0x7f;
524 if (value != 0) /* more bytes to come */
530 static G_GNUC_UNUSED void
531 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
534 gboolean negative = (value < 0);
541 /* the following is unnecessary if the
542 * implementation of >>= uses an arithmetic rather
543 * than logical shift for a signed left operand
547 value |= - ((gint64)1 <<(size - 7));
548 /* sign bit of byte is second high order bit (0x40) */
549 if ((value == 0 && !(byte & 0x40)) ||
550 (value == -1 && (byte & 0x40)))
554 emit_byte (acfg, byte);
558 static G_GNUC_UNUSED void
559 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
564 guint8 b = value & 0x7f;
566 if (value != 0) /* more bytes to come */
574 static G_GNUC_UNUSED void
575 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
578 gboolean negative = (value < 0);
586 /* the following is unnecessary if the
587 * implementation of >>= uses an arithmetic rather
588 * than logical shift for a signed left operand
592 value |= - (1 <<(size - 7));
593 /* sign bit of byte is second high order bit (0x40) */
594 if ((value == 0 && !(byte & 0x40)) ||
595 (value == -1 && (byte & 0x40)))
606 emit_unset_mode (MonoAotCompile *acfg)
608 img_writer_emit_unset_mode (acfg->w);
611 static G_GNUC_UNUSED void
612 emit_set_thumb_mode (MonoAotCompile *acfg)
614 emit_unset_mode (acfg);
615 fprintf (acfg->fp, ".code 16\n");
618 static G_GNUC_UNUSED void
619 emit_set_arm_mode (MonoAotCompile *acfg)
621 emit_unset_mode (acfg);
622 fprintf (acfg->fp, ".code 32\n");
626 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
631 g_assert (size % 4 == 0);
632 emit_unset_mode (acfg);
633 for (i = 0; i < size; i += 4)
634 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
636 emit_bytes (acfg, buf, size);
640 /* ARCHITECTURE SPECIFIC CODE */
642 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
643 #define EMIT_DWARF_INFO 1
646 #if defined(TARGET_ARM)
647 #define AOT_FUNC_ALIGNMENT 4
649 #define AOT_FUNC_ALIGNMENT 16
651 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
652 #undef AOT_FUNC_ALIGNMENT
653 #define AOT_FUNC_ALIGNMENT 32
656 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
657 #define PPC_LD_OP "ld"
658 #define PPC_LDX_OP "ldx"
660 #define PPC_LD_OP "lwz"
661 #define PPC_LDX_OP "lwzx"
665 #define AOT_TARGET_STR "AMD64"
670 #define AOT_TARGET_STR "ARM (MACH)"
672 #define AOT_TARGET_STR "ARM (!MACH)"
678 #define AOT_TARGET_STR "ARM64 (MACH)"
680 #define AOT_TARGET_STR "ARM64 (!MACH)"
684 #ifdef TARGET_POWERPC64
685 #ifdef __mono_ilp32__
686 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
688 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
691 #ifdef TARGET_POWERPC
692 #ifdef __mono_ilp32__
693 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
695 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
702 #define AOT_TARGET_STR "X86 (WIN32)"
703 #elif defined(__native_client_codegen__)
704 #define AOT_TARGET_STR "X86 (native client codegen)"
706 #define AOT_TARGET_STR "X86 (!native client codegen)"
710 #ifndef AOT_TARGET_STR
711 #define AOT_TARGET_STR ""
715 arch_init (MonoAotCompile *acfg)
717 acfg->llc_args = g_string_new ("");
718 acfg->as_args = g_string_new ("");
721 * The prefix LLVM likes to put in front of symbol names on darwin.
722 * The mach-os specs require this for globals, but LLVM puts them in front of all
723 * symbols. We need to handle this, since we need to refer to LLVM generated
726 acfg->llvm_label_prefix = "";
727 acfg->user_symbol_prefix = "";
729 #if defined(TARGET_X86)
730 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
733 #if defined(TARGET_AMD64)
734 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
736 acfg->align_pad_value = 0x90;
740 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
741 g_string_append (acfg->llc_args, "-mattr=+v6");
744 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
745 g_string_append (acfg->as_args, " -mfpu=vfp3");
747 g_string_append (acfg->llc_args, " -soft-float");
750 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
751 acfg->thumb_mixed = TRUE;
753 if (acfg->aot_opts.mtriple)
754 mono_arch_set_target (acfg->aot_opts.mtriple);
758 acfg->inst_directive = ".inst";
759 if (acfg->aot_opts.mtriple)
760 mono_arch_set_target (acfg->aot_opts.mtriple);
764 acfg->user_symbol_prefix = "_";
765 acfg->llvm_label_prefix = "_";
766 acfg->inst_directive = ".word";
767 acfg->need_no_dead_strip = TRUE;
768 acfg->aot_opts.gnu_asm = TRUE;
771 #if defined(__linux__) && !defined(TARGET_ARM)
772 acfg->need_pt_gnu_stack = TRUE;
776 acfg->global_symbols = TRUE;
782 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
786 #ifdef MONO_ARCH_AOT_SUPPORTED
788 * arch_emit_direct_call:
790 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
794 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
796 #if defined(TARGET_X86) || defined(TARGET_AMD64)
797 /* Need to make sure this is exactly 5 bytes long */
798 if (!acfg->use_bin_writer) {
799 emit_unset_mode (acfg);
800 fprintf (acfg->fp, "call %s\n", target);
802 emit_byte (acfg, '\xe8');
803 emit_symbol_diff (acfg, target, ".", -4);
806 #elif defined(TARGET_ARM)
807 if (acfg->use_bin_writer) {
814 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
815 emit_bytes (acfg, buf, 4);
817 emit_unset_mode (acfg);
819 fprintf (acfg->fp, "blx %s\n", target);
821 fprintf (acfg->fp, "bl %s\n", target);
824 #elif defined(TARGET_ARM64)
825 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
826 #elif defined(TARGET_POWERPC)
827 if (acfg->use_bin_writer) {
828 g_assert_not_reached ();
830 emit_unset_mode (acfg);
831 fprintf (acfg->fp, "bl %s\n", target);
835 g_assert_not_reached ();
842 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
844 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
845 * in in the 2. slot of every GOT, and require every method to place the GOT
846 * address in r30, even when it doesn't access the GOT otherwise. This way,
847 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
852 * PPC64 uses function descriptors which greatly complicate all code, since
853 * these are used very inconsistently in the runtime. Some functions like
854 * mono_compile_method () return ftn descriptors, while others like the
855 * trampoline creation functions do not.
856 * We assume that all GOT slots contain function descriptors, and create
857 * descriptors in aot-runtime.c when needed.
858 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
859 * from function descriptors, we could do the same, but it would require
860 * rewriting all the ppc/aot code to handle function descriptors properly.
861 * So instead, we use the same approach as on PPC32.
862 * This is a horrible mess, but fixing it would probably lead to an even bigger
868 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
871 #ifdef MONO_ARCH_AOT_SUPPORTED
873 * arch_emit_got_offset:
875 * The memory pointed to by CODE should hold native code for computing the GOT
876 * address. Emit this code while patching it with the offset between code and
877 * the GOT. CODE_SIZE is set to the number of bytes emitted.
880 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
882 #if defined(TARGET_POWERPC64)
883 g_assert (!acfg->use_bin_writer);
884 emit_unset_mode (acfg);
886 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
887 * unsupported relocations. So we store the got address into the .Lgot_addr
888 * symbol which is in the text segment, compute its address, and load it.
890 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
891 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
892 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
893 fprintf (acfg->fp, "add 30, 30, 0\n");
894 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
895 acfg->label_generator ++;
897 #elif defined(TARGET_POWERPC)
898 g_assert (!acfg->use_bin_writer);
899 emit_unset_mode (acfg);
900 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
901 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
902 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
903 acfg->label_generator ++;
906 guint32 offset = mono_arch_get_patch_offset (code);
907 emit_bytes (acfg, code, offset);
908 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
910 *code_size = offset + 4;
915 * arch_emit_got_access:
917 * The memory pointed to by CODE should hold native code for loading a GOT
918 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
919 * CODE_SIZE is set to the number of bytes emitted.
922 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
924 /* This needs to emit the same code as OP_AOTCONST */
927 /* mov reg, got+offset(%rip) */
928 if (acfg->llvm_separate) {
929 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
933 /* Decode reg, see amd64_mov_reg_membase () */
934 rex_r = code [0] & AMD64_REX_R;
935 g_assert (code [0] == 0x49 + rex_r);
936 g_assert (code [1] == 0x8b);
937 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
939 emit_unset_mode (acfg);
940 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
943 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
944 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
945 *code_size = mono_arch_get_patch_offset (code) + 4;
947 #elif defined(TARGET_X86)
948 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
949 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
950 *code_size = mono_arch_get_patch_offset (code) + 4;
951 #elif defined(TARGET_ARM)
952 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
953 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
954 *code_size = mono_arch_get_patch_offset (code) + 4;
955 #elif defined(TARGET_ARM64)
956 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
957 arm64_emit_got_access (acfg, code, got_slot, code_size);
958 #elif defined(TARGET_POWERPC)
963 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
965 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
966 g_assert (code - buf == 8);
967 emit_bytes (acfg, buf, code - buf);
968 *code_size = code - buf;
971 g_assert_not_reached ();
977 #ifdef MONO_ARCH_AOT_SUPPORTED
979 * arch_emit_objc_selector_ref:
981 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
984 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
986 #if defined(TARGET_ARM)
989 int lindex = acfg->objc_selector_index_2 ++;
992 emit_bytes (acfg, code, 8);
994 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
995 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
997 emit_label (acfg, symbol1);
998 img_writer_emit_unset_mode (acfg->w);
999 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1002 #elif defined(TARGET_ARM64)
1003 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1005 g_assert_not_reached ();
1011 * arch_emit_plt_entry:
1013 * Emit code for the PLT entry with index INDEX.
1016 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
1018 #if defined(TARGET_X86)
1019 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1020 #if defined(__default_codegen__)
1021 /* jmp *<offset>(%ebx) */
1022 emit_byte (acfg, 0xff);
1023 emit_byte (acfg, 0xa3);
1024 emit_int32 (acfg, offset);
1025 /* Used by mono_aot_get_plt_info_offset */
1026 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1027 #elif defined(__native_client_codegen__)
1028 const guint8 kSizeOfNaClJmp = 11;
1029 guint8 bytes[kSizeOfNaClJmp];
1030 guint8 *pbytes = &bytes[0];
1032 x86_jump_membase32 (pbytes, X86_EBX, offset);
1033 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1034 /* four bytes of data, used by mono_arch_patch_plt_entry */
1035 /* For Native Client, make this work with data embedded in push. */
1036 emit_byte (acfg, 0x68); /* hide data in a push */
1037 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1038 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1039 #endif /*__native_client_codegen__*/
1040 #elif defined(TARGET_AMD64)
1041 #if defined(__default_codegen__)
1042 if (acfg->use_bin_writer) {
1043 emit_byte (acfg, '\xff');
1044 emit_byte (acfg, '\x25');
1045 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1047 emit_unset_mode (acfg);
1048 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
1050 /* Used by mono_aot_get_plt_info_offset */
1051 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1052 acfg->stats.plt_size += 10;
1053 #elif defined(__native_client_codegen__)
1055 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1056 guint8 *code = buf_aligned;
1058 /* mov <OFFSET>(%rip), %r11d */
1059 emit_byte (acfg, '\x45');
1060 emit_byte (acfg, '\x8b');
1061 emit_byte (acfg, '\x1d');
1062 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1064 amd64_jump_reg (code, AMD64_R11);
1065 /* This should be constant for the plt patch */
1066 g_assert ((size_t)(code-buf_aligned) == 10);
1067 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1069 /* Hide data in a push imm32 so it passes validation */
1070 emit_byte (acfg, 0x68); /* push */
1071 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1072 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1073 #endif /*__native_client_codegen__*/
1074 #elif defined(TARGET_ARM)
1079 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1080 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1081 emit_bytes (acfg, buf, code - buf);
1082 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1083 /* Used by mono_aot_get_plt_info_offset */
1084 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1085 #elif defined(TARGET_ARM64)
1086 arm64_emit_plt_entry (acfg, index);
1087 #elif defined(TARGET_POWERPC)
1088 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1090 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1091 g_assert (!acfg->use_bin_writer);
1092 emit_unset_mode (acfg);
1093 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1094 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1095 fprintf (acfg->fp, "add 11, 11, 30\n");
1096 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1097 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1098 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1099 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1101 fprintf (acfg->fp, "mtctr 11\n");
1102 fprintf (acfg->fp, "bctr\n");
1103 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1105 g_assert_not_reached ();
1110 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1112 #if defined(TARGET_ARM)
1114 /* LLVM calls the PLT entries using bl, so emit a stub */
1115 /* FIXME: Too much overhead on every call */
1116 fprintf (acfg->fp, ".thumb_func\n");
1117 fprintf (acfg->fp, "bx pc\n");
1118 fprintf (acfg->fp, "nop\n");
1119 fprintf (acfg->fp, ".arm\n");
1121 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1122 /* The caller already transitioned to thumb */
1123 /* The code below should be 12 bytes long */
1124 /* clang has trouble encoding these instructions, so emit the binary */
1126 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1127 /* thumb can't encode ld pc, [pc, ip] */
1128 fprintf (acfg->fp, "add ip, pc, ip\n");
1129 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1130 fprintf (acfg->fp, "bx ip\n");
1132 emit_set_thumb_mode (acfg);
1133 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1134 fprintf (acfg->fp, ".2byte 0x44fc\n");
1135 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1136 fprintf (acfg->fp, ".2byte 0x4760\n");
1137 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1138 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1139 emit_unset_mode (acfg);
1140 emit_set_arm_mode (acfg);
1142 g_assert_not_reached ();
1147 * arch_emit_specific_trampoline_pages:
1149 * Emits a page full of trampolines: each trampoline uses its own address to
1150 * lookup both the generic trampoline code and the data argument.
1151 * This page can be remapped in process multiple times so we can get an
1152 * unlimited number of trampolines.
1153 * Specifically this implementation uses the following trick: two memory pages
1154 * are allocated, with the first containing the data and the second containing the trampolines.
1155 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1156 * implementation does all the lifting.
1157 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1158 * on the arm 32 bit system.
1161 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1163 #if defined(TARGET_ARM)
1166 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1168 #define COMMON_TRAMP_SIZE 16
1169 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1170 int imm8, rot_amount;
1173 if (!acfg->aot_opts.use_trampolines_page)
1176 acfg->tramp_page_size = mono_pagesize ();
1178 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1179 emit_alignment (acfg, mono_pagesize ());
1180 emit_global (acfg, symbol, TRUE);
1181 emit_label (acfg, symbol);
1183 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1185 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1186 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1187 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1188 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1190 g_assert (code - buf == COMMON_TRAMP_SIZE);
1193 emit_bytes (acfg, buf, code - buf);
1195 for (i = 0; i < count; ++i) {
1197 ARM_PUSH (code, 0x5fff);
1199 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1200 g_assert (code - buf == 8);
1201 emit_bytes (acfg, buf, code - buf);
1204 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1205 * the instruction pointer address, so the generic trampoline at the start of the page
1206 * subtracts 4096 to get to the data page and loads the values
1207 * We again fit the generic trampiline in 16 bytes.
1209 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1210 emit_global (acfg, symbol, TRUE);
1211 emit_label (acfg, symbol);
1213 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1214 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1215 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1216 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1218 g_assert (code - buf == COMMON_TRAMP_SIZE);
1221 emit_bytes (acfg, buf, code - buf);
1223 for (i = 0; i < count; ++i) {
1225 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1227 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1228 g_assert (code - buf == 8);
1229 emit_bytes (acfg, buf, code - buf);
1233 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1235 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1236 emit_global (acfg, symbol, TRUE);
1237 emit_label (acfg, symbol);
1239 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1240 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1241 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1242 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1243 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1244 g_assert (code - buf == COMMON_TRAMP_SIZE);
1246 emit_bytes (acfg, buf, code - buf);
1248 for (i = 0; i < count; ++i) {
1250 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1252 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1253 g_assert (code - buf == 8);
1254 emit_bytes (acfg, buf, code - buf);
1257 /* now the imt trampolines: each specific trampolines puts in the ip register
1258 * the instruction pointer address, so the generic trampoline at the start of the page
1259 * subtracts 4096 to get to the data page and loads the values
1260 * We again fit the generic trampiline in 16 bytes.
1262 #define IMT_TRAMP_SIZE 72
1263 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1264 emit_global (acfg, symbol, TRUE);
1265 emit_label (acfg, symbol);
1267 /* Need at least two free registers, plus a slot for storing the pc */
1268 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1270 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1271 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1272 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1274 /* The IMT method is in v5, r0 has the imt array address */
1277 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1278 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1279 imt_found_check = code;
1280 ARM_B_COND (code, ARMCOND_EQ, 0);
1282 /* End-of-loop check */
1283 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1284 loop_end_check = code;
1285 ARM_B_COND (code, ARMCOND_EQ, 0);
1288 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1289 loop_branch_back = code;
1291 arm_patch (loop_branch_back, loop_start);
1294 arm_patch (imt_found_check, code);
1295 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1296 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1297 /* Save it to the third stack slot */
1298 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1299 /* Restore the registers and branch */
1300 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1303 arm_patch (loop_end_check, code);
1304 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1305 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1306 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1310 g_assert (code - buf == IMT_TRAMP_SIZE);
1311 emit_bytes (acfg, buf, code - buf);
1313 for (i = 0; i < count; ++i) {
1315 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1317 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1318 g_assert (code - buf == 8);
1319 emit_bytes (acfg, buf, code - buf);
1322 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1323 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1326 #elif defined(TARGET_ARM64)
1327 arm64_emit_specific_trampoline_pages (acfg);
1332 * arch_emit_specific_trampoline:
1334 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1335 * two GOT slots which contain the generic trampoline address and the trampoline
1336 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1339 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1342 * The trampolines created here are variations of the specific
1343 * trampolines created in mono_arch_create_specific_trampoline (). The
1345 * - the generic trampoline address is taken from a got slot.
1346 * - the offset of the got slot where the trampoline argument is stored
1347 * is embedded in the instruction stream, and the generic trampoline
1348 * can load the argument by loading the offset, adding it to the
1349 * address of the trampoline to get the address of the got slot, and
1350 * loading the argument from there.
1351 * - all the trampolines should be of the same length.
1353 #if defined(TARGET_AMD64)
1354 #if defined(__default_codegen__)
1355 /* This should be exactly 8 bytes long */
1357 /* call *<offset>(%rip) */
1358 if (acfg->llvm_separate) {
1359 emit_unset_mode (acfg);
1360 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1361 emit_zero_bytes (acfg, 2);
1363 emit_byte (acfg, '\x41');
1364 emit_byte (acfg, '\xff');
1365 emit_byte (acfg, '\x15');
1366 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1367 emit_zero_bytes (acfg, 1);
1369 #elif defined(__native_client_codegen__)
1371 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1372 guint8 *code = buf_aligned;
1377 /* Emit this call in 'code' so we can find out how long it is. */
1378 amd64_call_reg (code, AMD64_R11);
1379 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1380 call_len = code - call_start;
1382 /* The tramp_size is twice the NaCl alignment because it starts with */
1383 /* a call which needs to be aligned to the end of the boundary. */
1384 *tramp_size = kNaClAlignment*2;
1386 /* Emit nops to align call site below which is 7 bytes plus */
1387 /* the length of the call sequence emitted above. */
1388 /* Note: this requires the specific trampoline starts on a */
1389 /* kNaclAlignedment aligned address, which it does because */
1390 /* it's its own function that is aligned. */
1391 guint8 nop_buf[256];
1392 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1393 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1394 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1396 /* The trampoline is stored at the offset'th pointer, the -4 is */
1397 /* present because RIP relative addressing starts at the end of */
1398 /* the current instruction, while the label "." is relative to */
1399 /* the beginning of the current asm location, which in this case */
1400 /* is not the mov instruction, but the offset itself, due to the */
1401 /* way the bytes and ints are emitted here. */
1402 got_offset = (offset * sizeof(gpointer)) - 4;
1404 /* mov <OFFSET>(%rip), %r11d */
1405 emit_byte (acfg, '\x45');
1406 emit_byte (acfg, '\x8b');
1407 emit_byte (acfg, '\x1d');
1408 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1411 emit_bytes (acfg, call_start, call_len);
1413 /* The arg is stored at the offset+1 pointer, relative to beginning */
1414 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1415 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1417 /* We can't emit this data directly, hide in a "push imm32" */
1418 emit_byte (acfg, '\x68'); /* push */
1419 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1420 emit_alignment (acfg, kNaClAlignment);
1421 #endif /*__native_client_codegen__*/
1422 #elif defined(TARGET_ARM)
1426 /* This should be exactly 20 bytes long */
1429 ARM_PUSH (code, 0x5fff);
1430 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1431 /* Load the value from the GOT */
1432 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1434 ARM_BLX_REG (code, ARMREG_R1);
1436 g_assert (code - buf == 16);
1439 emit_bytes (acfg, buf, code - buf);
1441 * Only one offset is needed, since the second one would be equal to the
1444 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1445 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1446 #elif defined(TARGET_ARM64)
1447 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1448 #elif defined(TARGET_POWERPC)
1455 g_assert (!acfg->use_bin_writer);
1458 * PPC has no ip relative addressing, so we need to compute the address
1459 * of the mscorlib got. That is slow and complex, so instead, we store it
1460 * in the second got slot of every aot image. The caller already computed
1461 * the address of its got and placed it into r30.
1463 emit_unset_mode (acfg);
1464 /* Load mscorlib got address */
1465 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1466 /* Load generic trampoline address */
1467 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1468 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1469 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1470 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1471 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1473 fprintf (acfg->fp, "mtctr 11\n");
1474 /* Load trampoline argument */
1475 /* On ppc, we pass it normally to the generic trampoline */
1476 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1477 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1478 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1479 /* Branch to generic trampoline */
1480 fprintf (acfg->fp, "bctr\n");
1482 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1483 *tramp_size = 10 * 4;
1485 *tramp_size = 9 * 4;
1487 #elif defined(TARGET_X86)
1491 /* Similar to the PPC code above */
1493 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1495 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1496 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1497 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1498 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1499 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1504 /* Load mscorlib got address */
1505 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1506 /* Push trampoline argument */
1507 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1508 /* Load generic trampoline address */
1509 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1510 /* Branch to generic trampoline */
1511 x86_jump_reg (code, X86_ECX);
1513 #ifdef __native_client_codegen__
1515 /* emit nops to next 32 byte alignment */
1516 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1517 while (code < (buf + a)) x86_nop(code);
1520 emit_bytes (acfg, buf, code - buf);
1522 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1523 g_assert (code - buf == *tramp_size);
1525 g_assert_not_reached ();
1530 * arch_emit_unbox_trampoline:
1532 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1533 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1536 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1538 #if defined(TARGET_AMD64)
1543 this_reg = mono_arch_get_this_arg_reg (NULL);
1545 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1547 emit_bytes (acfg, buf, code - buf);
1549 if (acfg->llvm_separate) {
1550 emit_unset_mode (acfg);
1551 fprintf (acfg->fp, "jmp %s\n", call_target);
1553 emit_byte (acfg, '\xe9');
1554 emit_symbol_diff (acfg, call_target, ".", -4);
1556 #elif defined(TARGET_X86)
1563 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1565 emit_bytes (acfg, buf, code - buf);
1568 emit_byte (acfg, '\xe9');
1569 emit_symbol_diff (acfg, call_target, ".", -4);
1570 #elif defined(TARGET_ARM)
1574 if (acfg->thumb_mixed && cfg->compile_llvm) {
1575 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1576 fprintf (acfg->fp, "b %s\n", call_target);
1577 fprintf (acfg->fp, ".arm\n");
1578 fprintf (acfg->fp, ".align 2\n");
1584 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1586 emit_bytes (acfg, buf, code - buf);
1587 /* jump to method */
1588 if (acfg->use_bin_writer) {
1595 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1596 emit_bytes (acfg, buf, 4);
1598 if (acfg->thumb_mixed && cfg->compile_llvm)
1599 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1601 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1603 #elif defined(TARGET_ARM64)
1604 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1605 #elif defined(TARGET_POWERPC)
1608 g_assert (!acfg->use_bin_writer);
1610 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1611 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1613 g_assert_not_reached ();
1618 * arch_emit_static_rgctx_trampoline:
1620 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1621 * two GOT slots which contain the rgctx argument, and the method to jump to.
1622 * TRAMP_SIZE is set to the size of the emitted trampoline.
1623 * These kinds of trampolines cannot be enumerated statically, since there could
1624 * be one trampoline per method instantiation, so we emit the same code for all
1625 * trampolines, and parameterize them using two GOT slots.
1628 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1630 #if defined(TARGET_AMD64)
1631 #if defined(__default_codegen__)
1632 /* This should be exactly 13 bytes long */
1635 if (acfg->llvm_separate) {
1636 emit_unset_mode (acfg);
1637 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1638 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1640 /* mov <OFFSET>(%rip), %r10 */
1641 emit_byte (acfg, '\x4d');
1642 emit_byte (acfg, '\x8b');
1643 emit_byte (acfg, '\x15');
1644 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1646 /* jmp *<offset>(%rip) */
1647 emit_byte (acfg, '\xff');
1648 emit_byte (acfg, '\x25');
1649 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1651 #elif defined(__native_client_codegen__)
1653 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1654 guint8 *code = buf_aligned;
1656 /* mov <OFFSET>(%rip), %r10d */
1657 emit_byte (acfg, '\x45');
1658 emit_byte (acfg, '\x8b');
1659 emit_byte (acfg, '\x15');
1660 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1662 /* mov <OFFSET>(%rip), %r11d */
1663 emit_byte (acfg, '\x45');
1664 emit_byte (acfg, '\x8b');
1665 emit_byte (acfg, '\x1d');
1666 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1669 amd64_jump_reg (code, AMD64_R11);
1670 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1672 emit_alignment (acfg, kNaClAlignment);
1673 *tramp_size = kNaClAlignment;
1674 #endif /*__native_client_codegen__*/
1676 #elif defined(TARGET_ARM)
1680 /* This should be exactly 24 bytes long */
1683 /* Load rgctx value */
1684 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1685 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1686 /* Load branch addr + branch */
1687 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1688 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1690 g_assert (code - buf == 16);
1693 emit_bytes (acfg, buf, code - buf);
1694 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1695 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1696 #elif defined(TARGET_ARM64)
1697 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1698 #elif defined(TARGET_POWERPC)
1705 g_assert (!acfg->use_bin_writer);
1708 * PPC has no ip relative addressing, so we need to compute the address
1709 * of the mscorlib got. That is slow and complex, so instead, we store it
1710 * in the second got slot of every aot image. The caller already computed
1711 * the address of its got and placed it into r30.
1713 emit_unset_mode (acfg);
1714 /* Load mscorlib got address */
1715 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1717 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1718 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1719 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1720 /* Load target address */
1721 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1722 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1723 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1724 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1725 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1726 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1728 fprintf (acfg->fp, "mtctr 11\n");
1729 /* Branch to the target address */
1730 fprintf (acfg->fp, "bctr\n");
1732 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1733 *tramp_size = 11 * 4;
1735 *tramp_size = 9 * 4;
1738 #elif defined(TARGET_X86)
1742 /* Similar to the PPC code above */
1744 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1747 /* Load mscorlib got address */
1748 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1750 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1751 /* Branch to the target address */
1752 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1754 #ifdef __native_client_codegen__
1756 /* emit nops to next 32 byte alignment */
1757 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1758 while (code < (buf + a)) x86_nop(code);
1762 emit_bytes (acfg, buf, code - buf);
1764 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1765 g_assert (code - buf == *tramp_size);
1767 g_assert_not_reached ();
1772 * arch_emit_imt_thunk:
1774 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1775 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1776 * key is the IMT key, and ptr holds the address of a memory location holding
1777 * the address to branch to if the IMT arg matches the key. The array is
1778 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1780 * TRAMP_SIZE is set to the size of the emitted trampoline.
1783 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1785 #if defined(TARGET_AMD64)
1787 #if defined(__native_client_codegen__)
1790 guint8 *labels [16];
1792 guint8 *mov_buf_ptr = mov_buf;
1794 const int kSizeOfMove = 7;
1795 #if defined(__default_codegen__)
1796 code = buf = g_malloc (256);
1797 #elif defined(__native_client_codegen__)
1798 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1799 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1800 /* The RIP relative move below is emitted first */
1805 /* FIXME: Optimize this, i.e. use binary search etc. */
1806 /* Maybe move the body into a separate function (slower, but much smaller) */
1808 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1810 if (acfg->llvm_separate) {
1811 emit_unset_mode (acfg);
1812 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1816 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1818 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1821 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1823 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1826 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1827 amd64_jump_code (code, labels [0]);
1830 mono_amd64_patch (labels [2], code);
1831 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1832 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1835 mono_amd64_patch (labels [1], code);
1836 /* Load fail tramp */
1837 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1838 /* Check if there is a fail tramp */
1839 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1841 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1842 /* Jump to fail tramp */
1843 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1846 mono_amd64_patch (labels [3], code);
1847 x86_breakpoint (code);
1849 if (!acfg->llvm_separate) {
1850 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1851 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1852 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1853 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1854 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1855 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1857 emit_bytes (acfg, buf, code - buf);
1859 *tramp_size = code - buf + kSizeOfMove;
1860 #if defined(__native_client_codegen__)
1861 /* The tramp will be padded to the next kNaClAlignment bundle. */
1862 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1865 #if defined(__default_codegen__)
1867 #elif defined(__native_client_codegen__)
1871 #elif defined(TARGET_X86)
1873 #ifdef __native_client_codegen__
1876 guint8 *labels [16];
1878 #if defined(__default_codegen__)
1879 code = buf = g_malloc (256);
1880 #elif defined(__native_client_codegen__)
1881 buf_alloc = g_malloc (256 + kNaClAlignment);
1882 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1885 /* Allocate a temporary stack slot */
1886 x86_push_reg (code, X86_EAX);
1888 x86_push_reg (code, X86_EAX);
1890 /* Load mscorlib got address */
1891 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1893 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1896 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1898 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1901 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1903 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1906 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1907 x86_jump_code (code, labels [0]);
1910 mono_x86_patch (labels [2], code);
1911 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1912 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1913 /* Save the target address to the temporary stack location */
1914 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1916 x86_pop_reg (code, X86_EAX);
1917 /* Jump to the target address */
1921 mono_x86_patch (labels [1], code);
1922 /* Load fail tramp */
1923 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1924 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1926 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1927 /* Jump to fail tramp */
1928 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1929 x86_pop_reg (code, X86_EAX);
1933 mono_x86_patch (labels [3], code);
1934 x86_breakpoint (code);
1936 #ifdef __native_client_codegen__
1938 /* emit nops to next 32 byte alignment */
1939 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1940 while (code < (buf + a)) x86_nop(code);
1943 emit_bytes (acfg, buf, code - buf);
1945 *tramp_size = code - buf;
1947 #if defined(__default_codegen__)
1949 #elif defined(__native_client_codegen__)
1953 #elif defined(TARGET_ARM)
1955 guint8 *code, *code2, *labels [16];
1959 /* The IMT method is in v5 */
1961 /* Need at least two free registers, plus a slot for storing the pc */
1962 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1964 /* Load the parameter from the GOT */
1965 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1966 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1969 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1970 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1972 ARM_B_COND (code, ARMCOND_EQ, 0);
1974 /* End-of-loop check */
1975 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1977 ARM_B_COND (code, ARMCOND_EQ, 0);
1980 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1983 arm_patch (labels [4], labels [1]);
1986 arm_patch (labels [2], code);
1987 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1988 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1989 /* Save it to the third stack slot */
1990 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1991 /* Restore the registers and branch */
1992 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1995 arm_patch (labels [3], code);
1996 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1997 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1998 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2002 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2004 emit_bytes (acfg, buf, code - buf);
2005 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2007 *tramp_size = code - buf + 4;
2008 #elif defined(TARGET_ARM64)
2009 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2010 #elif defined(TARGET_POWERPC)
2012 guint8 *code, *labels [16];
2016 /* Load the mscorlib got address */
2017 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2018 /* Load the parameter from the GOT */
2019 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2020 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2022 /* Load and check key */
2024 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2025 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2027 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2029 /* End-of-loop check */
2030 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2032 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2035 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2038 mono_ppc_patch (labels [4], labels [1]);
2041 mono_ppc_patch (labels [2], code);
2042 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2043 /* r12 now contains the value of the vtable slot */
2044 /* this is not a function descriptor on ppc64 */
2045 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2046 ppc_mtctr (code, ppc_r12);
2047 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2050 mono_ppc_patch (labels [3], code);
2054 *tramp_size = code - buf;
2056 emit_bytes (acfg, buf, code - buf);
2058 g_assert_not_reached ();
2063 * arch_emit_gsharedvt_arg_trampoline:
2065 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2066 * two GOT slots which contain the argument, and the code to jump to.
2067 * TRAMP_SIZE is set to the size of the emitted trampoline.
2068 * These kinds of trampolines cannot be enumerated statically, since there could
2069 * be one trampoline per method instantiation, so we emit the same code for all
2070 * trampolines, and parameterize them using two GOT slots.
2073 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2075 #if defined(TARGET_X86)
2079 /* Similar to the PPC code above */
2081 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2084 /* Load mscorlib got address */
2085 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2087 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2088 /* Branch to the target address */
2089 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2091 #ifdef __native_client_codegen__
2093 /* emit nops to next 32 byte alignment */
2094 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2095 while (code < (buf + a)) x86_nop(code);
2099 emit_bytes (acfg, buf, code - buf);
2101 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2102 g_assert (code - buf == *tramp_size);
2103 #elif defined(TARGET_ARM)
2107 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2108 /* Similar to arch_emit_specific_trampoline () */
2111 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2112 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2113 /* Load the arg value from the GOT */
2114 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2115 /* Load the addr from the GOT */
2116 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2118 ARM_BX (code, ARMREG_R1);
2120 g_assert (code - buf == 20);
2123 emit_bytes (acfg, buf, code - buf);
2124 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2125 #elif defined(TARGET_ARM64)
2126 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2128 g_assert_not_reached ();
2133 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2135 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2136 /* Based on code generated by gcc */
2137 emit_unset_mode (acfg);
2140 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2141 ".section .ctors,\"aw\",@progbits\n"
2145 ".section .opd,\"aw\"\n"
2148 ".long .%s,.TOC.@tocbase32\n"
2151 ".type .%s,@function\n"
2153 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2155 ".section .ctors,\"aw\",@progbits\n"
2159 ".section .opd,\"aw\"\n"
2162 ".long .%1$s,.TOC.@tocbase32\n"
2163 ".size %1$s,.-%1$s\n"
2165 ".type .%1$s,@function\n"
2167 ".%1$s:\n", symbol);
2178 "lis 3, .Lglobals@h\n"
2179 "ori 3, 3, .Lglobals@l\n"
2180 "bl .mono_aot_register_module\n"
2188 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2190 ".size .%s,.-.%s\n", symbol, symbol);
2193 ".size .%1$s,.-.%1$s\n", symbol);
2199 /* END OF ARCH SPECIFIC CODE */
2202 mono_get_field_token (MonoClassField *field)
2204 MonoClass *klass = field->parent;
2207 for (i = 0; i < klass->field.count; ++i) {
2208 if (field == &klass->fields [i])
2209 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2212 g_assert_not_reached ();
2217 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2221 //printf ("ENCODE: %d 0x%x.\n", value, value);
2224 * Same encoding as the one used in the metadata, extended to handle values
2225 * greater than 0x1fffffff.
2227 if ((value >= 0) && (value <= 127))
2229 else if ((value >= 0) && (value <= 16383)) {
2230 p [0] = 0x80 | (value >> 8);
2231 p [1] = value & 0xff;
2233 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2234 p [0] = (value >> 24) | 0xc0;
2235 p [1] = (value >> 16) & 0xff;
2236 p [2] = (value >> 8) & 0xff;
2237 p [3] = value & 0xff;
2242 p [1] = (value >> 24) & 0xff;
2243 p [2] = (value >> 16) & 0xff;
2244 p [3] = (value >> 8) & 0xff;
2245 p [4] = value & 0xff;
2253 stream_init (MonoDynamicStream *sh)
2256 sh->alloc_size = 4096;
2257 sh->data = g_malloc (4096);
2259 /* So offsets are > 0 */
2265 make_room_in_stream (MonoDynamicStream *stream, int size)
2267 if (size <= stream->alloc_size)
2270 while (stream->alloc_size <= size) {
2271 if (stream->alloc_size < 4096)
2272 stream->alloc_size = 4096;
2274 stream->alloc_size *= 2;
2277 stream->data = g_realloc (stream->data, stream->alloc_size);
2281 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2285 make_room_in_stream (stream, stream->index + len);
2286 memcpy (stream->data + stream->index, data, len);
2287 idx = stream->index;
2288 stream->index += len;
2295 * Add data to the binary blob inside the aot image. Returns the offset inside the
2296 * blob where the data was stored.
2299 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2301 if (acfg->blob.alloc_size == 0)
2302 stream_init (&acfg->blob);
2304 return add_stream_data (&acfg->blob, (char*)data, data_len);
2308 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2313 if (acfg->blob.alloc_size == 0)
2314 stream_init (&acfg->blob);
2316 count = acfg->blob.index % align;
2318 /* we assume the stream data will be aligned */
2320 add_stream_data (&acfg->blob, buf, 4 - count);
2322 return add_stream_data (&acfg->blob, (char*)data, data_len);
2326 * emit_offset_table:
2328 * Emit a table of increasing offsets in a compact form using differential encoding.
2329 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2330 * group size, the more compact the table becomes, but the slower it becomes to compute
2331 * a given entry. Returns the size of the table.
2334 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2336 gint32 current_offset;
2337 int i, buf_size, ngroups, index_entry_size;
2339 guint32 *index_offsets;
2341 ngroups = (noffsets + (group_size - 1)) / group_size;
2343 index_offsets = g_new0 (guint32, ngroups);
2345 buf_size = noffsets * 4;
2346 p = buf = g_malloc0 (buf_size);
2349 for (i = 0; i < noffsets; ++i) {
2350 //printf ("D: %d -> %d\n", i, offsets [i]);
2351 if ((i % group_size) == 0) {
2352 index_offsets [i / group_size] = p - buf;
2353 /* Emit the full value for these entries */
2354 encode_value (offsets [i], p, &p);
2356 /* The offsets are allowed to be non-increasing */
2357 //g_assert (offsets [i] >= current_offset);
2358 encode_value (offsets [i] - current_offset, p, &p);
2360 current_offset = offsets [i];
2363 if (ngroups && index_offsets [ngroups - 1] < 65000)
2364 index_entry_size = 2;
2366 index_entry_size = 4;
2368 /* Emit the header */
2369 emit_int32 (acfg, noffsets);
2370 emit_int32 (acfg, group_size);
2371 emit_int32 (acfg, ngroups);
2372 emit_int32 (acfg, index_entry_size);
2374 /* Emit the index */
2375 for (i = 0; i < ngroups; ++i) {
2376 if (index_entry_size == 2)
2377 emit_int16 (acfg, index_offsets [i]);
2379 emit_int32 (acfg, index_offsets [i]);
2383 emit_bytes (acfg, buf, p - buf);
2385 return (int)(p - buf) + (ngroups * 4);
2389 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2393 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2397 index = g_hash_table_size (cfg->image_hash);
2398 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2399 g_ptr_array_add (cfg->image_table, image);
2405 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2408 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2410 /* FIXME: Search referenced images as well */
2411 if (!acfg->typespec_classes) {
2412 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2413 for (i = 0; i < len; ++i) {
2415 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2416 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2419 for (i = 0; i < len; ++i) {
2420 if (acfg->typespec_classes [i] == klass)
2425 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2431 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2434 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2437 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2440 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2443 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2448 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2452 if (klass->generic_class) {
2454 g_assert (klass->type_token);
2456 /* Find a typespec for a class if possible */
2457 token = find_typespec_for_class (acfg, klass);
2459 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2460 encode_value (token, p, &p);
2462 MonoClass *gclass = klass->generic_class->container_class;
2463 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2464 static int count = 0;
2467 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2468 encode_klass_ref (acfg, gclass, p, &p);
2469 encode_ginst (acfg, inst, p, &p);
2473 } else if (klass->type_token) {
2474 int iindex = get_image_index (acfg, klass->image);
2476 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2478 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2479 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2481 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2482 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2483 encode_value (get_image_index (acfg, klass->image), p, &p);
2485 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2486 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2487 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2489 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2490 encode_value (klass->byval_arg.type, p, &p);
2491 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2493 encode_value (container ? 1 : 0, p, &p);
2495 encode_value (container->is_method, p, &p);
2496 g_assert (par->serial == 0);
2497 if (container->is_method)
2498 encode_method_ref (acfg, container->owner.method, p, &p);
2500 encode_klass_ref (acfg, container->owner.klass, p, &p);
2502 encode_value (par->serial, p, &p);
2504 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2505 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2506 encode_type (acfg, &klass->byval_arg, p, &p);
2509 g_assert (klass->rank > 0);
2510 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2511 encode_value (klass->rank, p, &p);
2512 encode_klass_ref (acfg, klass->element_class, p, &p);
2520 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2521 * standard metadata encoding.
2524 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2526 gboolean shared = FALSE;
2529 * The encoding of generic instances is large so emit them only once.
2531 if (klass->generic_class) {
2533 g_assert (klass->type_token);
2535 /* Find a typespec for a class if possible */
2536 token = find_typespec_for_class (acfg, klass);
2539 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2544 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2548 buf2 = g_malloc (1024);
2551 encode_klass_ref_inner (acfg, klass, p, &p);
2552 g_assert (p - buf2 < 1024);
2554 offset = add_to_blob (acfg, buf2, p - buf2);
2557 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2563 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2564 encode_value (offset, p, &p);
2569 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2573 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2575 guint32 token = mono_get_field_token (field);
2578 encode_klass_ref (cfg, field->parent, p, &p);
2579 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2580 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2585 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2590 encode_value (inst->type_argc, p, &p);
2591 for (i = 0; i < inst->type_argc; ++i)
2592 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2597 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2600 MonoGenericInst *inst;
2602 inst = context->class_inst;
2604 g_assert (inst->type_argc);
2605 encode_ginst (acfg, inst, p, &p);
2607 encode_value (0, p, &p);
2609 inst = context->method_inst;
2611 g_assert (inst->type_argc);
2612 encode_ginst (acfg, inst, p, &p);
2614 encode_value (0, p, &p);
2620 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2624 g_assert (t->num_mods == 0);
2625 /* t->attrs can be ignored */
2626 //g_assert (t->attrs == 0);
2629 *p = MONO_TYPE_PINNED;
2633 *p = MONO_TYPE_BYREF;
2641 case MONO_TYPE_VOID:
2642 case MONO_TYPE_BOOLEAN:
2643 case MONO_TYPE_CHAR:
2656 case MONO_TYPE_STRING:
2657 case MONO_TYPE_OBJECT:
2658 case MONO_TYPE_TYPEDBYREF:
2660 case MONO_TYPE_VALUETYPE:
2661 case MONO_TYPE_CLASS:
2662 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2664 case MONO_TYPE_SZARRAY:
2665 encode_klass_ref (acfg, t->data.klass, p, &p);
2668 encode_type (acfg, t->data.type, p, &p);
2670 case MONO_TYPE_GENERICINST: {
2671 MonoClass *gclass = t->data.generic_class->container_class;
2672 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2674 encode_klass_ref (acfg, gclass, p, &p);
2675 encode_ginst (acfg, inst, p, &p);
2678 case MONO_TYPE_ARRAY: {
2679 MonoArrayType *array = t->data.array;
2682 encode_klass_ref (acfg, array->eklass, p, &p);
2683 encode_value (array->rank, p, &p);
2684 encode_value (array->numsizes, p, &p);
2685 for (i = 0; i < array->numsizes; ++i)
2686 encode_value (array->sizes [i], p, &p);
2687 encode_value (array->numlobounds, p, &p);
2688 for (i = 0; i < array->numlobounds; ++i)
2689 encode_value (array->lobounds [i], p, &p);
2693 case MONO_TYPE_MVAR:
2694 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2697 g_assert_not_reached ();
2704 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2710 /* Similar to the metadata encoding */
2711 if (sig->generic_param_count)
2715 if (sig->explicit_this)
2717 flags |= (sig->call_convention & 0x0F);
2721 if (sig->generic_param_count)
2722 encode_value (sig->generic_param_count, p, &p);
2723 encode_value (sig->param_count, p, &p);
2725 encode_type (acfg, sig->ret, p, &p);
2726 for (i = 0; i < sig->param_count; ++i) {
2727 if (sig->sentinelpos == i) {
2728 *p = MONO_TYPE_SENTINEL;
2731 encode_type (acfg, sig->params [i], p, &p);
2737 #define MAX_IMAGE_INDEX 250
2740 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2742 guint32 image_index = get_image_index (acfg, method->klass->image);
2743 guint32 token = method->token;
2744 MonoJumpInfoToken *ji;
2748 * The encoding for most methods is as follows:
2749 * - image index encoded as a leb128
2750 * - token index encoded as a leb128
2751 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2752 * types of method encodings.
2755 /* Mark methods which can't use aot trampolines because they need the further
2756 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2758 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2759 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2760 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2762 if (method->wrapper_type) {
2763 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2765 encode_value (method->wrapper_type, p, &p);
2767 switch (method->wrapper_type) {
2768 case MONO_WRAPPER_REMOTING_INVOKE:
2769 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2770 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2773 m = mono_marshal_method_from_wrapper (method);
2775 encode_method_ref (acfg, m, p, &p);
2778 case MONO_WRAPPER_PROXY_ISINST:
2779 case MONO_WRAPPER_LDFLD:
2780 case MONO_WRAPPER_LDFLDA:
2781 case MONO_WRAPPER_STFLD:
2782 case MONO_WRAPPER_ISINST: {
2783 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2786 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2789 case MONO_WRAPPER_LDFLD_REMOTE:
2790 case MONO_WRAPPER_STFLD_REMOTE:
2792 case MONO_WRAPPER_ALLOC: {
2793 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2795 /* The GC name is saved once in MonoAotFileInfo */
2796 g_assert (info->alloc_type != -1);
2797 encode_value (info->alloc_type, p, &p);
2800 case MONO_WRAPPER_WRITE_BARRIER:
2802 case MONO_WRAPPER_STELEMREF: {
2803 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2806 encode_value (info->subtype, p, &p);
2807 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2808 encode_value (info->d.virtual_stelemref.kind, p, &p);
2811 case MONO_WRAPPER_UNKNOWN: {
2812 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2815 encode_value (info->subtype, p, &p);
2816 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2817 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2818 encode_klass_ref (acfg, method->klass, p, &p);
2819 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2820 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2821 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2822 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2825 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2826 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2829 encode_value (info->subtype, p, &p);
2830 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2831 strcpy ((char*)p, method->name);
2832 p += strlen (method->name) + 1;
2833 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2834 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2836 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2837 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2841 case MONO_WRAPPER_SYNCHRONIZED: {
2844 m = mono_marshal_method_from_wrapper (method);
2846 g_assert (m != method);
2847 encode_method_ref (acfg, m, p, &p);
2850 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2851 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2854 encode_value (info->subtype, p, &p);
2856 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2857 encode_value (info->d.element_addr.rank, p, &p);
2858 encode_value (info->d.element_addr.elem_size, p, &p);
2859 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2860 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2862 g_assert_not_reached ();
2866 case MONO_WRAPPER_CASTCLASS: {
2867 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2870 encode_value (info->subtype, p, &p);
2873 case MONO_WRAPPER_RUNTIME_INVOKE: {
2874 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2877 encode_value (info->subtype, p, &p);
2878 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2879 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2880 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2881 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2884 case MONO_WRAPPER_DELEGATE_INVOKE:
2885 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2886 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2887 if (method->is_inflated) {
2888 /* These wrappers are identified by their class */
2889 encode_value (1, p, &p);
2890 encode_klass_ref (acfg, method->klass, p, &p);
2892 MonoMethodSignature *sig = mono_method_signature (method);
2893 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2895 encode_value (0, p, &p);
2896 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2897 encode_value (info ? info->subtype : 0, p, &p);
2898 encode_signature (acfg, sig, p, &p);
2902 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2903 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2906 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2907 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2911 g_assert_not_reached ();
2913 } else if (mono_method_signature (method)->is_inflated) {
2915 * This is a generic method, find the original token which referenced it and
2917 * Obtain the token from information recorded by the JIT.
2919 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2921 image_index = get_image_index (acfg, ji->image);
2922 g_assert (image_index < MAX_IMAGE_INDEX);
2925 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2926 encode_value (image_index, p, &p);
2927 encode_value (token, p, &p);
2929 MonoMethod *declaring;
2930 MonoGenericContext *context = mono_method_get_context (method);
2932 g_assert (method->is_inflated);
2933 declaring = ((MonoMethodInflated*)method)->declaring;
2936 * This might be a non-generic method of a generic instance, which
2937 * doesn't have a token since the reference is generated by the JIT
2938 * like Nullable:Box/Unbox, or by generic sharing.
2940 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2941 /* Encode the klass */
2942 encode_klass_ref (acfg, method->klass, p, &p);
2943 /* Encode the method */
2944 image_index = get_image_index (acfg, method->klass->image);
2945 g_assert (image_index < MAX_IMAGE_INDEX);
2946 g_assert (declaring->token);
2947 token = declaring->token;
2948 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2949 encode_value (image_index, p, &p);
2950 encode_value (token, p, &p);
2951 encode_generic_context (acfg, context, p, &p);
2953 } else if (token == 0) {
2954 /* This might be a method of a constructed type like int[,].Set */
2955 /* Obtain the token from information recorded by the JIT */
2956 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2958 image_index = get_image_index (acfg, ji->image);
2959 g_assert (image_index < MAX_IMAGE_INDEX);
2962 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2963 encode_value (image_index, p, &p);
2964 encode_value (token, p, &p);
2967 g_assert (method->klass->rank);
2969 /* Encode directly */
2970 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2971 encode_klass_ref (acfg, method->klass, p, &p);
2972 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2973 encode_value (0, p, &p);
2974 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2975 encode_value (1, p, &p);
2976 else if (!strcmp (method->name, "Get"))
2977 encode_value (2, p, &p);
2978 else if (!strcmp (method->name, "Address"))
2979 encode_value (3, p, &p);
2980 else if (!strcmp (method->name, "Set"))
2981 encode_value (4, p, &p);
2983 g_assert_not_reached ();
2986 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2988 if (image_index >= MONO_AOT_METHODREF_MIN) {
2989 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2990 encode_value (image_index, p, &p);
2991 encode_value (mono_metadata_token_index (token), p, &p);
2993 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3000 compare_patches (gconstpointer a, gconstpointer b)
3004 i = (*(MonoJumpInfo**)a)->ip.i;
3005 j = (*(MonoJumpInfo**)b)->ip.i;
3016 static G_GNUC_UNUSED char*
3017 patch_to_string (MonoJumpInfo *patch_info)
3021 str = g_string_new ("");
3023 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3025 switch (patch_info->type) {
3026 case MONO_PATCH_INFO_VTABLE:
3027 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3032 g_string_append_printf (str, ")");
3033 return g_string_free (str, FALSE);
3039 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3042 static inline gboolean
3043 is_plt_patch (MonoJumpInfo *patch_info)
3045 switch (patch_info->type) {
3046 case MONO_PATCH_INFO_METHOD:
3047 case MONO_PATCH_INFO_INTERNAL_METHOD:
3048 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3049 case MONO_PATCH_INFO_ICALL_ADDR:
3050 case MONO_PATCH_INFO_CLASS_INIT:
3051 case MONO_PATCH_INFO_RGCTX_FETCH:
3052 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3053 case MONO_PATCH_INFO_MONITOR_ENTER:
3054 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3055 case MONO_PATCH_INFO_MONITOR_EXIT:
3056 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3066 * Return the symbol identifying the plt entry PLT_OFFSET.
3069 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3073 * The Apple linker reorganizes object files, so it doesn't like branches to local
3074 * labels, since those have no relocations.
3076 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3078 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3085 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3087 static MonoPltEntry*
3088 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3092 if (!is_plt_patch (patch_info))
3095 if (!acfg->patch_to_plt_entry [patch_info->type])
3096 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3097 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3099 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3101 * Allocate a separate PLT slot for each such patch, since some plt
3102 * entries will refer to the method itself, and some will refer to the
3109 MonoJumpInfo *new_ji;
3111 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3113 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3114 res->plt_offset = acfg->plt_offset;
3116 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3117 if (acfg->aot_opts.write_symbols)
3118 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3120 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3122 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3124 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3126 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3128 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3129 //mono_print_ji (patch_info); printf ("\n");
3130 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3132 acfg->plt_offset ++;
3141 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3142 * JI could be found if it exists, otherwise allocates a new one.
3145 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3148 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3150 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3152 return got_offset - 1;
3155 got_offset = acfg->llvm_got_offset;
3156 acfg->llvm_got_offset ++;
3158 got_offset = acfg->got_offset;
3159 acfg->got_offset ++;
3162 acfg->stats.got_slots ++;
3163 acfg->stats.got_slot_types [ji->type] ++;
3165 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3166 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3167 g_ptr_array_add (info->got_patches, ji);
3172 /* Add a method to the list of methods which need to be emitted */
3174 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3177 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3178 g_ptr_array_add (acfg->methods, method);
3179 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3180 acfg->nmethods = acfg->methods->len + 1;
3183 if (method->wrapper_type || extra)
3184 g_ptr_array_add (acfg->extra_methods, method);
3188 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3190 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3198 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3202 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3206 index = acfg->method_index;
3207 add_method_with_index (acfg, method, index, extra);
3209 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3211 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3213 acfg->method_index ++;
3219 add_method (MonoAotCompile *acfg, MonoMethod *method)
3221 return add_method_full (acfg, method, FALSE, 0);
3225 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3227 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3228 method = mini_get_shared_method (method);
3230 if (acfg->aot_opts.log_generics)
3231 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3233 add_method_full (acfg, method, TRUE, depth);
3237 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3239 add_extra_method_with_depth (acfg, method, 0);
3243 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3245 MonoAotCompile *acfg = user_data;
3246 MonoJitICallInfo *callinfo = value;
3247 MonoMethod *wrapper;
3253 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3254 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3257 add_method (acfg, wrapper);
3261 get_runtime_invoke_sig (MonoMethodSignature *sig)
3263 MonoMethodBuilder *mb;
3266 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3267 m = mono_mb_create_method (mb, sig, 16);
3268 return mono_marshal_get_runtime_invoke (m, FALSE);
3272 can_marshal_struct (MonoClass *klass)
3274 MonoClassField *field;
3275 gboolean can_marshal = TRUE;
3276 gpointer iter = NULL;
3277 MonoMarshalType *info;
3280 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3283 info = mono_marshal_load_type_info (klass);
3285 /* Only allow a few field types to avoid asserts in the marshalling code */
3286 while ((field = mono_class_get_fields (klass, &iter))) {
3287 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3290 switch (field->type->type) {
3295 case MONO_TYPE_BOOLEAN:
3298 case MONO_TYPE_CHAR:
3306 case MONO_TYPE_STRING:
3308 case MONO_TYPE_VALUETYPE:
3309 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3310 can_marshal = FALSE;
3312 case MONO_TYPE_SZARRAY: {
3313 gboolean has_mspec = FALSE;
3316 for (i = 0; i < info->num_fields; ++i) {
3317 if (info->fields [i].field == field && info->fields [i].mspec)
3322 can_marshal = FALSE;
3326 can_marshal = FALSE;
3332 /* Its hard to compute whenever these can be marshalled or not */
3333 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3340 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3342 /* Create a vtype instantiation */
3343 MonoGenericContext shared_context;
3345 MonoGenericInst *inst;
3346 MonoGenericContainer *container;
3347 MonoClass **constraints;
3350 memset (ctx, 0, sizeof (MonoGenericContext));
3352 if (method->klass->generic_container) {
3353 shared_context = method->klass->generic_container->context;
3354 inst = shared_context.class_inst;
3356 args = g_new0 (MonoType*, inst->type_argc);
3357 for (i = 0; i < inst->type_argc; ++i) {
3358 args [i] = &mono_defaults.int_class->byval_arg;
3360 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3362 if (method->is_generic) {
3363 container = mono_method_get_generic_container (method);
3364 shared_context = container->context;
3365 inst = shared_context.method_inst;
3367 args = g_new0 (MonoType*, inst->type_argc);
3368 for (i = 0; i < container->type_argc; ++i) {
3369 MonoGenericParamInfo *info = &container->type_params [i].info;
3370 gboolean ref_only = FALSE;
3372 if (info && info->constraints) {
3373 constraints = info->constraints;
3375 while (*constraints) {
3376 MonoClass *cklass = *constraints;
3377 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3378 /* Inflaring the method with our vtype would not be valid */
3385 args [i] = &mono_defaults.object_class->byval_arg;
3387 args [i] = &mono_defaults.int_class->byval_arg;
3389 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3394 add_wrappers (MonoAotCompile *acfg)
3396 MonoMethod *method, *m;
3398 MonoMethodSignature *sig, *csig;
3402 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3403 * so there is only one wrapper of a given type, or inlining their contents into their
3406 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3408 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3409 gboolean skip = FALSE;
3411 method = mono_get_method (acfg->image, token, NULL);
3413 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3414 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3415 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3418 /* Skip methods which can not be handled by get_runtime_invoke () */
3419 sig = mono_method_signature (method);
3422 if ((sig->ret->type == MONO_TYPE_PTR) ||
3423 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3425 if (mono_class_is_open_constructed_type (sig->ret))
3428 for (j = 0; j < sig->param_count; j++) {
3429 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3431 if (mono_class_is_open_constructed_type (sig->params [j]))
3435 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3436 if (!mono_class_is_contextbound (method->klass)) {
3437 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3438 gboolean has_nullable = FALSE;
3440 for (j = 0; j < sig->param_count; j++) {
3441 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3442 has_nullable = TRUE;
3445 if (info && !has_nullable) {
3446 /* Supported by the dynamic runtime-invoke wrapper */
3450 mono_arch_dyn_call_free (info);
3455 //printf ("%s\n", mono_method_full_name (method, TRUE));
3456 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3460 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3463 /* Runtime invoke wrappers */
3465 /* void runtime-invoke () [.cctor] */
3466 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3467 csig->ret = &mono_defaults.void_class->byval_arg;
3468 add_method (acfg, get_runtime_invoke_sig (csig));
3470 /* void runtime-invoke () [Finalize] */
3471 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3473 csig->ret = &mono_defaults.void_class->byval_arg;
3474 add_method (acfg, get_runtime_invoke_sig (csig));
3476 /* void runtime-invoke (string) [exception ctor] */
3477 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3479 csig->ret = &mono_defaults.void_class->byval_arg;
3480 csig->params [0] = &mono_defaults.string_class->byval_arg;
3481 add_method (acfg, get_runtime_invoke_sig (csig));
3483 /* void runtime-invoke (string, string) [exception ctor] */
3484 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3486 csig->ret = &mono_defaults.void_class->byval_arg;
3487 csig->params [0] = &mono_defaults.string_class->byval_arg;
3488 csig->params [1] = &mono_defaults.string_class->byval_arg;
3489 add_method (acfg, get_runtime_invoke_sig (csig));
3491 /* string runtime-invoke () [Exception.ToString ()] */
3492 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3494 csig->ret = &mono_defaults.string_class->byval_arg;
3495 add_method (acfg, get_runtime_invoke_sig (csig));
3497 /* void runtime-invoke (string, Exception) [exception ctor] */
3498 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3500 csig->ret = &mono_defaults.void_class->byval_arg;
3501 csig->params [0] = &mono_defaults.string_class->byval_arg;
3502 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3503 add_method (acfg, get_runtime_invoke_sig (csig));
3505 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3506 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3508 csig->ret = &(mono_class_from_name (
3509 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3510 csig->params [0] = &mono_defaults.string_class->byval_arg;
3511 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3512 add_method (acfg, get_runtime_invoke_sig (csig));
3514 /* runtime-invoke used by finalizers */
3515 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3517 /* This is used by mono_runtime_capture_context () */
3518 method = mono_get_context_capture_method ();
3520 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3522 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3523 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3527 add_method (acfg, mono_marshal_get_stelemref ());
3529 if (MONO_ARCH_HAVE_TLS_GET) {
3530 /* Managed Allocators */
3531 nallocators = mono_gc_get_managed_allocator_types ();
3532 for (i = 0; i < nallocators; ++i) {
3533 m = mono_gc_get_managed_allocator_by_type (i);
3535 add_method (acfg, m);
3539 /* Stelemref wrappers */
3541 MonoMethod **wrappers;
3544 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3545 for (i = 0; i < nwrappers; ++i)
3546 add_method (acfg, wrappers [i]);
3550 /* castclass_with_check wrapper */
3551 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3552 /* isinst_with_check wrapper */
3553 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3555 /* JIT icall wrappers */
3556 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3557 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3561 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3562 * we use the original method instead at runtime.
3563 * Since full-aot doesn't support remoting, this is not a problem.
3566 /* remoting-invoke wrappers */
3567 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3568 MonoMethodSignature *sig;
3570 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3571 method = mono_get_method (acfg->image, token, NULL);
3573 sig = mono_method_signature (method);
3575 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3576 m = mono_marshal_get_remoting_invoke_with_check (method);
3578 add_method (acfg, m);
3583 /* delegate-invoke wrappers */
3584 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3587 MonoCustomAttrInfo *cattr;
3589 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3590 klass = mono_class_get_checked (acfg->image, token, &error);
3593 mono_error_cleanup (&error);
3597 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3600 if (!klass->generic_container) {
3601 method = mono_get_delegate_invoke (klass);
3603 m = mono_marshal_get_delegate_invoke (method, NULL);
3605 add_method (acfg, m);
3607 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3609 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3611 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3613 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3615 cattr = mono_custom_attrs_from_class (klass);
3620 for (j = 0; j < cattr->num_attrs; ++j)
3621 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3623 if (j < cattr->num_attrs)
3624 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3626 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3628 MonoGenericContext ctx;
3629 MonoMethod *inst, *gshared;
3632 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3635 method = mono_get_delegate_invoke (klass);
3636 create_gsharedvt_inst (acfg, method, &ctx);
3638 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3639 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3641 m = mono_marshal_get_delegate_invoke (inst, NULL);
3642 g_assert (m->is_inflated);
3644 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3645 add_extra_method (acfg, gshared);
3648 method = mono_get_delegate_begin_invoke (klass);
3649 create_gsharedvt_inst (acfg, method, &ctx);
3651 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3652 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3654 m = mono_marshal_get_delegate_begin_invoke (inst);
3655 g_assert (m->is_inflated);
3657 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3658 add_extra_method (acfg, gshared);
3661 method = mono_get_delegate_end_invoke (klass);
3662 create_gsharedvt_inst (acfg, method, &ctx);
3664 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3665 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3667 m = mono_marshal_get_delegate_end_invoke (inst);
3668 g_assert (m->is_inflated);
3670 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3671 add_extra_method (acfg, gshared);
3676 /* array access wrappers */
3677 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3681 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3682 klass = mono_class_get_checked (acfg->image, token, &error);
3685 mono_error_cleanup (&error);
3689 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3690 MonoMethod *m, *wrapper;
3692 /* Add runtime-invoke wrappers too */
3694 m = mono_class_get_method_from_name (klass, "Get", -1);
3696 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3697 add_extra_method (acfg, wrapper);
3698 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3700 m = mono_class_get_method_from_name (klass, "Set", -1);
3702 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3703 add_extra_method (acfg, wrapper);
3704 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3708 /* Synchronized wrappers */
3709 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3710 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3711 method = mono_get_method (acfg->image, token, NULL);
3713 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3714 if (method->is_generic) {
3716 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3718 MonoGenericContext ctx;
3719 MonoMethod *inst, *gshared, *m;
3722 * Create a generic wrapper for a generic instance, and AOT that.
3724 create_gsharedvt_inst (acfg, method, &ctx);
3725 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3726 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3727 m = mono_marshal_get_synchronized_wrapper (inst);
3728 g_assert (m->is_inflated);
3729 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3730 add_method (acfg, gshared);
3732 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3737 /* pinvoke wrappers */
3738 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3740 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3742 method = mono_get_method (acfg->image, token, NULL);
3744 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3745 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3746 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3750 /* native-to-managed wrappers */
3751 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3753 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3754 MonoCustomAttrInfo *cattr;
3757 method = mono_get_method (acfg->image, token, NULL);
3760 * Only generate native-to-managed wrappers for methods which have an
3761 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3762 * name to avoid defining a new assembly to contain it.
3764 cattr = mono_custom_attrs_from_method (method);
3767 for (j = 0; j < cattr->num_attrs; ++j)
3768 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3770 if (j < cattr->num_attrs) {
3771 MonoCustomAttrEntry *e = &cattr->attrs [j];
3772 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3773 const char *p = (const char*)e->data;
3775 int slen, num_named, named_type, data_type;
3779 char *export_name = NULL;
3780 MonoMethod *wrapper;
3782 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3783 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3784 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3785 mono_method_full_name (method, TRUE));
3789 g_assert (sig->param_count == 1);
3790 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3793 * Decode the cattr manually since we can't create objects
3794 * during aot compilation.
3800 /* From load_cattr_value () in reflection.c */
3801 slen = mono_metadata_decode_value (p, &p);
3802 n = g_memdup (p, slen + 1);
3804 t = mono_reflection_type_from_name (n, acfg->image);
3808 klass = mono_class_from_mono_type (t);
3809 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3813 num_named = read16 (p);
3816 g_assert (num_named < 2);
3817 if (num_named == 1) {
3820 MonoType *prop_type;
3822 /* parse ExportSymbol attribute */
3824 named_type = *named;
3829 name_len = mono_metadata_decode_blob_size (named, &named);
3830 name = g_malloc (name_len + 1);
3831 memcpy (name, named, name_len);
3832 name [name_len] = 0;
3835 g_assert (named_type == 0x54);
3836 g_assert (!strcmp (name, "ExportSymbol"));
3838 prop_type = &mono_defaults.string_class->byval_arg;
3840 /* load_cattr_value (), string case */
3841 g_assert (*named != (char)0xff);
3842 slen = mono_metadata_decode_value (named, &named);
3843 export_name = g_malloc (slen + 1);
3844 memcpy (export_name, named, slen);
3845 export_name [slen] = 0;
3849 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3850 add_method (acfg, wrapper);
3852 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3856 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3857 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3858 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3862 /* StructureToPtr/PtrToStructure wrappers */
3863 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3867 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3868 klass = mono_class_get_checked (acfg->image, token, &error);
3871 mono_error_cleanup (&error);
3875 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3876 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3877 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3878 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3884 has_type_vars (MonoClass *klass)
3886 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3889 return has_type_vars (klass->element_class);
3890 if (klass->generic_class) {
3891 MonoGenericContext *context = &klass->generic_class->context;
3892 if (context->class_inst) {
3895 for (i = 0; i < context->class_inst->type_argc; ++i)
3896 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3900 if (klass->generic_container)
3906 is_vt_inst (MonoGenericInst *inst)
3910 for (i = 0; i < inst->type_argc; ++i) {
3911 MonoType *t = inst->type_argv [i];
3912 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3919 method_has_type_vars (MonoMethod *method)
3921 if (has_type_vars (method->klass))
3924 if (method->is_inflated) {
3925 MonoGenericContext *context = mono_method_get_context (method);
3926 if (context->method_inst) {
3929 for (i = 0; i < context->method_inst->type_argc; ++i)
3930 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3937 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3940 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3942 /* This might lead to a huge code blowup so only do it if neccesary */
3943 if (!acfg->aot_opts.full_aot && !force)
3946 add_generic_class_with_depth (acfg, klass, 0, ref);
3950 check_type_depth (MonoType *t, int depth)
3958 case MONO_TYPE_GENERICINST: {
3959 MonoGenericClass *gklass = t->data.generic_class;
3960 MonoGenericInst *ginst = gklass->context.class_inst;
3963 for (i = 0; i < ginst->type_argc; ++i) {
3964 if (check_type_depth (ginst->type_argv [i], depth + 1))
3978 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3981 * add_generic_class:
3983 * Add all methods of a generic class.
3986 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3989 MonoClassField *field;
3991 gboolean use_gsharedvt = FALSE;
3993 if (!acfg->ginst_hash)
3994 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3996 mono_class_init (klass);
3998 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4001 if (has_type_vars (klass))
4004 if (!klass->generic_class && !klass->rank)
4007 if (klass->exception_type)
4010 if (!acfg->ginst_hash)
4011 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4013 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4016 if (check_type_depth (&klass->byval_arg, 0))
4019 if (acfg->aot_opts.log_generics)
4020 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4022 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4025 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4026 * Enable this only for some classes since gsharedvt might not support all methods.
4028 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) &&
4029 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4030 use_gsharedvt = TRUE;
4033 while ((method = mono_class_get_methods (klass, &iter))) {
4034 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4036 * This is partial sharing, and we can't handle it yet
4041 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4043 add_types_from_method_header (acfg, method);
4047 if (method->is_generic)
4052 * FIXME: Instances which are referenced by these methods are not added,
4053 * for example Array.Resize<int> for List<int>.Add ().
4055 add_extra_method_with_depth (acfg, method, depth + 1);
4059 while ((field = mono_class_get_fields (klass, &iter))) {
4060 if (field->type->type == MONO_TYPE_GENERICINST)
4061 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4064 if (klass->delegate) {
4065 method = mono_get_delegate_invoke (klass);
4067 method = mono_marshal_get_delegate_invoke (method, NULL);
4069 if (acfg->aot_opts.log_generics)
4070 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4072 add_method (acfg, method);
4075 /* Add superclasses */
4077 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4080 * For ICollection<T>, add instances of the helper methods
4081 * in Array, since a T[] could be cast to ICollection<T>.
4083 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4084 (!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"))) {
4085 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4086 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4090 if (!strcmp (klass->name, "IEnumerator`1"))
4091 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4093 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4095 /* Add the T[]/InternalEnumerator class */
4096 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4100 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4101 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4105 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4106 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4110 while ((method = mono_class_get_methods (array_class, &iter))) {
4111 if (strstr (method->name, name_prefix)) {
4112 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4114 add_extra_method_with_depth (acfg, m, depth);
4118 g_free (name_prefix);
4121 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4122 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4123 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4124 MonoClass *icomparable, *gcomparer;
4125 MonoGenericContext ctx;
4126 MonoType *args [16];
4128 memset (&ctx, 0, sizeof (ctx));
4130 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4131 g_assert (icomparable);
4132 args [0] = &tclass->byval_arg;
4133 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4135 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4136 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4137 g_assert (gcomparer);
4138 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4142 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4143 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4144 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4145 MonoClass *iface, *gcomparer;
4146 MonoGenericContext ctx;
4147 MonoType *args [16];
4149 memset (&ctx, 0, sizeof (ctx));
4151 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4153 args [0] = &tclass->byval_arg;
4154 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4156 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4157 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4158 g_assert (gcomparer);
4159 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4165 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4168 MonoGenericContext ctx;
4169 MonoType *args [16];
4171 if (acfg->aot_opts.no_instances)
4174 memset (&ctx, 0, sizeof (ctx));
4176 for (i = 0; i < ninsts; ++i) {
4177 args [0] = insts [i];
4178 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4179 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4184 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4186 MonoMethodHeader *header;
4187 MonoMethodSignature *sig;
4190 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4192 sig = mono_method_signature (method);
4195 for (j = 0; j < sig->param_count; ++j)
4196 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4197 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4200 header = mono_method_get_header (method);
4203 for (j = 0; j < header->num_locals; ++j)
4204 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4205 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4207 mono_loader_clear_error ();
4212 * add_generic_instances:
4214 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4217 add_generic_instances (MonoAotCompile *acfg)
4222 MonoGenericContext *context;
4224 if (acfg->aot_opts.no_instances)
4227 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4228 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4229 method = mono_get_method (acfg->image, token, NULL);
4234 if (method->klass->image != acfg->image)
4237 context = mono_method_get_context (method);
4239 if (context && ((context->class_inst && context->class_inst->is_open)))
4243 * For open methods, create an instantiation which can be passed to the JIT.
4244 * FIXME: Handle class_inst as well.
4246 if (context && context->method_inst && context->method_inst->is_open) {
4248 MonoGenericContext shared_context;
4249 MonoGenericInst *inst;
4250 MonoType **type_argv;
4252 MonoMethod *declaring_method;
4253 gboolean supported = TRUE;
4255 /* Check that the context doesn't contain open constructed types */
4256 if (context->class_inst) {
4257 inst = context->class_inst;
4258 for (i = 0; i < inst->type_argc; ++i) {
4259 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)
4261 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4265 if (context->method_inst) {
4266 inst = context->method_inst;
4267 for (i = 0; i < inst->type_argc; ++i) {
4268 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)
4270 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4278 memset (&shared_context, 0, sizeof (MonoGenericContext));
4280 inst = context->class_inst;
4282 type_argv = g_new0 (MonoType*, inst->type_argc);
4283 for (i = 0; i < inst->type_argc; ++i) {
4284 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)
4285 type_argv [i] = &mono_defaults.object_class->byval_arg;
4287 type_argv [i] = inst->type_argv [i];
4290 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4294 inst = context->method_inst;
4296 type_argv = g_new0 (MonoType*, inst->type_argc);
4297 for (i = 0; i < inst->type_argc; ++i) {
4298 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)
4299 type_argv [i] = &mono_defaults.object_class->byval_arg;
4301 type_argv [i] = inst->type_argv [i];
4304 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4308 if (method->is_generic || method->klass->generic_container)
4309 declaring_method = method;
4311 declaring_method = mono_method_get_declaring_generic_method (method);
4313 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4314 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4318 * If the method is fully sharable, it was already added in place of its
4319 * generic definition.
4321 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4325 * FIXME: Partially shared methods are not shared here, so we end up with
4326 * many identical methods.
4328 add_extra_method (acfg, method);
4331 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4335 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4337 klass = mono_class_get_checked (acfg->image, token, &error);
4338 if (!klass || klass->rank) {
4339 mono_error_cleanup (&error);
4343 add_generic_class (acfg, klass, FALSE, "typespec");
4346 /* Add types of args/locals */
4347 for (i = 0; i < acfg->methods->len; ++i) {
4348 method = g_ptr_array_index (acfg->methods, i);
4349 add_types_from_method_header (acfg, method);
4352 if (acfg->image == mono_defaults.corlib) {
4354 MonoType *insts [256];
4357 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4358 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4359 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4360 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4361 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4362 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4363 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4364 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4365 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4366 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4367 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4368 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4370 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4371 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4373 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4374 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4376 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4378 /* Add instances of the array generic interfaces for primitive types */
4379 /* This will add instances of the InternalArray_ helper methods in Array too */
4380 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4382 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4383 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4385 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4386 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4388 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4391 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4392 * used for all instances of GetGenericValueImpl by the AOT runtime.
4395 MonoGenericContext ctx;
4396 MonoType *args [16];
4397 MonoMethod *get_method;
4398 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4400 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4404 memset (&ctx, 0, sizeof (ctx));
4405 args [0] = &mono_defaults.object_class->byval_arg;
4406 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4407 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4408 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4412 /* Same for CompareExchange<T>/Exchange<T> */
4414 MonoGenericContext ctx;
4415 MonoType *args [16];
4417 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4418 gpointer iter = NULL;
4420 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4421 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4423 memset (&ctx, 0, sizeof (ctx));
4424 args [0] = &mono_defaults.object_class->byval_arg;
4425 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4426 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4427 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4432 /* Same for Volatile.Read/Write<T> */
4434 MonoGenericContext ctx;
4435 MonoType *args [16];
4437 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4438 gpointer iter = NULL;
4440 if (volatile_klass) {
4441 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4442 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4444 memset (&ctx, 0, sizeof (ctx));
4445 args [0] = &mono_defaults.object_class->byval_arg;
4446 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4447 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4448 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4457 * is_direct_callable:
4459 * Return whenever the method identified by JI is directly callable without
4460 * going through the PLT.
4463 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4465 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4466 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4468 gboolean direct_callable = TRUE;
4470 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4471 direct_callable = FALSE;
4472 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4473 // FIXME: Maybe call the wrapper directly ?
4474 direct_callable = FALSE;
4476 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4477 /* Disable this so all calls go through load_method (), see the
4478 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4479 * mono_debugger_agent_init ().
4481 direct_callable = FALSE;
4484 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4485 /* sgen does some initialization when the allocator method is created */
4486 direct_callable = FALSE;
4488 if (direct_callable)
4491 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4492 if (acfg->aot_opts.direct_pinvoke)
4494 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4495 if (acfg->aot_opts.direct_icalls)
4503 #ifdef MONO_ARCH_AOT_SUPPORTED
4505 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4507 MonoImage *image = method->klass->image;
4508 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4509 MonoTableInfo *tables = image->tables;
4510 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4511 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4512 guint32 im_cols [MONO_IMPLMAP_SIZE];
4515 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4519 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4522 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4524 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4527 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4529 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4536 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4538 if (a->native_offset == b->native_offset)
4539 return a->il_offset - b->il_offset;
4541 return a->native_offset - b->native_offset;
4545 * compute_line_numbers:
4547 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4550 static MonoDebugSourceLocation**
4551 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4553 MonoDebugMethodInfo *minfo;
4554 MonoDebugLineNumberEntry *ln_array;
4555 MonoDebugSourceLocation *loc;
4556 int i, prev_line, prev_il_offset;
4557 int *native_to_il_offset = NULL;
4558 MonoDebugSourceLocation **res;
4561 minfo = mono_debug_lookup_method (method);
4564 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4565 if (debug_info->code_size != code_size)
4568 g_assert (code_size);
4570 /* Compute the native->IL offset mapping */
4572 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4573 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4575 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4577 native_to_il_offset = g_new0 (int, code_size + 1);
4579 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4581 MonoDebugLineNumberEntry *lne = &ln_array [i];
4584 for (j = 0; j < lne->native_offset; ++j)
4585 native_to_il_offset [j] = -1;
4588 if (i < debug_info->num_line_numbers - 1) {
4589 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4591 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4592 native_to_il_offset [j] = lne->il_offset;
4594 for (j = lne->native_offset; j < code_size; ++j)
4595 native_to_il_offset [j] = lne->il_offset;
4600 /* Compute the native->line number mapping */
4601 res = g_new0 (MonoDebugSourceLocation*, code_size);
4602 prev_il_offset = -1;
4605 for (i = 0; i < code_size; ++i) {
4606 int il_offset = native_to_il_offset [i];
4608 if (il_offset == -1 || il_offset == prev_il_offset)
4610 prev_il_offset = il_offset;
4611 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4612 if (!(loc && loc->source_file))
4614 if (loc->row == prev_line) {
4615 mono_debug_symfile_free_location (loc);
4618 prev_line = loc->row;
4619 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4621 /* This will cover the prolog too */
4631 get_file_index (MonoAotCompile *acfg, const char *source_file)
4635 // FIXME: Free these
4636 if (!acfg->dwarf_ln_filenames)
4637 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4638 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4640 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4641 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4642 emit_unset_mode (acfg);
4643 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4655 * emit_and_reloc_code:
4657 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4658 * is true, calls are made through the GOT too. This is used for emitting trampolines
4659 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4660 * since trampolines are needed to make PTL work.
4663 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4665 int i, pindex, start_index, method_index;
4667 MonoJumpInfo *patch_info;
4668 MonoMethodHeader *header;
4669 MonoDebugSourceLocation **locs = NULL;
4671 #ifdef MONO_ARCH_AOT_SUPPORTED
4672 gboolean direct_call, external_call;
4674 const char *direct_call_target = 0;
4675 const char *direct_pinvoke;
4679 header = mono_method_get_header (method);
4681 method_index = get_method_index (acfg, method);
4684 if (acfg->gas_line_numbers && method && debug_info) {
4685 locs = compute_line_numbers (method, code_len, debug_info);
4687 int findex = get_file_index (acfg, "<unknown>");
4688 emit_unset_mode (acfg);
4689 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4693 /* Collect and sort relocations */
4694 patches = g_ptr_array_new ();
4695 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4696 g_ptr_array_add (patches, patch_info);
4697 g_ptr_array_sort (patches, compare_patches);
4700 for (i = 0; i < code_len; i += INST_LEN) {
4702 for (pindex = start_index; pindex < patches->len; ++pindex) {
4703 patch_info = g_ptr_array_index (patches, pindex);
4704 if (patch_info->ip.i >= i)
4708 if (locs && locs [i]) {
4709 MonoDebugSourceLocation *loc = locs [i];
4712 findex = get_file_index (acfg, loc->source_file);
4713 emit_unset_mode (acfg);
4714 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4715 mono_debug_symfile_free_location (loc);
4719 #ifdef MONO_ARCH_AOT_SUPPORTED
4720 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4721 start_index = pindex;
4723 switch (patch_info->type) {
4724 case MONO_PATCH_INFO_NONE:
4726 case MONO_PATCH_INFO_GOT_OFFSET: {
4729 arch_emit_got_offset (acfg, code + i, &code_size);
4730 i += code_size - INST_LEN;
4732 patch_info->type = MONO_PATCH_INFO_NONE;
4735 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4736 int code_size, index;
4737 char *selector = (void*)patch_info->data.target;
4739 if (!acfg->objc_selector_to_index)
4740 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4741 if (!acfg->objc_selectors)
4742 acfg->objc_selectors = g_ptr_array_new ();
4743 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4747 index = acfg->objc_selector_index;
4748 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4749 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4750 acfg->objc_selector_index ++;
4753 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4754 i += code_size - INST_LEN;
4756 patch_info->type = MONO_PATCH_INFO_NONE;
4761 * If this patch is a call, try emitting a direct call instead of
4762 * through a PLT entry. This is possible if the called method is in
4763 * the same assembly and requires no initialization.
4765 direct_call = FALSE;
4766 external_call = FALSE;
4767 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4768 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4769 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4770 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4772 direct_call_target = callee_cfg->asm_symbol;
4773 patch_info->type = MONO_PATCH_INFO_NONE;
4774 acfg->stats.direct_calls ++;
4777 acfg->stats.all_calls ++;
4778 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4779 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4780 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4781 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4783 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4784 if (direct_pinvoke) {
4786 g_assert (strlen (direct_pinvoke) < 1000);
4787 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4790 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4791 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4792 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4793 /* Call to a C function implementing a jit icall */
4795 external_call = TRUE;
4796 g_assert (strlen (sym) < 1000);
4797 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4799 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4800 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4801 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4802 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4803 /* Call to a jit icall without a wrapper */
4805 external_call = TRUE;
4806 g_assert (strlen (sym) < 1000);
4807 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4812 patch_info->type = MONO_PATCH_INFO_NONE;
4813 acfg->stats.direct_calls ++;
4816 if (!got_only && !direct_call) {
4817 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4819 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4821 direct_call_target = plt_entry->symbol;
4823 /* Nullify the patch */
4824 patch_info->type = MONO_PATCH_INFO_NONE;
4825 plt_entry->jit_used = TRUE;
4832 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4833 i += call_size - INST_LEN;
4837 got_slot = get_got_offset (acfg, FALSE, patch_info);
4839 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4840 i += code_size - INST_LEN;
4846 #endif /* MONO_ARCH_AOT_SUPPORTED */
4849 /* Find next patch */
4851 for (pindex = start_index; pindex < patches->len; ++pindex) {
4852 patch_info = g_ptr_array_index (patches, pindex);
4853 if (patch_info->ip.i >= i)
4857 /* Try to emit multiple bytes at once */
4858 if (pindex < patches->len && patch_info->ip.i > i) {
4861 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4862 if (locs && locs [limit])
4866 emit_code_bytes (acfg, code + i, limit - i);
4867 i = limit - INST_LEN;
4869 emit_code_bytes (acfg, code + i, INST_LEN);
4880 * Return a modified version of S which only includes characters permissible in symbols.
4883 sanitize_symbol (MonoAotCompile *acfg, char *s)
4885 gboolean process = FALSE;
4894 for (i = 0; i < len; ++i)
4895 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4900 gs = g_string_sized_new (len);
4901 for (i = 0; i < len; ++i) {
4903 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4904 g_string_append_c (gs, c);
4905 } else if (c > 0x7f) {
4906 /* multi-byte utf8 */
4907 g_string_append_printf (gs, "_0x%x", c);
4910 while (c >> 6 == 0x2) {
4911 g_string_append_printf (gs, "%x", c);
4915 g_string_append_printf (gs, "_");
4918 g_string_append_c (gs, '_');
4922 res = mono_mempool_strdup (acfg->mempool, gs->str);
4923 g_string_free (gs, TRUE);
4928 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4930 char *name1, *name2, *cached;
4931 int i, j, len, count;
4932 MonoMethod *cached_method;
4934 name1 = mono_method_full_name (method, TRUE);
4937 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4938 if ((!prefix || !*prefix) && name1 [0] == 'L')
4942 len = strlen (name1);
4943 name2 = malloc (strlen (prefix) + len + 16);
4944 memcpy (name2, prefix, strlen (prefix));
4945 j = strlen (prefix);
4946 for (i = 0; i < len; ++i) {
4947 if (isalnum (name1 [i])) {
4948 name2 [j ++] = name1 [i];
4949 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4951 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4954 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4964 cached_method = g_hash_table_lookup (cache, name2);
4965 if (!(cached_method && cached_method != method))
4967 sprintf (name2 + j, "_%d", count);
4971 cached = g_strdup (name2);
4972 g_hash_table_insert (cache, cached, method);
4978 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4983 char *debug_sym = NULL;
4984 char *symbol = NULL;
4985 int func_alignment = AOT_FUNC_ALIGNMENT;
4986 MonoMethodHeader *header;
4989 method = cfg->orig_method;
4990 code = cfg->native_code;
4991 header = cfg->header;
4993 method_index = get_method_index (acfg, method);
4994 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4996 /* Make the labels local */
4997 emit_section_change (acfg, ".text", 0);
4998 emit_alignment_code (acfg, func_alignment);
5000 if (acfg->global_symbols && acfg->need_no_dead_strip)
5001 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5003 emit_label (acfg, cfg->asm_symbol);
5005 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm_separate) {
5007 * Write a C style symbol for every method, this has two uses:
5008 * - it works on platforms where the dwarf debugging info is not
5010 * - it allows the setting of breakpoints of aot-ed methods.
5012 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5014 if (acfg->need_no_dead_strip)
5015 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5016 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5017 emit_label (acfg, debug_sym);
5020 export_name = g_hash_table_lookup (acfg->export_names, method);
5022 /* Emit a global symbol for the method */
5023 emit_global_inner (acfg, export_name, TRUE);
5024 emit_label (acfg, export_name);
5027 if (cfg->verbose_level > 0)
5028 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5030 acfg->stats.code_size += cfg->code_len;
5032 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5034 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 ()));
5038 if (acfg->aot_opts.write_symbols) {
5040 emit_symbol_size (acfg, debug_sym, ".");
5042 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5046 emit_label (acfg, symbol);
5053 * Encode PATCH_INFO into its disk representation.
5056 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5060 switch (patch_info->type) {
5061 case MONO_PATCH_INFO_NONE:
5063 case MONO_PATCH_INFO_IMAGE:
5064 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5066 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5067 case MONO_PATCH_INFO_JIT_TLS_ID:
5068 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5070 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5071 encode_value (patch_info->data.index, p, &p);
5073 case MONO_PATCH_INFO_METHOD_REL:
5074 encode_value ((gint)patch_info->data.offset, p, &p);
5076 case MONO_PATCH_INFO_SWITCH: {
5077 gpointer *table = (gpointer *)patch_info->data.table->table;
5080 encode_value (patch_info->data.table->table_size, p, &p);
5081 for (k = 0; k < patch_info->data.table->table_size; k++)
5082 encode_value ((int)(gssize)table [k], p, &p);
5085 case MONO_PATCH_INFO_METHODCONST:
5086 case MONO_PATCH_INFO_METHOD:
5087 case MONO_PATCH_INFO_METHOD_JUMP:
5088 case MONO_PATCH_INFO_ICALL_ADDR:
5089 case MONO_PATCH_INFO_METHOD_RGCTX:
5090 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5091 encode_method_ref (acfg, patch_info->data.method, p, &p);
5093 case MONO_PATCH_INFO_INTERNAL_METHOD:
5094 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5095 guint32 len = strlen (patch_info->data.name);
5097 encode_value (len, p, &p);
5099 memcpy (p, patch_info->data.name, len);
5104 case MONO_PATCH_INFO_LDSTR: {
5105 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5106 guint32 token = patch_info->data.token->token;
5107 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5108 encode_value (image_index, p, &p);
5109 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5112 case MONO_PATCH_INFO_RVA:
5113 case MONO_PATCH_INFO_DECLSEC:
5114 case MONO_PATCH_INFO_LDTOKEN:
5115 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5116 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5117 encode_value (patch_info->data.token->token, p, &p);
5118 encode_value (patch_info->data.token->has_context, p, &p);
5119 if (patch_info->data.token->has_context)
5120 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5122 case MONO_PATCH_INFO_EXC_NAME: {
5123 MonoClass *ex_class;
5126 mono_class_from_name (mono_defaults.exception_class->image,
5127 "System", patch_info->data.target);
5128 g_assert (ex_class);
5129 encode_klass_ref (acfg, ex_class, p, &p);
5132 case MONO_PATCH_INFO_R4:
5133 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5135 case MONO_PATCH_INFO_R8:
5136 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5137 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5139 case MONO_PATCH_INFO_VTABLE:
5140 case MONO_PATCH_INFO_CLASS:
5141 case MONO_PATCH_INFO_IID:
5142 case MONO_PATCH_INFO_ADJUSTED_IID:
5143 case MONO_PATCH_INFO_CLASS_INIT:
5144 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5146 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5147 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5148 if (patch_info->data.del_tramp->method) {
5149 encode_value (1, p, &p);
5150 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5152 encode_value (0, p, &p);
5154 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5156 case MONO_PATCH_INFO_FIELD:
5157 case MONO_PATCH_INFO_SFLDA:
5158 encode_field_info (acfg, patch_info->data.field, p, &p);
5160 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5162 case MONO_PATCH_INFO_RGCTX_FETCH: {
5163 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5168 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5169 * reference the same method, so encode the method only once.
5171 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5173 buf2 = g_malloc (1024);
5176 encode_method_ref (acfg, entry->method, p2, &p2);
5177 g_assert (p2 - buf2 < 1024);
5179 offset = add_to_blob (acfg, buf2, p2 - buf2);
5182 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5187 encode_value (offset, p, &p);
5188 g_assert ((int)entry->info_type < 256);
5189 g_assert (entry->data->type < 256);
5190 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5191 encode_patch (acfg, entry->data, p, &p);
5194 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5195 case MONO_PATCH_INFO_MONITOR_ENTER:
5196 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5197 case MONO_PATCH_INFO_MONITOR_EXIT:
5198 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5200 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5201 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5202 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5204 case MONO_PATCH_INFO_SIGNATURE:
5205 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5207 case MONO_PATCH_INFO_TLS_OFFSET:
5208 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5210 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5211 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5212 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5214 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5215 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5218 encode_method_ref (acfg, info->method, p, &p);
5219 encode_value (info->num_entries, p, &p);
5220 for (i = 0; i < info->num_entries; ++i) {
5221 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5223 encode_value (template->info_type, p, &p);
5224 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5225 case MONO_PATCH_INFO_CLASS:
5226 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5228 case MONO_PATCH_INFO_FIELD:
5229 encode_field_info (acfg, template->data, p, &p);
5232 g_assert_not_reached ();
5238 case MONO_PATCH_INFO_LDSTR_LIT: {
5239 const char *s = patch_info->data.target;
5241 encode_value (strlen (s), p, &p);
5242 memcpy (p, s, strlen (s) + 1);
5246 g_warning ("unable to handle jump info %d", patch_info->type);
5247 g_assert_not_reached ();
5254 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5257 guint32 pindex, offset;
5258 MonoJumpInfo *patch_info;
5260 encode_value (n_patches, p, &p);
5262 for (pindex = 0; pindex < patches->len; ++pindex) {
5263 patch_info = g_ptr_array_index (patches, pindex);
5265 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5269 offset = get_got_offset (acfg, llvm, patch_info);
5270 encode_value (offset, p, &p);
5277 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5281 int pindex, buf_size, n_patches;
5283 MonoJumpInfo *patch_info;
5284 MonoMethodHeader *header;
5285 guint32 method_index;
5287 guint32 first_got_offset;
5289 method = cfg->orig_method;
5290 header = mono_method_get_header (method);
5292 method_index = get_method_index (acfg, method);
5294 /* Sort relocations */
5295 patches = g_ptr_array_new ();
5296 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5297 g_ptr_array_add (patches, patch_info);
5298 g_ptr_array_sort (patches, compare_patches);
5300 first_got_offset = acfg->cfgs [method_index]->got_offset;
5302 /**********************/
5303 /* Encode method info */
5304 /**********************/
5306 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5307 p = buf = g_malloc (buf_size);
5309 if (mono_class_get_cctor (method->klass))
5310 encode_klass_ref (acfg, method->klass, p, &p);
5312 /* Not needed when loading the method */
5313 encode_value (0, p, &p);
5316 if (cfg->opt & MONO_OPT_SHARED) {
5317 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5318 for (l = cfg->ldstr_list; l; l = l->next) {
5319 encode_value ((long)l->data, p, &p);
5323 /* Used only in shared mode */
5324 g_assert (!cfg->ldstr_list);
5327 for (pindex = 0; pindex < patches->len; ++pindex) {
5328 patch_info = g_ptr_array_index (patches, pindex);
5330 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5331 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5332 patch_info->type = MONO_PATCH_INFO_NONE;
5337 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5338 /* Stored in a GOT slot initialized at module load time */
5339 patch_info->type = MONO_PATCH_INFO_NONE;
5343 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5344 /* Stored in a GOT slot initialized at module load time */
5345 patch_info->type = MONO_PATCH_INFO_NONE;
5349 if (is_plt_patch (patch_info)) {
5350 /* Calls are made through the PLT */
5351 patch_info->type = MONO_PATCH_INFO_NONE;
5359 g_assert (cfg->has_got_slots);
5361 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5363 acfg->stats.info_size += p - buf;
5365 g_assert (p - buf < buf_size);
5367 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5372 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5374 guint32 cache_index;
5377 /* Reuse the unwind module to canonize and store unwind info entries */
5378 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5380 /* Use +/- 1 to distinguish 0s from missing entries */
5381 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5389 * It would be easier to use assembler symbols, but the caller needs an
5392 offset = acfg->unwind_info_offset;
5393 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5394 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5397 encode_value (encoded_len, p, &p);
5399 acfg->unwind_info_offset += encoded_len + (p - buf);
5405 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5408 int i, k, buf_size, method_index;
5409 guint32 debug_info_size, seq_points_size;
5411 MonoMethodHeader *header;
5412 guint8 *p, *buf, *debug_info;
5413 MonoJitInfo *jinfo = cfg->jit_info;
5415 gboolean use_unwind_ops = FALSE;
5416 MonoSeqPointInfo *seq_points;
5418 method = cfg->orig_method;
5419 code = cfg->native_code;
5420 header = cfg->header;
5422 method_index = get_method_index (acfg, method);
5424 if (!acfg->aot_opts.nodebug) {
5425 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5428 debug_info_size = 0;
5431 seq_points = cfg->seq_point_info;
5433 seq_points_size = (cfg->gen_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5435 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5436 p = buf = g_malloc (buf_size);
5438 use_unwind_ops = cfg->unwind_ops != NULL;
5440 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);
5442 encode_value (flags, p, &p);
5444 if (use_unwind_ops) {
5445 guint32 encoded_len;
5447 guint32 unwind_desc;
5449 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5451 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5452 encode_value (unwind_desc, p, &p);
5454 encode_value (jinfo->unwind_info, p, &p);
5457 /*Encode the number of holes before the number of clauses to make decoding easier*/
5458 if (jinfo->has_try_block_holes) {
5459 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5460 encode_value (table->num_holes, p, &p);
5463 if (jinfo->has_arch_eh_info) {
5465 * In AOT mode, the code length is calculated from the address of the previous method,
5466 * which could include alignment padding, so calculating the start of the epilog as
5467 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5469 encode_value (jinfo->code_size, p, &p);
5472 /* Exception table */
5473 if (cfg->compile_llvm) {
5475 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5476 * since the information is only available to llc. Instead, we let llc save the data
5477 * into the LSDA, and read it from there at runtime.
5479 /* The assembly might be CIL stripped so emit the data ourselves */
5480 if (header->num_clauses)
5481 encode_value (header->num_clauses, p, &p);
5483 for (k = 0; k < header->num_clauses; ++k) {
5484 MonoExceptionClause *clause;
5486 clause = &header->clauses [k];
5488 encode_value (clause->flags, p, &p);
5489 if (clause->data.catch_class) {
5490 encode_value (1, p, &p);
5491 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5493 encode_value (0, p, &p);
5496 /* Emit a list of nesting clauses */
5497 for (i = 0; i < header->num_clauses; ++i) {
5499 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5501 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5503 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5504 encode_value (i, p, &p);
5506 encode_value (-1, p, &p);
5509 if (jinfo->num_clauses)
5510 encode_value (jinfo->num_clauses, p, &p);
5512 for (k = 0; k < jinfo->num_clauses; ++k) {
5513 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5515 encode_value (ei->flags, p, &p);
5516 encode_value (ei->exvar_offset, p, &p);
5518 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5519 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5521 if (ei->data.catch_class) {
5525 buf2 = g_malloc (4096);
5527 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5529 g_assert (len < 4096);
5530 encode_value (len, p, &p);
5531 memcpy (p, buf2, len);
5535 encode_value (0, p, &p);
5539 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5540 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5541 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5545 if (jinfo->has_try_block_holes) {
5546 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5547 for (i = 0; i < table->num_holes; ++i) {
5548 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5549 encode_value (hole->clause, p, &p);
5550 encode_value (hole->length, p, &p);
5551 encode_value (hole->offset, p, &p);
5555 if (jinfo->has_arch_eh_info) {
5556 MonoArchEHJitInfo *eh_info;
5558 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5559 encode_value (eh_info->stack_size, p, &p);
5560 encode_value (eh_info->epilog_size, p, &p);
5563 if (jinfo->has_generic_jit_info) {
5564 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5565 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5571 encode_value (gi->nlocs, p, &p);
5573 for (i = 0; i < gi->nlocs; ++i) {
5574 MonoDwarfLocListEntry *entry = &gi->locations [i];
5576 encode_value (entry->is_reg ? 1 : 0, p, &p);
5577 encode_value (entry->reg, p, &p);
5579 encode_value (entry->offset, p, &p);
5581 g_assert (entry->from == 0);
5583 encode_value (entry->from, p, &p);
5584 encode_value (entry->to, p, &p);
5587 if (!cfg->compile_llvm) {
5588 encode_value (gi->has_this ? 1 : 0, p, &p);
5589 encode_value (gi->this_reg, p, &p);
5590 encode_value (gi->this_offset, p, &p);
5595 * Need to encode jinfo->method too, since it is not equal to 'method'
5596 * when using generic sharing.
5598 buf2 = g_malloc (4096);
5600 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5602 g_assert (len < 4096);
5603 encode_value (len, p, &p);
5604 memcpy (p, buf2, len);
5608 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5609 MonoMethodInflated *inflated;
5610 MonoGenericContext *context;
5611 MonoGenericInst *inst;
5613 g_assert (jinfo->d.method->is_inflated);
5614 inflated = (MonoMethodInflated*)jinfo->d.method;
5615 context = &inflated->context;
5617 encode_value (1, p, &p);
5618 if (context->class_inst) {
5619 inst = context->class_inst;
5621 encode_value (inst->type_argc, p, &p);
5622 for (i = 0; i < inst->type_argc; ++i)
5623 encode_value (gsctx->var_is_vt [i], p, &p);
5625 encode_value (0, p, &p);
5627 if (context->method_inst) {
5628 inst = context->method_inst;
5630 encode_value (inst->type_argc, p, &p);
5631 for (i = 0; i < inst->type_argc; ++i)
5632 encode_value (gsctx->mvar_is_vt [i], p, &p);
5634 encode_value (0, p, &p);
5637 encode_value (0, p, &p);
5642 p += seq_point_info_write (seq_points, p);
5644 g_assert (debug_info_size < buf_size);
5646 encode_value (debug_info_size, p, &p);
5647 if (debug_info_size) {
5648 memcpy (p, debug_info, debug_info_size);
5649 p += debug_info_size;
5650 g_free (debug_info);
5655 encode_value (cfg->gc_map_size, p, &p);
5656 /* The GC map requires 4 bytes of alignment */
5657 while ((gsize)p % 4)
5659 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5660 p += cfg->gc_map_size;
5663 acfg->stats.ex_info_size += p - buf;
5665 g_assert (p - buf < buf_size);
5668 /* The GC Map requires 4 byte alignment */
5669 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5674 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5677 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5679 int i, buf_size, res;
5680 gboolean no_special_static, cant_encode;
5681 gpointer iter = NULL;
5684 mono_error_cleanup (&error);
5688 p = buf = g_malloc (buf_size);
5690 /* Mark as unusable */
5691 encode_value (-1, p, &p);
5693 res = add_to_blob (acfg, buf, p - buf);
5699 buf_size = 10240 + (klass->vtable_size * 16);
5700 p = buf = g_malloc (buf_size);
5704 mono_class_init (klass);
5706 mono_class_get_nested_types (klass, &iter);
5707 g_assert (klass->nested_classes_inited);
5709 mono_class_setup_vtable (klass);
5712 * Emit all the information which is required for creating vtables so
5713 * the runtime does not need to create the MonoMethod structures which
5714 * take up a lot of space.
5717 no_special_static = !mono_class_has_special_static_fields (klass);
5719 /* Check whenever we have enough info to encode the vtable */
5720 cant_encode = FALSE;
5721 for (i = 0; i < klass->vtable_size; ++i) {
5722 MonoMethod *cm = klass->vtable [i];
5724 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5728 mono_class_has_finalizer (klass);
5730 if (klass->generic_container || cant_encode) {
5731 encode_value (-1, p, &p);
5733 encode_value (klass->vtable_size, p, &p);
5734 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);
5735 if (klass->has_cctor)
5736 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5737 if (klass->has_finalize)
5738 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5740 encode_value (klass->instance_size, p, &p);
5741 encode_value (mono_class_data_size (klass), p, &p);
5742 encode_value (klass->packing_size, p, &p);
5743 encode_value (klass->min_align, p, &p);
5745 for (i = 0; i < klass->vtable_size; ++i) {
5746 MonoMethod *cm = klass->vtable [i];
5749 encode_method_ref (acfg, cm, p, &p);
5751 encode_value (0, p, &p);
5755 acfg->stats.class_info_size += p - buf;
5757 g_assert (p - buf < buf_size);
5758 res = add_to_blob (acfg, buf, p - buf);
5765 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5767 char *debug_sym = NULL;
5771 if (acfg->llvm_separate && llvm_acfg->aot_opts.static_link) {
5772 /* Need to add a prefix to create unique symbols */
5773 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5775 prefix = g_strdup ("plt_");
5779 case MONO_PATCH_INFO_METHOD:
5780 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5782 case MONO_PATCH_INFO_INTERNAL_METHOD:
5783 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5785 case MONO_PATCH_INFO_CLASS_INIT:
5786 s = mono_type_get_name (&ji->data.klass->byval_arg);
5787 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5790 case MONO_PATCH_INFO_RGCTX_FETCH:
5791 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5793 case MONO_PATCH_INFO_ICALL_ADDR: {
5794 char *s = get_debug_sym (ji->data.method, "", cache);
5796 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5800 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5801 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5803 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5804 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5812 return sanitize_symbol (acfg, debug_sym);
5816 * Calls made from AOTed code are routed through a table of jumps similar to the
5817 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5818 * control to the AOT runtime through a trampoline.
5821 emit_plt (MonoAotCompile *acfg)
5827 sprintf (symbol, "plt");
5829 emit_section_change (acfg, ".text", 0);
5830 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5831 emit_label (acfg, symbol);
5832 emit_label (acfg, acfg->plt_symbol);
5834 for (i = 0; i < acfg->plt_offset; ++i) {
5835 char *debug_sym = NULL;
5836 MonoPltEntry *plt_entry = NULL;
5841 * The first plt entry is unused.
5845 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5848 debug_sym = plt_entry->debug_sym;
5850 if (acfg->thumb_mixed && !plt_entry->jit_used)
5851 /* Emit only a thumb version */
5854 /* Skip plt entries not actually called */
5855 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5858 if (acfg->llvm && !acfg->thumb_mixed) {
5859 emit_label (acfg, plt_entry->llvm_symbol);
5860 if (acfg->llvm_separate) {
5861 emit_global (acfg, plt_entry->llvm_symbol, TRUE);
5862 #if defined(TARGET_MACH)
5863 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5869 if (acfg->need_no_dead_strip) {
5870 emit_unset_mode (acfg);
5871 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5873 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5874 emit_label (acfg, debug_sym);
5877 emit_label (acfg, plt_entry->symbol);
5879 arch_emit_plt_entry (acfg, i);
5882 emit_symbol_size (acfg, debug_sym, ".");
5885 if (acfg->thumb_mixed) {
5886 /* Make sure the ARM symbols don't alias the thumb ones */
5887 emit_zero_bytes (acfg, 16);
5890 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5893 for (i = 0; i < acfg->plt_offset; ++i) {
5894 char *debug_sym = NULL;
5895 MonoPltEntry *plt_entry = NULL;
5901 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5904 /* Skip plt entries not actually called by LLVM code */
5905 if (!plt_entry->llvm_used)
5908 if (acfg->aot_opts.write_symbols) {
5909 if (plt_entry->debug_sym)
5910 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5914 #if defined(TARGET_MACH)
5915 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5916 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5918 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5919 emit_label (acfg, debug_sym);
5921 fprintf (acfg->fp, "\n.thumb_func\n");
5923 emit_label (acfg, plt_entry->llvm_symbol);
5925 arch_emit_llvm_plt_entry (acfg, i);
5928 emit_symbol_size (acfg, debug_sym, ".");
5934 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5936 sprintf (symbol, "plt_end");
5937 emit_label (acfg, symbol);
5941 * emit_trampoline_full:
5943 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5944 * create_jit_info_for_trampoline ().
5946 static G_GNUC_UNUSED void
5947 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5949 char start_symbol [256];
5950 char end_symbol [256];
5952 guint32 buf_size, info_offset;
5953 MonoJumpInfo *patch_info;
5966 code_size = info->code_size;
5968 unwind_ops = info->unwind_ops;
5970 #ifdef __native_client_codegen__
5971 mono_nacl_fix_patches (code, ji);
5976 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5978 emit_section_change (acfg, ".text", 0);
5979 emit_global (acfg, start_symbol, TRUE);
5980 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
5981 emit_label (acfg, start_symbol);
5983 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5984 emit_label (acfg, symbol);
5987 * The code should access everything through the GOT, so we pass
5990 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5992 emit_symbol_size (acfg, start_symbol, ".");
5995 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5996 emit_label (acfg, end_symbol);
6001 /* Sort relocations */
6002 patches = g_ptr_array_new ();
6003 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6004 if (patch_info->type != MONO_PATCH_INFO_NONE)
6005 g_ptr_array_add (patches, patch_info);
6006 g_ptr_array_sort (patches, compare_patches);
6008 buf_size = patches->len * 128 + 128;
6009 buf = g_malloc (buf_size);
6012 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6013 g_assert (p - buf < buf_size);
6015 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6017 info_offset = add_to_blob (acfg, buf, p - buf);
6019 emit_section_change (acfg, RODATA_SECT, 0);
6020 emit_global (acfg, symbol, FALSE);
6021 emit_label (acfg, symbol);
6023 emit_int32 (acfg, info_offset);
6027 guint32 encoded_len;
6031 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6033 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6034 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6037 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6038 emit_int32 (acfg, uw_offset);
6041 /* Emit debug info */
6045 sprintf (symbol, "%s", name);
6046 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6049 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6053 static G_GNUC_UNUSED void
6054 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6056 emit_trampoline_full (acfg, got_offset, info, FALSE);
6060 emit_trampolines (MonoAotCompile *acfg)
6063 char end_symbol [256];
6064 int i, tramp_got_offset;
6065 MonoAotTrampoline ntype;
6066 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6070 if (!acfg->aot_opts.full_aot)
6073 g_assert (acfg->image->assembly);
6075 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6076 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6077 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6078 MonoTrampInfo *info;
6081 * Emit the generic trampolines.
6083 * We could save some code by treating the generic trampolines as a wrapper
6084 * method, but that approach has its own complexities, so we choose the simpler
6087 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6088 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6089 #ifdef DISABLE_REMOTING
6090 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6093 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6094 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6097 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6098 emit_trampoline (acfg, acfg->got_offset, info);
6101 mono_arch_get_nullified_class_init_trampoline (&info);
6102 emit_trampoline (acfg, acfg->got_offset, info);
6103 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6104 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6105 emit_trampoline (acfg, acfg->got_offset, info);
6106 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6107 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6108 emit_trampoline (acfg, acfg->got_offset, info);
6110 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6111 emit_trampoline (acfg, acfg->got_offset, info);
6114 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6115 emit_trampoline (acfg, acfg->got_offset, info);
6117 /* Emit the exception related code pieces */
6118 mono_arch_get_restore_context (&info, TRUE);
6119 emit_trampoline (acfg, acfg->got_offset, info);
6120 mono_arch_get_call_filter (&info, TRUE);
6121 emit_trampoline (acfg, acfg->got_offset, info);
6122 mono_arch_get_throw_exception (&info, TRUE);
6123 emit_trampoline (acfg, acfg->got_offset, info);
6124 mono_arch_get_rethrow_exception (&info, TRUE);
6125 emit_trampoline (acfg, acfg->got_offset, info);
6126 mono_arch_get_throw_corlib_exception (&info, TRUE);
6127 emit_trampoline (acfg, acfg->got_offset, info);
6129 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6130 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6132 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6134 /* Create a separate out trampoline for more information in stack traces */
6135 info->name = g_strdup ("gsharedvt_out_trampoline");
6136 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6140 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6142 GSList *l = mono_arch_get_trampolines (TRUE);
6145 MonoTrampInfo *info = l->data;
6147 emit_trampoline (acfg, acfg->got_offset, info);
6153 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6156 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6157 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6158 emit_trampoline (acfg, acfg->got_offset, info);
6160 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6161 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6162 emit_trampoline (acfg, acfg->got_offset, info);
6165 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6166 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6167 emit_trampoline (acfg, acfg->got_offset, info);
6173 /* delegate_invoke_impl trampolines */
6174 l = mono_arch_get_delegate_invoke_impls ();
6176 MonoTrampInfo *info = l->data;
6178 emit_trampoline (acfg, acfg->got_offset, info);
6183 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6185 /* Emit trampolines which are numerous */
6188 * These include the following:
6189 * - specific trampolines
6190 * - static rgctx invoke trampolines
6192 * These trampolines have the same code, they are parameterized by GOT
6194 * They are defined in this file, in the arch_... routines instead of
6195 * in tramp-<ARCH>.c, since it is easier to do it this way.
6199 * When running in aot-only mode, we can't create specific trampolines at
6200 * runtime, so we create a few, and save them in the AOT file.
6201 * Normal trampolines embed their argument as a literal inside the
6202 * trampoline code, we can't do that here, so instead we embed an offset
6203 * which needs to be added to the trampoline address to get the address of
6204 * the GOT slot which contains the argument value.
6205 * The generated trampolines jump to the generic trampolines using another
6206 * GOT slot, which will be setup by the AOT loader to point to the
6207 * generic trampoline code of the given type.
6211 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6215 emit_section_change (acfg, ".text", 0);
6217 tramp_got_offset = acfg->got_offset;
6219 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6221 case MONO_AOT_TRAMP_SPECIFIC:
6222 sprintf (symbol, "specific_trampolines");
6224 case MONO_AOT_TRAMP_STATIC_RGCTX:
6225 sprintf (symbol, "static_rgctx_trampolines");
6227 case MONO_AOT_TRAMP_IMT_THUNK:
6228 sprintf (symbol, "imt_thunks");
6230 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6231 sprintf (symbol, "gsharedvt_arg_trampolines");
6234 g_assert_not_reached ();
6237 sprintf (end_symbol, "%s_e", symbol);
6239 if (acfg->aot_opts.write_symbols)
6240 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6242 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6243 emit_label (acfg, symbol);
6245 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6247 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6251 case MONO_AOT_TRAMP_SPECIFIC:
6252 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6253 tramp_got_offset += 2;
6255 case MONO_AOT_TRAMP_STATIC_RGCTX:
6256 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6257 tramp_got_offset += 2;
6259 case MONO_AOT_TRAMP_IMT_THUNK:
6260 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6261 tramp_got_offset += 1;
6263 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6264 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6265 tramp_got_offset += 2;
6268 g_assert_not_reached ();
6270 #ifdef __native_client_codegen__
6271 /* align to avoid 32-byte boundary crossings */
6272 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6275 if (!acfg->trampoline_size [ntype]) {
6276 g_assert (tramp_size);
6277 acfg->trampoline_size [ntype] = tramp_size;
6281 emit_label (acfg, end_symbol);
6282 emit_int32 (acfg, 0);
6285 arch_emit_specific_trampoline_pages (acfg);
6287 /* Reserve some entries at the end of the GOT for our use */
6288 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6291 acfg->got_offset += acfg->num_trampoline_got_entries;
6295 str_begins_with (const char *str1, const char *str2)
6297 int len = strlen (str2);
6298 return strncmp (str1, str2, len) == 0;
6302 mono_aot_readonly_field_override (MonoClassField *field)
6305 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6306 char *p = rdv->name;
6308 len = strlen (field->parent->name_space);
6309 if (strncmp (p, field->parent->name_space, len))
6314 len = strlen (field->parent->name);
6315 if (strncmp (p, field->parent->name, len))
6320 if (strcmp (p, field->name))
6322 switch (rdv->type) {
6324 return &rdv->value.i1;
6326 return &rdv->value.i2;
6328 return &rdv->value.i4;
6337 add_readonly_value (MonoAotOptions *opts, const char *val)
6342 /* the format of val is:
6343 * namespace.typename.fieldname=type/value
6344 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6346 fval = strrchr (val, '/');
6348 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6351 tval = strrchr (val, '=');
6353 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6356 rdv = g_new0 (ReadOnlyValue, 1);
6357 rdv->name = g_malloc0 (tval - val + 1);
6358 memcpy (rdv->name, val, tval - val);
6361 if (strncmp (tval, "i1", 2) == 0) {
6362 rdv->value.i1 = atoi (fval);
6363 rdv->type = MONO_TYPE_I1;
6364 } else if (strncmp (tval, "i2", 2) == 0) {
6365 rdv->value.i2 = atoi (fval);
6366 rdv->type = MONO_TYPE_I2;
6367 } else if (strncmp (tval, "i4", 2) == 0) {
6368 rdv->value.i4 = atoi (fval);
6369 rdv->type = MONO_TYPE_I4;
6371 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6374 rdv->next = readonly_values;
6375 readonly_values = rdv;
6379 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6381 gchar **args, **ptr;
6383 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6384 for (ptr = args; ptr && *ptr; ptr ++) {
6385 const char *arg = *ptr;
6387 if (str_begins_with (arg, "outfile=")) {
6388 opts->outfile = g_strdup (arg + strlen ("outfile="));
6389 } else if (str_begins_with (arg, "llvm-outfile=")) {
6390 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6391 } else if (str_begins_with (arg, "save-temps")) {
6392 opts->save_temps = TRUE;
6393 } else if (str_begins_with (arg, "keep-temps")) {
6394 opts->save_temps = TRUE;
6395 } else if (str_begins_with (arg, "write-symbols")) {
6396 opts->write_symbols = TRUE;
6397 } else if (str_begins_with (arg, "no-write-symbols")) {
6398 opts->write_symbols = FALSE;
6399 } else if (str_begins_with (arg, "metadata-only")) {
6400 opts->metadata_only = TRUE;
6401 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6402 opts->bind_to_runtime_version = TRUE;
6403 } else if (str_begins_with (arg, "full")) {
6404 opts->full_aot = TRUE;
6405 } else if (str_begins_with (arg, "threads=")) {
6406 opts->nthreads = atoi (arg + strlen ("threads="));
6407 } else if (str_begins_with (arg, "static")) {
6408 opts->static_link = TRUE;
6409 opts->no_dlsym = TRUE;
6410 } else if (str_begins_with (arg, "asmonly")) {
6411 opts->asm_only = TRUE;
6412 } else if (str_begins_with (arg, "asmwriter")) {
6413 opts->asm_writer = TRUE;
6414 } else if (str_begins_with (arg, "nodebug")) {
6415 opts->nodebug = TRUE;
6416 } else if (str_begins_with (arg, "dwarfdebug")) {
6417 opts->dwarf_debug = TRUE;
6418 } else if (str_begins_with (arg, "nopagetrampolines")) {
6419 opts->use_trampolines_page = FALSE;
6420 } else if (str_begins_with (arg, "ntrampolines=")) {
6421 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6422 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6423 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6424 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6425 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6426 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6427 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6428 } else if (str_begins_with (arg, "autoreg")) {
6429 opts->autoreg = TRUE;
6430 } else if (str_begins_with (arg, "tool-prefix=")) {
6431 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6432 } else if (str_begins_with (arg, "soft-debug")) {
6433 opts->soft_debug = TRUE;
6434 } else if (str_begins_with (arg, "direct-pinvoke")) {
6435 opts->direct_pinvoke = TRUE;
6436 } else if (str_begins_with (arg, "direct-icalls")) {
6437 opts->direct_icalls = TRUE;
6438 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6439 } else if (str_begins_with (arg, "iphone-abi")) {
6440 // older full-aot users did depend on this.
6442 } else if (str_begins_with (arg, "no-direct-calls")) {
6443 opts->no_direct_calls = TRUE;
6444 } else if (str_begins_with (arg, "print-skipped")) {
6445 opts->print_skipped_methods = TRUE;
6446 } else if (str_begins_with (arg, "stats")) {
6448 } else if (str_begins_with (arg, "no-instances")) {
6449 opts->no_instances = TRUE;
6450 } else if (str_begins_with (arg, "log-generics")) {
6451 opts->log_generics = TRUE;
6452 } else if (str_begins_with (arg, "log-instances=")) {
6453 opts->log_instances = TRUE;
6454 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6455 } else if (str_begins_with (arg, "log-instances")) {
6456 opts->log_instances = TRUE;
6457 } else if (str_begins_with (arg, "internal-logfile=")) {
6458 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6459 } else if (str_begins_with (arg, "mtriple=")) {
6460 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6461 } else if (str_begins_with (arg, "llvm-path=")) {
6462 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6463 } else if (!strcmp (arg, "llvm")) {
6465 } else if (str_begins_with (arg, "readonly-value=")) {
6466 add_readonly_value (opts, arg + strlen ("readonly-value="));
6467 } else if (str_begins_with (arg, "info")) {
6468 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6470 } else if (str_begins_with (arg, "gc-maps")) {
6471 mini_gc_enable_gc_maps_for_aot ();
6472 } else if (str_begins_with (arg, "dump")) {
6473 opts->dump_json = TRUE;
6474 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6475 printf ("Supported options for --aot:\n");
6476 printf (" outfile=\n");
6477 printf (" llvm-outfile=\n");
6478 printf (" save-temps\n");
6479 printf (" keep-temps\n");
6480 printf (" write-symbols\n");
6481 printf (" metadata-only\n");
6482 printf (" bind-to-runtime-version\n");
6484 printf (" threads=\n");
6485 printf (" static\n");
6486 printf (" asmonly\n");
6487 printf (" asmwriter\n");
6488 printf (" nodebug\n");
6489 printf (" dwarfdebug\n");
6490 printf (" ntrampolines=\n");
6491 printf (" nrgctx-trampolines=\n");
6492 printf (" nimt-trampolines=\n");
6493 printf (" ngsharedvt-trampolines=\n");
6494 printf (" autoreg\n");
6495 printf (" tool-prefix=\n");
6496 printf (" readonly-value=\n");
6497 printf (" soft-debug\n");
6498 printf (" gc-maps\n");
6499 printf (" print-skipped\n");
6500 printf (" no-instances\n");
6501 printf (" stats\n");
6504 printf (" help/?\n");
6507 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6512 if (opts->use_trampolines_page) {
6513 opts->ntrampolines = 0;
6514 opts->nrgctx_trampolines = 0;
6515 opts->nimt_trampolines = 0;
6516 opts->ngsharedvt_arg_trampolines = 0;
6522 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6524 MonoMethod *method = (MonoMethod*)key;
6525 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6526 MonoAotCompile *acfg = user_data;
6527 MonoJumpInfoToken *new_ji;
6529 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6530 new_ji->image = ji->image;
6531 new_ji->token = ji->token;
6532 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6536 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6538 if (klass->type_token)
6540 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6543 return can_encode_class (acfg, klass->element_class);
6548 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6550 if (method->wrapper_type) {
6551 switch (method->wrapper_type) {
6552 case MONO_WRAPPER_NONE:
6553 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6554 case MONO_WRAPPER_XDOMAIN_INVOKE:
6555 case MONO_WRAPPER_STFLD:
6556 case MONO_WRAPPER_LDFLD:
6557 case MONO_WRAPPER_LDFLDA:
6558 case MONO_WRAPPER_LDFLD_REMOTE:
6559 case MONO_WRAPPER_STFLD_REMOTE:
6560 case MONO_WRAPPER_STELEMREF:
6561 case MONO_WRAPPER_ISINST:
6562 case MONO_WRAPPER_PROXY_ISINST:
6563 case MONO_WRAPPER_ALLOC:
6564 case MONO_WRAPPER_REMOTING_INVOKE:
6565 case MONO_WRAPPER_UNKNOWN:
6566 case MONO_WRAPPER_WRITE_BARRIER:
6567 case MONO_WRAPPER_DELEGATE_INVOKE:
6568 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6569 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6570 case MONO_WRAPPER_SYNCHRONIZED:
6572 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6573 case MONO_WRAPPER_CASTCLASS: {
6574 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6583 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6587 if (!method->token) {
6588 /* The method is part of a constructed type like Int[,].Set (). */
6589 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6590 if (method->klass->rank)
6600 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6602 switch (patch_info->type) {
6603 case MONO_PATCH_INFO_METHOD:
6604 case MONO_PATCH_INFO_METHODCONST:
6605 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6606 MonoMethod *method = patch_info->data.method;
6608 return can_encode_method (acfg, method);
6610 case MONO_PATCH_INFO_VTABLE:
6611 case MONO_PATCH_INFO_CLASS_INIT:
6612 case MONO_PATCH_INFO_CLASS:
6613 case MONO_PATCH_INFO_IID:
6614 case MONO_PATCH_INFO_ADJUSTED_IID:
6615 if (!can_encode_class (acfg, patch_info->data.klass)) {
6616 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6620 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6621 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6622 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6627 case MONO_PATCH_INFO_RGCTX_FETCH: {
6628 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6630 if (!can_encode_method (acfg, entry->method))
6632 if (!can_encode_patch (acfg, entry->data))
6646 * AOT compile a given method.
6647 * This function might be called by multiple threads, so it must be thread-safe.
6650 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6653 MonoJumpInfo *patch_info;
6656 MonoMethod *wrapped;
6659 if (acfg->aot_opts.metadata_only)
6662 mono_acfg_lock (acfg);
6663 index = get_method_index (acfg, method);
6664 mono_acfg_unlock (acfg);
6666 /* fixme: maybe we can also precompile wrapper methods */
6667 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6668 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6669 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6670 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6674 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6677 wrapped = mono_marshal_method_from_wrapper (method);
6678 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6679 // FIXME: The wrapper should be generic too, but it is not
6682 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6685 InterlockedIncrement (&acfg->stats.mcount);
6688 if (method->is_generic || method->klass->generic_container) {
6689 InterlockedIncrement (&acfg->stats.genericcount);
6694 //acfg->aot_opts.print_skipped_methods = TRUE;
6697 * Since these methods are the only ones which are compiled with
6698 * AOT support, and they are not used by runtime startup/shutdown code,
6699 * the runtime will not see AOT methods during AOT compilation,so it
6700 * does not need to support them by creating a fake GOT etc.
6702 flags = JIT_FLAG_AOT;
6703 if (acfg->aot_opts.full_aot)
6704 flags |= JIT_FLAG_FULL_AOT;
6706 flags |= JIT_FLAG_LLVM;
6707 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6708 mono_loader_clear_error ();
6710 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6711 if (acfg->aot_opts.print_skipped_methods)
6712 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6713 InterlockedIncrement (&acfg->stats.genericcount);
6716 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6717 if (acfg->aot_opts.print_skipped_methods)
6718 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6719 /* Let the exception happen at runtime */
6723 if (cfg->disable_aot) {
6724 if (acfg->aot_opts.print_skipped_methods)
6725 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6726 InterlockedIncrement (&acfg->stats.ocount);
6727 mono_destroy_compile (cfg);
6730 cfg->method_index = index;
6732 /* Nullify patches which need no aot processing */
6733 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6734 switch (patch_info->type) {
6735 case MONO_PATCH_INFO_LABEL:
6736 case MONO_PATCH_INFO_BB:
6737 patch_info->type = MONO_PATCH_INFO_NONE;
6744 /* Collect method->token associations from the cfg */
6745 mono_acfg_lock (acfg);
6746 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6747 mono_acfg_unlock (acfg);
6748 g_hash_table_destroy (cfg->token_info_hash);
6749 cfg->token_info_hash = NULL;
6752 * Check for absolute addresses.
6755 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6756 switch (patch_info->type) {
6757 case MONO_PATCH_INFO_ABS:
6758 /* unable to handle this */
6767 if (acfg->aot_opts.print_skipped_methods)
6768 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6769 InterlockedIncrement (&acfg->stats.abscount);
6770 mono_destroy_compile (cfg);
6774 /* Lock for the rest of the code */
6775 mono_acfg_lock (acfg);
6778 * Check for methods/klasses we can't encode.
6781 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6782 if (!can_encode_patch (acfg, patch_info))
6787 if (acfg->aot_opts.print_skipped_methods)
6788 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6789 acfg->stats.ocount++;
6790 mono_destroy_compile (cfg);
6791 mono_acfg_unlock (acfg);
6795 if (method->is_inflated && acfg->aot_opts.log_instances) {
6796 if (acfg->instances_logfile)
6797 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6799 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6802 /* Adds generic instances referenced by this method */
6804 * The depth is used to avoid infinite loops when generic virtual recursion is
6807 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6808 if (!acfg->aot_opts.no_instances && depth < 32) {
6809 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6810 switch (patch_info->type) {
6811 case MONO_PATCH_INFO_METHOD: {
6812 MonoMethod *m = patch_info->data.method;
6813 if (m->is_inflated) {
6814 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6815 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6816 !method_has_type_vars (m)) {
6817 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6818 if (acfg->aot_opts.full_aot)
6819 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6821 add_extra_method_with_depth (acfg, m, depth + 1);
6822 add_types_from_method_header (acfg, m);
6825 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6827 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6828 add_extra_method_with_depth (acfg, m, depth + 1);
6831 case MONO_PATCH_INFO_VTABLE: {
6832 MonoClass *klass = patch_info->data.klass;
6834 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6835 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6838 case MONO_PATCH_INFO_SFLDA: {
6839 MonoClass *klass = patch_info->data.field->parent;
6841 /* The .cctor needs to run at runtime. */
6842 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6843 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6852 /* Determine whenever the method has GOT slots */
6853 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6854 switch (patch_info->type) {
6855 case MONO_PATCH_INFO_GOT_OFFSET:
6856 case MONO_PATCH_INFO_NONE:
6857 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6859 case MONO_PATCH_INFO_IMAGE:
6860 /* The assembly is stored in GOT slot 0 */
6861 if (patch_info->data.image != acfg->image)
6862 cfg->has_got_slots = TRUE;
6865 if (!is_plt_patch (patch_info))
6866 cfg->has_got_slots = TRUE;
6871 if (!cfg->has_got_slots)
6872 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6875 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6877 /* Make a copy of the patch info which is in the mempool */
6879 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6881 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6882 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6885 patches = new_patch_info;
6887 patches_end->next = new_patch_info;
6888 patches_end = new_patch_info;
6890 cfg->patch_info = patches;
6892 /* Make a copy of the unwind info */
6894 GSList *l, *unwind_ops;
6898 for (l = cfg->unwind_ops; l; l = l->next) {
6899 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6900 memcpy (op, l->data, sizeof (MonoUnwindOp));
6901 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6903 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6905 /* Make a copy of the argument/local info */
6907 MonoInst **args, **locals;
6908 MonoMethodSignature *sig;
6909 MonoMethodHeader *header;
6912 sig = mono_method_signature (method);
6913 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6914 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6915 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6916 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6920 header = mono_method_get_header (method);
6921 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6922 for (i = 0; i < header->num_locals; ++i) {
6923 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6924 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6926 cfg->locals = locals;
6929 /* Free some fields used by cfg to conserve memory */
6930 mono_mempool_destroy (cfg->mempool);
6931 cfg->mempool = NULL;
6932 g_free (cfg->varinfo);
6933 cfg->varinfo = NULL;
6937 mono_regstate_free (cfg->rs);
6941 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6943 while (index >= acfg->cfgs_size) {
6944 MonoCompile **new_cfgs;
6947 new_size = acfg->cfgs_size * 2;
6948 new_cfgs = g_new0 (MonoCompile*, new_size);
6949 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6950 g_free (acfg->cfgs);
6951 acfg->cfgs = new_cfgs;
6952 acfg->cfgs_size = new_size;
6954 acfg->cfgs [index] = cfg;
6956 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6959 if (cfg->orig_method->wrapper_type)
6960 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6963 mono_acfg_unlock (acfg);
6965 InterlockedIncrement (&acfg->stats.ccount);
6969 compile_thread_main (gpointer *user_data)
6971 MonoDomain *domain = user_data [0];
6972 MonoAotCompile *acfg = user_data [1];
6973 GPtrArray *methods = user_data [2];
6976 mono_thread_attach (domain);
6978 for (i = 0; i < methods->len; ++i)
6979 compile_method (acfg, g_ptr_array_index (methods, i));
6983 load_profile_files (MonoAotCompile *acfg)
6987 int file_index, res, method_index, i;
6990 GList *unordered, *l;
6995 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6997 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7002 infile = fopen (tmp, "r");
7005 printf ("Using profile data file '%s'\n", tmp);
7010 res = fscanf (infile, "%32s\n", ver);
7011 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7012 printf ("Profile file has wrong version or invalid.\n");
7019 MonoMethodDesc *desc;
7022 if (fgets (name, 1023, infile) == NULL)
7025 /* Kill the newline */
7026 if (strlen (name) > 0)
7027 name [strlen (name) - 1] = '\0';
7029 desc = mono_method_desc_new (name, TRUE);
7031 method = mono_method_desc_search_in_image (desc, acfg->image);
7033 if (method && mono_method_get_token (method)) {
7034 token = mono_method_get_token (method);
7035 method_index = mono_metadata_token_index (token) - 1;
7038 for (i = 0; i < acfg->method_order->len; ++i) {
7039 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7045 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7047 //printf ("No method found matching '%s'.\n", name);
7053 /* Add missing methods */
7055 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7057 for (i = 0; i < acfg->method_order->len; ++i) {
7058 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7064 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7066 unordered = g_list_reverse (unordered);
7067 for (l = unordered; l; l = l->next)
7068 g_ptr_array_add (acfg->method_order, l->data);
7071 /* Used by the LLVM backend */
7073 mono_aot_get_got_offset (MonoJumpInfo *ji)
7075 return get_got_offset (llvm_acfg, TRUE, ji);
7079 mono_aot_get_method_name (MonoCompile *cfg)
7081 if (llvm_acfg->aot_opts.static_link)
7082 /* Include the assembly name too to avoid duplicate symbol errors */
7083 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7085 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7089 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7091 return is_direct_callable (llvm_acfg, NULL, patch_info);
7095 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7097 MonoPltEntry *plt_entry;
7099 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7100 plt_entry->llvm_used = FALSE;
7104 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7106 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7107 MonoPltEntry *plt_entry;
7110 ji->data.target = data;
7112 if (!can_encode_patch (llvm_acfg, ji))
7115 plt_entry = get_plt_entry (llvm_acfg, ji);
7116 plt_entry->llvm_used = TRUE;
7118 #if defined(TARGET_MACH)
7119 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7121 return g_strdup_printf (plt_entry->llvm_symbol);
7126 mono_aot_get_method_index (MonoMethod *method)
7128 g_assert (llvm_acfg);
7129 return get_method_index (llvm_acfg, method);
7133 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7137 mono_acfg_lock (llvm_acfg);
7138 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7139 mono_acfg_unlock (llvm_acfg);
7149 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7153 emit_llvm_file (MonoAotCompile *acfg)
7155 char *command, *opts, *tempbc, *output_fname;
7157 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7158 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7162 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7163 * a lot of time, and doesn't seem to save much space.
7164 * The following optimizations cannot be enabled:
7166 * - 'jump-threading' changes our blockaddress references to int constants.
7167 * - 'basiccg' fails because it contains:
7168 * if (CS && !isa<IntrinsicInst>(II)) {
7169 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7170 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7171 * The opt list below was produced by taking the output of:
7172 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7173 * then removing tailcallelim + the global opts.
7174 * strip-dead-prototypes deletes unused intrinsics definitions.
7176 opts = g_strdup ("-instcombine -simplifycfg");
7177 //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");
7178 /* The dse pass is disabled because of #13734 and #17616 */
7180 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7181 * // If we have no DataLayout information around, then the size of the store
7182 * // is inferrable from the pointee type. If they are the same type, then
7183 * // we know that the store is safe.
7184 * if (AA.getDataLayout() == 0 &&
7185 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7186 * return OverwriteComplete;
7187 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7189 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");
7191 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7192 aot_printf (acfg, "Executing opt: %s\n", command);
7193 if (system (command) != 0)
7198 if (!acfg->llc_args)
7199 acfg->llc_args = g_string_new ("");
7201 /* Verbose asm slows down llc greatly */
7202 g_string_append (acfg->llc_args, " -asm-verbose=false");
7204 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7206 if (acfg->aot_opts.mtriple)
7207 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7209 if (acfg->llvm_separate)
7210 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7212 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7213 /* ios requires PIC code now */
7214 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7216 if (llvm_acfg->aot_opts.static_link)
7217 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7219 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7221 unlink (acfg->tmpfname);
7223 if (acfg->llvm_separate) {
7224 if (acfg->llvm_owriter) {
7225 /* Emit an object file directly */
7226 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7227 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7229 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7232 output_fname = g_strdup (acfg->tmpfname);
7234 command = g_strdup_printf ("%sllc %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7236 aot_printf (acfg, "Executing llc: %s\n", command);
7238 if (system (command) != 0)
7245 emit_code (MonoAotCompile *acfg)
7247 int oindex, i, prev_index;
7250 #if defined(TARGET_POWERPC64)
7251 sprintf (symbol, ".Lgot_addr");
7252 emit_section_change (acfg, ".text", 0);
7253 emit_alignment (acfg, 8);
7254 emit_label (acfg, symbol);
7255 emit_pointer (acfg, acfg->got_symbol);
7259 * This global symbol is used to compute the address of each method using the
7260 * code_offsets array. It is also used to compute the memory ranges occupied by
7261 * AOT code, so it must be equal to the address of the first emitted method.
7263 emit_section_change (acfg, ".text", 0);
7264 emit_alignment_code (acfg, 8);
7266 for (i = 0; i < acfg->nmethods; ++i) {
7267 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7268 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7273 if (!acfg->methods_symbol) {
7274 sprintf (symbol, "methods");
7275 emit_label (acfg, symbol);
7276 acfg->methods_symbol = g_strdup (symbol);
7278 emit_label (acfg, "jit_code_start");
7281 * Emit some padding so the local symbol for the first method doesn't have the
7282 * same address as 'methods'.
7284 #if defined(__default_codegen__)
7285 emit_padding (acfg, 16);
7286 #elif defined(__native_client_codegen__)
7288 const int kPaddingSize = 16;
7289 guint8 pad_buffer[kPaddingSize];
7290 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7291 emit_bytes (acfg, pad_buffer, kPaddingSize);
7295 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7299 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7301 cfg = acfg->cfgs [i];
7306 method = cfg->orig_method;
7308 /* Emit unbox trampoline */
7309 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7310 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7312 emit_section_change (acfg, ".text", 0);
7313 #ifdef __native_client_codegen__
7314 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7317 if (acfg->thumb_mixed && cfg->compile_llvm) {
7318 emit_set_thumb_mode (acfg);
7319 fprintf (acfg->fp, "\n.thumb_func\n");
7322 emit_label (acfg, symbol);
7324 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7326 if (acfg->thumb_mixed && cfg->compile_llvm)
7327 emit_set_arm_mode (acfg);
7330 if (cfg->compile_llvm)
7331 acfg->stats.llvm_count ++;
7333 emit_method_code (acfg, cfg);
7336 sprintf (symbol, "methods_end");
7337 emit_section_change (acfg, ".text", 0);
7338 emit_alignment_code (acfg, 8);
7339 emit_label (acfg, symbol);
7341 emit_label (acfg, "jit_code_end");
7343 /* To distinguish it from the next symbol */
7344 emit_padding (acfg, 4);
7347 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7348 * from optimizing them away, since it doesn't see that code_offsets references them.
7349 * JITted methods don't need this since they are referenced using assembler local
7351 * FIXME: This is why write-symbols doesn't work on OSX ?
7353 if (acfg->llvm && acfg->need_no_dead_strip) {
7354 fprintf (acfg->fp, "\n");
7355 for (i = 0; i < acfg->nmethods; ++i) {
7356 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7357 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7362 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7363 * This is PIE code, and the linker can update it if needed.
7365 sprintf (symbol, "method_addresses");
7366 emit_section_change (acfg, ".text", 1);
7367 emit_alignment_code (acfg, 8);
7368 emit_label (acfg, symbol);
7369 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7370 emit_unset_mode (acfg);
7371 if (acfg->need_no_dead_strip)
7372 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7374 for (i = 0; i < acfg->nmethods; ++i) {
7375 #ifdef MONO_ARCH_AOT_SUPPORTED
7379 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7381 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7385 sprintf (symbol, "method_addresses_end");
7386 emit_label (acfg, symbol);
7389 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7390 sprintf (symbol, "unbox_trampolines");
7391 emit_section_change (acfg, RODATA_SECT, 0);
7392 emit_alignment (acfg, 8);
7393 emit_label (acfg, symbol);
7396 for (i = 0; i < acfg->nmethods; ++i) {
7401 cfg = acfg->cfgs [i];
7405 method = cfg->orig_method;
7407 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7408 index = get_method_index (acfg, method);
7410 emit_int32 (acfg, index);
7411 /* Make sure the table is sorted by index */
7412 g_assert (index > prev_index);
7416 sprintf (symbol, "unbox_trampolines_end");
7417 emit_label (acfg, symbol);
7418 emit_int32 (acfg, 0);
7420 /* Emit a separate table with the trampoline addresses/offsets */
7421 sprintf (symbol, "unbox_trampoline_addresses");
7422 emit_section_change (acfg, ".text", 0);
7423 emit_alignment_code (acfg, 8);
7424 emit_label (acfg, symbol);
7426 for (i = 0; i < acfg->nmethods; ++i) {
7431 cfg = acfg->cfgs [i];
7435 method = cfg->orig_method;
7437 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7438 #ifdef MONO_ARCH_AOT_SUPPORTED
7441 index = get_method_index (acfg, method);
7442 sprintf (symbol, "ut_%d", index);
7444 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7451 emit_info (MonoAotCompile *acfg)
7457 offsets = g_new0 (gint32, acfg->nmethods);
7459 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7460 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7462 if (acfg->cfgs [i]) {
7463 emit_method_info (acfg, acfg->cfgs [i]);
7464 offsets [i] = acfg->cfgs [i]->method_info_offset;
7470 sprintf (symbol, "method_info_offsets");
7471 emit_section_change (acfg, RODATA_SECT, 1);
7472 emit_alignment (acfg, 8);
7473 emit_label (acfg, symbol);
7475 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7480 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7482 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7483 #define mix(a,b,c) { \
7484 a -= c; a ^= rot(c, 4); c += b; \
7485 b -= a; b ^= rot(a, 6); a += c; \
7486 c -= b; c ^= rot(b, 8); b += a; \
7487 a -= c; a ^= rot(c,16); c += b; \
7488 b -= a; b ^= rot(a,19); a += c; \
7489 c -= b; c ^= rot(b, 4); b += a; \
7491 #define final(a,b,c) { \
7492 c ^= b; c -= rot(b,14); \
7493 a ^= c; a -= rot(c,11); \
7494 b ^= a; b -= rot(a,25); \
7495 c ^= b; c -= rot(b,16); \
7496 a ^= c; a -= rot(c,4); \
7497 b ^= a; b -= rot(a,14); \
7498 c ^= b; c -= rot(b,24); \
7502 mono_aot_type_hash (MonoType *t1)
7504 guint hash = t1->type;
7506 hash |= t1->byref << 6; /* do not collide with t1->type values */
7508 case MONO_TYPE_VALUETYPE:
7509 case MONO_TYPE_CLASS:
7510 case MONO_TYPE_SZARRAY:
7511 /* check if the distribution is good enough */
7512 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7514 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7515 case MONO_TYPE_ARRAY:
7516 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7517 case MONO_TYPE_GENERICINST:
7518 return ((hash << 5) - hash) ^ 0;
7525 * mono_aot_method_hash:
7527 * Return a hash code for methods which only depends on metadata.
7530 mono_aot_method_hash (MonoMethod *method)
7532 MonoMethodSignature *sig;
7536 guint32 *hashes_start, *hashes;
7538 MonoGenericInst *ginst = NULL;
7540 /* Similar to the hash in mono_method_get_imt_slot () */
7542 sig = mono_method_signature (method);
7544 if (method->is_inflated)
7545 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7547 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7548 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7549 hashes = hashes_start;
7551 /* Some wrappers are assigned to random classes */
7552 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7553 klass = method->klass;
7555 klass = mono_defaults.object_class;
7557 if (!method->wrapper_type) {
7558 char *full_name = mono_type_full_name (&klass->byval_arg);
7560 hashes [0] = mono_metadata_str_hash (full_name);
7564 hashes [0] = mono_metadata_str_hash (klass->name);
7565 hashes [1] = mono_metadata_str_hash (klass->name_space);
7567 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7568 /* The method name includes a stringified pointer */
7571 hashes [2] = mono_metadata_str_hash (method->name);
7572 hashes [3] = method->wrapper_type;
7573 hashes [4] = mono_aot_type_hash (sig->ret);
7575 for (i = 0; i < sig->param_count; i++) {
7576 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7579 for (i = 0; i < ginst->type_argc; ++i)
7580 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7582 g_assert (hindex == hashes_count);
7584 /* Setup internal state */
7585 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7587 /* Handle most of the hashes */
7588 while (hashes_count > 3) {
7597 /* Handle the last 3 hashes (all the case statements fall through) */
7598 switch (hashes_count) {
7599 case 3 : c += hashes [2];
7600 case 2 : b += hashes [1];
7601 case 1 : a += hashes [0];
7603 case 0: /* nothing left to add */
7607 free (hashes_start);
7616 * mono_aot_get_array_helper_from_wrapper;
7618 * Get the helper method in Array called by an array wrapper method.
7621 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7625 MonoGenericContext ctx;
7626 MonoType *args [16];
7627 char *mname, *iname, *s, *s2, *helper_name = NULL;
7629 prefix = "System.Collections.Generic";
7630 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7631 s2 = strstr (s, "`1.");
7637 //printf ("X: %s %s\n", iname, mname);
7639 if (!strcmp (iname, "IList"))
7640 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7642 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7643 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7645 g_free (helper_name);
7648 if (m->is_generic) {
7650 memset (&ctx, 0, sizeof (ctx));
7651 args [0] = &method->klass->element_class->byval_arg;
7652 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7653 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7654 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7660 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7662 typedef struct HashEntry {
7663 guint32 key, value, index;
7664 struct HashEntry *next;
7668 * emit_extra_methods:
7670 * Emit methods which are not in the METHOD table, like wrappers.
7673 emit_extra_methods (MonoAotCompile *acfg)
7675 int i, table_size, buf_size;
7678 guint32 *info_offsets;
7681 HashEntry *entry, *new_entry;
7682 int nmethods, max_chain_length;
7685 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7687 /* Emit method info */
7689 for (i = 0; i < acfg->extra_methods->len; ++i) {
7690 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7691 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7697 p = buf = g_malloc (buf_size);
7701 method = cfg->method_to_register;
7703 encode_method_ref (acfg, method, p, &p);
7705 g_assert ((p - buf) < buf_size);
7707 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7712 * Construct a chained hash table for mapping indexes in extra_method_info to
7715 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7716 table = g_ptr_array_sized_new (table_size);
7717 for (i = 0; i < table_size; ++i)
7718 g_ptr_array_add (table, NULL);
7719 chain_lengths = g_new0 (int, table_size);
7720 max_chain_length = 0;
7721 for (i = 0; i < acfg->extra_methods->len; ++i) {
7722 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7723 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7729 key = info_offsets [i];
7730 value = get_method_index (acfg, method);
7732 hash = mono_aot_method_hash (method) % table_size;
7733 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7735 chain_lengths [hash] ++;
7736 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7738 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7739 new_entry->key = key;
7740 new_entry->value = value;
7742 entry = g_ptr_array_index (table, hash);
7743 if (entry == NULL) {
7744 new_entry->index = hash;
7745 g_ptr_array_index (table, hash) = new_entry;
7748 entry = entry->next;
7750 entry->next = new_entry;
7751 new_entry->index = table->len;
7752 g_ptr_array_add (table, new_entry);
7756 //printf ("MAX: %d\n", max_chain_length);
7758 /* Emit the table */
7759 sprintf (symbol, "extra_method_table");
7760 emit_section_change (acfg, RODATA_SECT, 0);
7761 emit_alignment (acfg, 8);
7762 emit_label (acfg, symbol);
7764 emit_int32 (acfg, table_size);
7765 for (i = 0; i < table->len; ++i) {
7766 HashEntry *entry = g_ptr_array_index (table, i);
7768 if (entry == NULL) {
7769 emit_int32 (acfg, 0);
7770 emit_int32 (acfg, 0);
7771 emit_int32 (acfg, 0);
7773 //g_assert (entry->key > 0);
7774 emit_int32 (acfg, entry->key);
7775 emit_int32 (acfg, entry->value);
7777 emit_int32 (acfg, entry->next->index);
7779 emit_int32 (acfg, 0);
7784 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7785 * This is used by mono_aot_find_jit_info ().
7787 sprintf (symbol, "extra_method_info_offsets");
7788 emit_section_change (acfg, RODATA_SECT, 0);
7789 emit_alignment (acfg, 8);
7790 emit_label (acfg, symbol);
7792 emit_int32 (acfg, acfg->extra_methods->len);
7793 for (i = 0; i < acfg->extra_methods->len; ++i) {
7794 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7796 emit_int32 (acfg, get_method_index (acfg, method));
7797 emit_int32 (acfg, info_offsets [i]);
7802 emit_exception_info (MonoAotCompile *acfg)
7808 offsets = g_new0 (gint32, acfg->nmethods);
7809 for (i = 0; i < acfg->nmethods; ++i) {
7810 if (acfg->cfgs [i]) {
7811 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7812 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7818 sprintf (symbol, "ex_info_offsets");
7819 emit_section_change (acfg, RODATA_SECT, 1);
7820 emit_alignment (acfg, 8);
7821 emit_label (acfg, symbol);
7823 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7828 emit_unwind_info (MonoAotCompile *acfg)
7834 * The unwind info contains a lot of duplicates so we emit each unique
7835 * entry once, and only store the offset from the start of the table in the
7839 sprintf (symbol, "unwind_info");
7840 emit_section_change (acfg, RODATA_SECT, 1);
7841 emit_alignment (acfg, 8);
7842 emit_label (acfg, symbol);
7844 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7845 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7846 guint8 *unwind_info;
7847 guint32 unwind_info_len;
7851 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7854 encode_value (unwind_info_len, p, &p);
7855 emit_bytes (acfg, buf, p - buf);
7856 emit_bytes (acfg, unwind_info, unwind_info_len);
7858 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7863 emit_class_info (MonoAotCompile *acfg)
7869 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7870 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7871 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7873 sprintf (symbol, "class_info_offsets");
7874 emit_section_change (acfg, RODATA_SECT, 1);
7875 emit_alignment (acfg, 8);
7876 emit_label (acfg, symbol);
7878 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7882 typedef struct ClassNameTableEntry {
7883 guint32 token, index;
7884 struct ClassNameTableEntry *next;
7885 } ClassNameTableEntry;
7888 emit_class_name_table (MonoAotCompile *acfg)
7891 guint32 token, hash;
7896 ClassNameTableEntry *entry, *new_entry;
7899 * Construct a chained hash table for mapping class names to typedef tokens.
7901 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7902 table = g_ptr_array_sized_new (table_size);
7903 for (i = 0; i < table_size; ++i)
7904 g_ptr_array_add (table, NULL);
7905 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7907 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7908 klass = mono_class_get_checked (acfg->image, token, &error);
7910 mono_error_cleanup (&error);
7913 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7914 hash = mono_metadata_str_hash (full_name) % table_size;
7917 /* FIXME: Allocate from the mempool */
7918 new_entry = g_new0 (ClassNameTableEntry, 1);
7919 new_entry->token = token;
7921 entry = g_ptr_array_index (table, hash);
7922 if (entry == NULL) {
7923 new_entry->index = hash;
7924 g_ptr_array_index (table, hash) = new_entry;
7927 entry = entry->next;
7929 entry->next = new_entry;
7930 new_entry->index = table->len;
7931 g_ptr_array_add (table, new_entry);
7935 /* Emit the table */
7936 sprintf (symbol, "class_name_table");
7937 emit_section_change (acfg, RODATA_SECT, 0);
7938 emit_alignment (acfg, 8);
7939 emit_label (acfg, symbol);
7941 /* FIXME: Optimize memory usage */
7942 g_assert (table_size < 65000);
7943 emit_int16 (acfg, table_size);
7944 g_assert (table->len < 65000);
7945 for (i = 0; i < table->len; ++i) {
7946 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7948 if (entry == NULL) {
7949 emit_int16 (acfg, 0);
7950 emit_int16 (acfg, 0);
7952 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7954 emit_int16 (acfg, entry->next->index);
7956 emit_int16 (acfg, 0);
7962 emit_image_table (MonoAotCompile *acfg)
7968 * The image table is small but referenced in a lot of places.
7969 * So we emit it at once, and reference its elements by an index.
7972 sprintf (symbol, "image_table");
7973 emit_section_change (acfg, RODATA_SECT, 1);
7974 emit_alignment (acfg, 8);
7975 emit_label (acfg, symbol);
7977 emit_int32 (acfg, acfg->image_table->len);
7978 for (i = 0; i < acfg->image_table->len; i++) {
7979 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7980 MonoAssemblyName *aname = &image->assembly->aname;
7982 /* FIXME: Support multi-module assemblies */
7983 g_assert (image->assembly->image == image);
7985 emit_string (acfg, image->assembly_name);
7986 emit_string (acfg, image->guid);
7987 emit_string (acfg, aname->culture ? aname->culture : "");
7988 emit_string (acfg, (const char*)aname->public_key_token);
7990 emit_alignment (acfg, 8);
7991 emit_int32 (acfg, aname->flags);
7992 emit_int32 (acfg, aname->major);
7993 emit_int32 (acfg, aname->minor);
7994 emit_int32 (acfg, aname->build);
7995 emit_int32 (acfg, aname->revision);
8000 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8003 int i, first_plt_got_patch = 0, buf_size;
8005 guint32 *got_info_offsets;
8006 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8008 /* Add the patches needed by the PLT to the GOT */
8010 acfg->plt_got_offset_base = acfg->got_offset;
8011 first_plt_got_patch = info->got_patches->len;
8012 for (i = 1; i < acfg->plt_offset; ++i) {
8013 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8015 g_ptr_array_add (info->got_patches, plt_entry->ji);
8017 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8020 acfg->got_offset += acfg->plt_offset;
8025 * - optimize offsets table.
8026 * - reduce number of exported symbols.
8027 * - emit info for a klass only once.
8028 * - determine when a method uses a GOT slot which is guaranteed to be already
8030 * - clean up and document the code.
8031 * - use String.Empty in class libs.
8034 /* Encode info required to decode shared GOT entries */
8035 buf_size = info->got_patches->len * 128;
8036 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8037 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8039 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8041 if (acfg->plt_offset)
8042 acfg->plt_got_info_offsets [0] = 0;
8044 for (i = 0; i < info->got_patches->len; ++i) {
8045 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8050 encode_value (ji->type, p, &p);
8052 encode_patch (acfg, ji, p, &p);
8053 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8054 g_assert (p - buf <= buf_size);
8055 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8057 if (!llvm && i >= first_plt_got_patch)
8058 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8059 acfg->stats.got_info_size += p - buf;
8062 /* Emit got_info_offsets table */
8064 sprintf (symbol, "llvm_got_info_offsets");
8066 sprintf (symbol, "got_info_offsets");
8067 emit_section_change (acfg, RODATA_SECT, 1);
8068 emit_alignment (acfg, 8);
8069 emit_label (acfg, symbol);
8071 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8072 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8076 emit_got (MonoAotCompile *acfg)
8080 /* Don't make GOT global so accesses to it don't need relocations */
8081 sprintf (symbol, "%s", acfg->got_symbol);
8082 emit_section_change (acfg, ".bss", 0);
8083 emit_alignment (acfg, 8);
8084 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8085 emit_label (acfg, symbol);
8086 if (acfg->got_offset > 0)
8087 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8089 sprintf (symbol, "got_end");
8090 emit_label (acfg, symbol);
8093 typedef struct GlobalsTableEntry {
8094 guint32 value, index;
8095 struct GlobalsTableEntry *next;
8096 } GlobalsTableEntry;
8099 emit_globals (MonoAotCompile *acfg)
8105 GlobalsTableEntry *entry, *new_entry;
8107 if (!acfg->aot_opts.static_link)
8111 * When static linking, we emit a table containing our globals.
8115 * Construct a chained hash table for mapping global names to their index in
8116 * the globals table.
8118 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8119 table = g_ptr_array_sized_new (table_size);
8120 for (i = 0; i < table_size; ++i)
8121 g_ptr_array_add (table, NULL);
8122 for (i = 0; i < acfg->globals->len; ++i) {
8123 char *name = g_ptr_array_index (acfg->globals, i);
8125 hash = mono_metadata_str_hash (name) % table_size;
8127 /* FIXME: Allocate from the mempool */
8128 new_entry = g_new0 (GlobalsTableEntry, 1);
8129 new_entry->value = i;
8131 entry = g_ptr_array_index (table, hash);
8132 if (entry == NULL) {
8133 new_entry->index = hash;
8134 g_ptr_array_index (table, hash) = new_entry;
8137 entry = entry->next;
8139 entry->next = new_entry;
8140 new_entry->index = table->len;
8141 g_ptr_array_add (table, new_entry);
8145 /* Emit the table */
8146 sprintf (symbol, ".Lglobals_hash");
8147 emit_section_change (acfg, RODATA_SECT, 0);
8148 emit_alignment (acfg, 8);
8149 emit_label (acfg, symbol);
8151 /* FIXME: Optimize memory usage */
8152 g_assert (table_size < 65000);
8153 emit_int16 (acfg, table_size);
8154 for (i = 0; i < table->len; ++i) {
8155 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8157 if (entry == NULL) {
8158 emit_int16 (acfg, 0);
8159 emit_int16 (acfg, 0);
8161 emit_int16 (acfg, entry->value + 1);
8163 emit_int16 (acfg, entry->next->index);
8165 emit_int16 (acfg, 0);
8169 /* Emit the names */
8170 for (i = 0; i < acfg->globals->len; ++i) {
8171 char *name = g_ptr_array_index (acfg->globals, i);
8173 sprintf (symbol, "name_%d", i);
8174 emit_section_change (acfg, RODATA_SECT, 1);
8176 emit_alignment (acfg, 4);
8178 emit_label (acfg, symbol);
8179 emit_string (acfg, name);
8182 /* Emit the globals table */
8183 sprintf (symbol, "globals");
8184 emit_section_change (acfg, ".data", 0);
8185 /* This is not a global, since it is accessed by the init function */
8186 emit_alignment (acfg, 8);
8187 emit_label (acfg, symbol);
8189 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8190 emit_pointer (acfg, symbol);
8192 for (i = 0; i < acfg->globals->len; ++i) {
8193 char *name = g_ptr_array_index (acfg->globals, i);
8195 sprintf (symbol, "name_%d", i);
8196 emit_pointer (acfg, symbol);
8198 g_assert (strlen (name) < sizeof (symbol));
8199 sprintf (symbol, "%s", name);
8200 emit_pointer (acfg, symbol);
8202 /* Null terminate the table */
8203 emit_int32 (acfg, 0);
8204 emit_int32 (acfg, 0);
8208 emit_autoreg (MonoAotCompile *acfg)
8213 * Emit a function into the .ctor section which will be called by the ELF
8214 * loader to register this module with the runtime.
8216 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8219 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8221 arch_emit_autoreg (acfg, symbol);
8227 emit_mem_end (MonoAotCompile *acfg)
8231 sprintf (symbol, "mem_end");
8232 emit_section_change (acfg, ".text", 1);
8233 emit_alignment_code (acfg, 8);
8234 emit_label (acfg, symbol);
8238 * Emit a structure containing all the information not stored elsewhere.
8241 emit_file_info (MonoAotCompile *acfg)
8246 const char *gc_name;
8249 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8251 if (acfg->aot_opts.bind_to_runtime_version) {
8252 build_info = mono_get_runtime_build_info ();
8253 emit_string_symbol (acfg, "runtime_version", build_info);
8254 g_free (build_info);
8256 emit_string_symbol (acfg, "runtime_version", "");
8259 /* Emit a string holding the assembly name */
8260 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8263 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8266 gc_name = mono_gc_get_gc_name ();
8267 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8269 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8270 emit_section_change (acfg, ".data", 0);
8271 emit_alignment (acfg, 8);
8272 emit_label (acfg, symbol);
8273 if (!acfg->aot_opts.static_link)
8274 emit_global (acfg, symbol, FALSE);
8276 /* The data emitted here must match MonoAotFileInfo. */
8278 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8279 emit_int32 (acfg, 0);
8282 * We emit pointers to our data structures instead of emitting global symbols which
8283 * point to them, to reduce the number of globals, and because using globals leads to
8284 * various problems (i.e. arm/thumb).
8286 emit_pointer (acfg, acfg->got_symbol);
8288 emit_pointer (acfg, acfg->llvm_got_symbol);
8290 emit_pointer (acfg, NULL);
8291 emit_pointer (acfg, acfg->methods_symbol);
8292 emit_pointer (acfg, "jit_code_start");
8293 emit_pointer (acfg, "jit_code_end");
8296 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8298 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8300 emit_pointer (acfg, NULL);
8302 emit_pointer (acfg, "blob");
8303 emit_pointer (acfg, "class_name_table");
8304 emit_pointer (acfg, "class_info_offsets");
8305 emit_pointer (acfg, "method_info_offsets");
8306 emit_pointer (acfg, "ex_info_offsets");
8307 emit_pointer (acfg, "method_addresses");
8308 emit_pointer (acfg, "extra_method_info_offsets");
8309 emit_pointer (acfg, "extra_method_table");
8310 emit_pointer (acfg, "got_info_offsets");
8312 emit_pointer (acfg, "llvm_got_info_offsets");
8314 emit_pointer (acfg, NULL);
8315 emit_pointer (acfg, "methods_end");
8316 emit_pointer (acfg, "unwind_info");
8317 emit_pointer (acfg, "mem_end");
8318 emit_pointer (acfg, "image_table");
8319 emit_pointer (acfg, "plt");
8320 emit_pointer (acfg, "plt_end");
8321 emit_pointer (acfg, "assembly_guid");
8322 emit_pointer (acfg, "runtime_version");
8323 if (acfg->num_trampoline_got_entries) {
8324 emit_pointer (acfg, "specific_trampolines");
8325 emit_pointer (acfg, "static_rgctx_trampolines");
8326 emit_pointer (acfg, "imt_thunks");
8327 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8329 emit_pointer (acfg, NULL);
8330 emit_pointer (acfg, NULL);
8331 emit_pointer (acfg, NULL);
8332 emit_pointer (acfg, NULL);
8334 if (acfg->thumb_mixed) {
8335 emit_pointer (acfg, "thumb_end");
8337 emit_pointer (acfg, NULL);
8339 if (acfg->aot_opts.static_link) {
8340 emit_pointer (acfg, "globals");
8342 emit_pointer (acfg, NULL);
8344 emit_pointer (acfg, "assembly_name");
8345 emit_pointer (acfg, "unbox_trampolines");
8346 emit_pointer (acfg, "unbox_trampolines_end");
8347 emit_pointer (acfg, "unbox_trampoline_addresses");
8349 emit_int32 (acfg, acfg->plt_got_offset_base);
8350 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8351 emit_int32 (acfg, acfg->plt_offset);
8352 emit_int32 (acfg, acfg->nmethods);
8353 emit_int32 (acfg, acfg->flags);
8354 emit_int32 (acfg, acfg->opts);
8355 emit_int32 (acfg, acfg->simd_opts);
8356 emit_int32 (acfg, gc_name_offset);
8358 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8359 emit_int32 (acfg, acfg->num_trampolines [i]);
8360 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8361 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8362 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8363 emit_int32 (acfg, acfg->trampoline_size [i]);
8364 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8366 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8371 memset (&t, 0, sizeof (MonoType));
8372 t.type = MONO_TYPE_R8;
8373 mono_type_size (&t, &align);
8374 emit_int32 (acfg, align);
8376 memset (&t, 0, sizeof (MonoType));
8377 t.type = MONO_TYPE_I8;
8378 mono_type_size (&t, &align);
8380 emit_int32 (acfg, align);
8383 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8384 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8386 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8387 emit_int32 (acfg, acfg->tramp_page_size);
8388 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8389 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8391 if (acfg->aot_opts.static_link) {
8395 * Emit a global symbol which can be passed by an embedding app to
8396 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8399 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8401 /* Get rid of characters which cannot occur in symbols */
8403 for (p = symbol; *p; ++p) {
8404 if (!(isalnum (*p) || *p == '_'))
8407 acfg->static_linking_symbol = g_strdup (symbol);
8408 emit_global_inner (acfg, symbol, FALSE);
8409 emit_alignment (acfg, sizeof (gpointer));
8410 emit_label (acfg, symbol);
8411 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8416 emit_blob (MonoAotCompile *acfg)
8420 sprintf (symbol, "blob");
8421 emit_section_change (acfg, RODATA_SECT, 1);
8422 emit_alignment (acfg, 8);
8423 emit_label (acfg, symbol);
8425 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8429 emit_objc_selectors (MonoAotCompile *acfg)
8433 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8438 * cat > foo.m << EOF
8441 * return @selector(print:);
8446 img_writer_emit_unset_mode (acfg->w);
8447 g_assert (acfg->fp);
8448 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8449 fprintf (acfg->fp, ".align 3\n");
8450 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8451 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8452 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8454 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8455 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8456 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8457 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8460 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8461 fprintf (acfg->fp, ".align 3\n");
8462 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8463 fprintf (acfg->fp, ".long 0\n");
8464 fprintf (acfg->fp, ".long 16\n");
8468 emit_dwarf_info (MonoAotCompile *acfg)
8470 #ifdef EMIT_DWARF_INFO
8474 /* DIEs for methods */
8475 for (i = 0; i < acfg->nmethods; ++i) {
8476 MonoCompile *cfg = acfg->cfgs [i];
8481 // FIXME: LLVM doesn't define .Lme_...
8482 if (cfg->compile_llvm)
8485 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8487 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 ()));
8493 collect_methods (MonoAotCompile *acfg)
8496 MonoImage *image = acfg->image;
8498 /* Collect methods */
8499 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8501 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8503 method = mono_get_method (acfg->image, token, NULL);
8506 aot_printerrf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8507 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8511 /* Load all methods eagerly to skip the slower lazy loading code */
8512 mono_class_setup_methods (method->klass);
8514 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8515 /* Compile the wrapper instead */
8516 /* We do this here instead of add_wrappers () because it is easy to do it here */
8517 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8521 /* FIXME: Some mscorlib methods don't have debug info */
8523 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8524 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8525 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8526 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8527 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8528 if (!mono_debug_lookup_method (method)) {
8529 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8536 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8537 add_method_with_index (acfg, method, i, FALSE);
8538 acfg->method_index ++;
8541 /* gsharedvt methods */
8542 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8544 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8546 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8549 method = mono_get_method (acfg->image, token, NULL);
8553 if (strcmp (method->name, "gshared2"))
8557 if (!strstr (method->klass->image->name, "mini"))
8560 if (method->is_generic || method->klass->generic_container) {
8561 MonoMethod *gshared;
8563 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8564 add_extra_method (acfg, gshared);
8568 add_generic_instances (acfg);
8570 if (acfg->aot_opts.full_aot)
8571 add_wrappers (acfg);
8576 compile_methods (MonoAotCompile *acfg)
8580 if (acfg->aot_opts.nthreads > 0) {
8585 gpointer *user_data;
8586 MonoMethod **methods;
8588 methods_len = acfg->methods->len;
8590 len = acfg->methods->len / acfg->aot_opts.nthreads;
8593 * Partition the list of methods into fragments, and hand it to threads to
8596 threads = g_ptr_array_new ();
8597 /* Make a copy since acfg->methods is modified by compile_method () */
8598 methods = g_new0 (MonoMethod*, methods_len);
8599 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8600 for (i = 0; i < methods_len; ++i)
8601 methods [i] = g_ptr_array_index (acfg->methods, i);
8603 while (i < methods_len) {
8604 frag = g_ptr_array_new ();
8605 for (j = 0; j < len; ++j) {
8606 if (i < methods_len) {
8607 g_ptr_array_add (frag, methods [i]);
8612 user_data = g_new0 (gpointer, 3);
8613 user_data [0] = mono_domain_get ();
8614 user_data [1] = acfg;
8615 user_data [2] = frag;
8617 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8618 g_ptr_array_add (threads, handle);
8622 for (i = 0; i < threads->len; ++i) {
8623 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8629 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8630 for (i = methods_len; i < acfg->methods->len; ++i) {
8631 /* This can new methods to acfg->methods */
8632 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8637 compile_asm (MonoAotCompile *acfg)
8639 char *command, *objfile;
8640 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8641 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8643 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8644 #define AS_OPTIONS "--64"
8645 #elif defined(TARGET_POWERPC64)
8646 #define AS_OPTIONS "-a64 -mppc64"
8647 #define LD_OPTIONS "-m elf64ppc"
8648 #elif defined(sparc) && SIZEOF_VOID_P == 8
8649 #define AS_OPTIONS "-xarch=v9"
8650 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8651 #define AS_OPTIONS "-arch i386"
8653 #define AS_OPTIONS ""
8656 #ifdef __native_client_codegen__
8657 #if defined(TARGET_AMD64)
8658 #define AS_NAME "nacl64-as"
8660 #define AS_NAME "nacl-as"
8662 #elif defined(TARGET_OSX)
8663 #define AS_NAME "clang -c -x assembler"
8665 #define AS_NAME "as"
8669 #define LD_OPTIONS ""
8673 #define LD_NAME "ld -shared -G"
8674 #elif defined(__ppc__) && defined(TARGET_MACH)
8675 #define LD_NAME "gcc -dynamiclib"
8676 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8677 #define LD_NAME "clang --shared"
8678 #elif defined(HOST_WIN32)
8679 #define LD_NAME "gcc -shared --dll"
8680 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8681 #define LD_NAME "clang -m32 -dynamiclib"
8684 if (acfg->aot_opts.asm_only) {
8685 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8686 if (acfg->aot_opts.static_link)
8687 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8688 if (acfg->llvm_separate)
8689 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8693 if (acfg->aot_opts.static_link) {
8694 if (acfg->aot_opts.outfile)
8695 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8697 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8699 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8701 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);
8702 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8703 if (system (command) != 0) {
8709 if (acfg->llvm_separate && !acfg->llvm_owriter) {
8710 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);
8711 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8712 if (system (command) != 0) {
8721 if (acfg->aot_opts.static_link) {
8722 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8723 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8728 if (acfg->aot_opts.outfile)
8729 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8731 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8733 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8735 if (acfg->llvm_separate) {
8736 llvm_ofile = g_strdup (acfg->llvm_ofile);
8738 llvm_ofile = g_strdup ("");
8742 command = g_strdup_printf ("%s -o %s %s %s.o", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8744 command = g_strdup_printf ("%sld %s -shared -o %s %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8746 aot_printf (acfg, "Executing the native linker: %s\n", command);
8747 if (system (command) != 0) {
8748 g_free (tmp_outfile_name);
8749 g_free (outfile_name);
8757 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8758 printf ("Stripping the binary: %s\n", com);
8762 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8764 * gas generates 'mapping symbols' each time code and data is mixed, which
8765 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8767 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8768 aot_printf (acfg, "Stripping the binary: %s\n", command);
8769 if (system (command) != 0) {
8770 g_free (tmp_outfile_name);
8771 g_free (outfile_name);
8778 rename (tmp_outfile_name, outfile_name);
8780 #if defined(TARGET_MACH)
8781 command = g_strdup_printf ("dsymutil %s", outfile_name);
8782 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8783 if (system (command) != 0) {
8788 if (!acfg->aot_opts.save_temps)
8791 g_free (tmp_outfile_name);
8792 g_free (outfile_name);
8795 if (acfg->aot_opts.save_temps)
8796 aot_printf (acfg, "Retained input file.\n");
8798 unlink (acfg->tmpfname);
8803 static void init_got_info (GotInfo *info)
8807 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8808 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8809 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8810 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8811 info->got_patches = g_ptr_array_new ();
8814 static MonoAotCompile*
8815 acfg_create (MonoAssembly *ass, guint32 opts)
8817 MonoImage *image = ass->image;
8818 MonoAotCompile *acfg;
8820 acfg = g_new0 (MonoAotCompile, 1);
8821 acfg->methods = g_ptr_array_new ();
8822 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8823 acfg->method_depth = g_hash_table_new (NULL, NULL);
8824 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8825 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8826 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8827 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8828 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8829 acfg->image_hash = g_hash_table_new (NULL, NULL);
8830 acfg->image_table = g_ptr_array_new ();
8831 acfg->globals = g_ptr_array_new ();
8832 acfg->image = image;
8834 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8835 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8836 acfg->mempool = mono_mempool_new ();
8837 acfg->extra_methods = g_ptr_array_new ();
8838 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8839 acfg->unwind_ops = g_ptr_array_new ();
8840 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8841 acfg->method_order = g_ptr_array_new ();
8842 acfg->export_names = g_hash_table_new (NULL, NULL);
8843 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8844 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8845 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8846 mono_mutex_init_recursive (&acfg->mutex);
8848 init_got_info (&acfg->got_info);
8849 init_got_info (&acfg->llvm_got_info);
8855 got_info_free (GotInfo *info)
8859 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8860 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8861 g_free (info->patch_to_got_offset_by_type);
8862 g_hash_table_destroy (info->patch_to_got_offset);
8863 g_ptr_array_free (info->got_patches, TRUE);
8867 acfg_free (MonoAotCompile *acfg)
8871 img_writer_destroy (acfg->w);
8872 for (i = 0; i < acfg->nmethods; ++i)
8874 g_free (acfg->cfgs [i]);
8875 g_free (acfg->cfgs);
8876 g_free (acfg->static_linking_symbol);
8877 g_free (acfg->got_symbol);
8878 g_free (acfg->plt_symbol);
8879 g_ptr_array_free (acfg->methods, TRUE);
8880 g_ptr_array_free (acfg->image_table, TRUE);
8881 g_ptr_array_free (acfg->globals, TRUE);
8882 g_ptr_array_free (acfg->unwind_ops, TRUE);
8883 g_hash_table_destroy (acfg->method_indexes);
8884 g_hash_table_destroy (acfg->method_depth);
8885 g_hash_table_destroy (acfg->plt_offset_to_entry);
8886 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8887 if (acfg->patch_to_plt_entry [i])
8888 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8890 g_free (acfg->patch_to_plt_entry);
8891 g_hash_table_destroy (acfg->method_to_cfg);
8892 g_hash_table_destroy (acfg->token_info_hash);
8893 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8894 g_hash_table_destroy (acfg->image_hash);
8895 g_hash_table_destroy (acfg->unwind_info_offsets);
8896 g_hash_table_destroy (acfg->method_label_hash);
8897 g_hash_table_destroy (acfg->export_names);
8898 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8899 g_hash_table_destroy (acfg->klass_blob_hash);
8900 g_hash_table_destroy (acfg->method_blob_hash);
8901 got_info_free (&acfg->got_info);
8902 got_info_free (&acfg->llvm_got_info);
8903 mono_mempool_destroy (acfg->mempool);
8907 #include "aot_dump.c"
8910 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8912 MonoImage *image = ass->image;
8913 int i, res, all_sizes;
8914 MonoAotCompile *acfg;
8915 char *outfile_name, *tmp_outfile_name, *p;
8916 char llvm_stats_msg [256];
8920 acfg = acfg_create (ass, opts);
8922 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8923 acfg->aot_opts.write_symbols = TRUE;
8924 acfg->aot_opts.ntrampolines = 1024;
8925 acfg->aot_opts.nrgctx_trampolines = 1024;
8926 acfg->aot_opts.nimt_trampolines = 128;
8927 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8928 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8929 acfg->aot_opts.llvm_path = g_strdup ("");
8931 acfg->aot_opts.use_trampolines_page = TRUE;
8934 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8936 if (acfg->aot_opts.logfile) {
8937 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
8940 if (acfg->aot_opts.static_link)
8941 acfg->aot_opts.autoreg = TRUE;
8943 //acfg->aot_opts.print_skipped_methods = TRUE;
8945 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8946 if (opts & MONO_OPT_GSHAREDVT) {
8947 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
8952 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8954 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8955 if (acfg->aot_opts.full_aot) {
8956 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
8961 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8962 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8966 if (acfg->aot_opts.static_link)
8967 acfg->aot_opts.asm_writer = TRUE;
8969 if (acfg->aot_opts.soft_debug) {
8970 MonoDebugOptions *opt = mini_get_debug_options ();
8972 opt->mdb_optimizations = TRUE;
8973 opt->gen_seq_points_debug_data = TRUE;
8975 if (!mono_debug_enabled ()) {
8976 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
8979 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8982 if (mono_use_llvm || acfg->aot_opts.llvm) {
8984 acfg->aot_opts.asm_writer = TRUE;
8985 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8987 if (acfg->aot_opts.soft_debug) {
8988 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8994 if (!acfg->aot_opts.asm_only || acfg->aot_opts.llvm_outfile) {
8996 * Emit all LLVM code into a separate assembly/object file and link with it
8999 #if LLVM_API_VERSION >= 3
9000 acfg->llvm_separate = TRUE;
9001 if (!acfg->aot_opts.asm_only)
9002 acfg->llvm_owriter = TRUE;
9005 if (acfg->aot_opts.llvm_outfile && !acfg->llvm_separate) {
9006 aot_printerrf (acfg, "The llvm-outputfile= option is not supported on this platform.\n");
9011 if (acfg->aot_opts.full_aot)
9012 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9014 if (acfg->aot_opts.instances_logfile_path) {
9015 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9016 if (!acfg->instances_logfile) {
9017 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9022 load_profile_files (acfg);
9024 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9025 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9026 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9028 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9029 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9030 if (acfg->opts & MONO_OPT_GSHAREDVT)
9031 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9034 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9038 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9039 /* Get rid of characters which cannot occur in symbols */
9040 for (p = acfg->assembly_name_sym; *p; ++p) {
9041 if (!(isalnum (*p) || *p == '_'))
9045 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9046 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9047 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9049 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9051 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9052 if (acfg->llvm_separate)
9053 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9055 acfg->llvm_eh_frame_symbol = g_strdup ("mono_eh_frame");
9058 acfg->method_index = 1;
9062 if (acfg->aot_opts.full_aot)
9063 mono_set_partial_sharing_supported (TRUE);
9066 res = collect_methods (acfg);
9070 acfg->cfgs_size = acfg->methods->len + 32;
9071 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9073 /* PLT offset 0 is reserved for the PLT trampoline */
9074 acfg->plt_offset = 1;
9079 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, acfg->llvm_separate, acfg->llvm_separate);
9083 /* GOT offset 0 is reserved for the address of the current assembly */
9087 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9088 ji->type = MONO_PATCH_INFO_IMAGE;
9089 ji->data.image = acfg->image;
9091 get_got_offset (acfg, FALSE, ji);
9092 get_got_offset (acfg, TRUE, ji);
9094 /* Slot 1 is reserved for the mscorlib got addr */
9095 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9096 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9097 get_got_offset (acfg, FALSE, ji);
9098 get_got_offset (acfg, TRUE, ji);
9100 /* This is very common */
9101 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9102 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9103 get_got_offset (acfg, FALSE, ji);
9104 get_got_offset (acfg, TRUE, ji);
9106 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9107 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9108 get_got_offset (acfg, FALSE, ji);
9109 get_got_offset (acfg, TRUE, ji);
9114 compile_methods (acfg);
9118 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9126 if (acfg->aot_opts.asm_only) {
9127 if (acfg->aot_opts.outfile) {
9128 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9129 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9131 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9132 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9134 if (acfg->llvm_separate) {
9135 g_assert (acfg->aot_opts.llvm_outfile);
9136 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9139 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9140 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9141 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9142 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9145 res = emit_llvm_file (acfg);
9151 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9152 if (acfg->aot_opts.outfile)
9153 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9155 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9158 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9159 * it might be in another file system so the rename () won't work.
9161 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9163 acfg->fp = fopen (tmp_outfile_name, "w");
9165 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9169 acfg->w = img_writer_create (acfg->fp, TRUE);
9170 acfg->use_bin_writer = TRUE;
9172 if (acfg->llvm && !acfg->llvm_separate) {
9173 /* Append to the .s file created by llvm */
9174 /* FIXME: Use multiple files instead */
9175 acfg->fp = fopen (acfg->tmpfname, "a+");
9177 if (acfg->aot_opts.asm_only) {
9178 if (acfg->aot_opts.outfile)
9179 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9181 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9182 acfg->fp = fopen (acfg->tmpfname, "w+");
9184 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9185 acfg->fp = fdopen (i, "w+");
9188 if (acfg->fp == 0) {
9189 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9192 acfg->w = img_writer_create (acfg->fp, FALSE);
9194 tmp_outfile_name = NULL;
9195 outfile_name = NULL;
9198 /* Compute symbols for methods */
9199 for (i = 0; i < acfg->nmethods; ++i) {
9200 if (acfg->cfgs [i]) {
9201 MonoCompile *cfg = acfg->cfgs [i];
9202 int method_index = get_method_index (acfg, cfg->orig_method);
9204 if (COMPILE_LLVM (cfg))
9205 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9206 else if (acfg->global_symbols || acfg->llvm_separate)
9207 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9209 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9213 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9215 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9216 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9219 //acfg->gas_line_numbers = TRUE;
9222 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9223 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9224 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9227 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9230 img_writer_emit_start (acfg->w);
9233 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9235 if (acfg->thumb_mixed) {
9238 * This global symbol marks the end of THUMB code, and the beginning of ARM
9239 * code generated by our JIT.
9241 sprintf (symbol, "thumb_end");
9242 emit_section_change (acfg, ".text", 0);
9243 emit_alignment_code (acfg, 8);
9244 emit_label (acfg, symbol);
9245 emit_zero_bytes (acfg, 16);
9247 fprintf (acfg->fp, ".arm\n");
9254 emit_extra_methods (acfg);
9256 emit_trampolines (acfg);
9258 emit_class_name_table (acfg);
9260 emit_got_info (acfg, FALSE);
9262 emit_got_info (acfg, TRUE);
9264 emit_exception_info (acfg);
9266 emit_unwind_info (acfg);
9268 emit_class_info (acfg);
9272 emit_image_table (acfg);
9276 emit_file_info (acfg);
9280 emit_objc_selectors (acfg);
9282 emit_globals (acfg);
9284 emit_autoreg (acfg);
9287 emit_dwarf_info (acfg);
9288 mono_dwarf_writer_close (acfg->dwarf);
9291 emit_mem_end (acfg);
9293 if (acfg->need_pt_gnu_stack) {
9294 /* This is required so the .so doesn't have an executable stack */
9295 /* The bin writer already emits this */
9296 if (!acfg->use_bin_writer)
9297 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9302 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9305 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9307 strcpy (llvm_stats_msg, "");
9309 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;
9311 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",
9312 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9313 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9314 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9315 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9316 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9317 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9318 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9319 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9320 (int)(acfg->got_offset * sizeof (gpointer)));
9321 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9322 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9324 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9325 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9326 if (acfg->stats.genericcount)
9327 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9328 if (acfg->stats.abscount)
9329 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9330 if (acfg->stats.lmfcount)
9331 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9332 if (acfg->stats.ocount)
9333 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9336 res = img_writer_emit_writeout (acfg->w);
9341 if (acfg->use_bin_writer) {
9342 int err = rename (tmp_outfile_name, outfile_name);
9345 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9349 res = compile_asm (acfg);
9356 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9358 if (acfg->aot_opts.stats) {
9361 aot_printf (acfg, "GOT slot distribution:\n");
9362 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9363 if (acfg->stats.got_slot_types [i])
9364 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]);
9367 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);
9369 if (acfg->aot_opts.dump_json)
9382 mono_aot_readonly_field_override (MonoClassField *field)
9388 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)