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;
134 typedef struct MonoAotStats {
135 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
136 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
137 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
138 int got_slots, offsets_size;
139 int got_slot_types [MONO_PATCH_INFO_NONE];
140 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
141 int jit_time, gen_time, link_time;
144 typedef struct GotInfo {
145 GHashTable *patch_to_got_offset;
146 GHashTable **patch_to_got_offset_by_type;
147 GPtrArray *got_patches;
150 typedef struct MonoAotCompile {
153 GHashTable *method_indexes;
154 GHashTable *method_depth;
157 GHashTable **patch_to_plt_entry;
158 GHashTable *plt_offset_to_entry;
159 //GHashTable *patch_to_got_offset;
160 //GHashTable **patch_to_got_offset_by_type;
161 //GPtrArray *got_patches;
162 GotInfo got_info, llvm_got_info;
163 GHashTable *image_hash;
164 GHashTable *method_to_cfg;
165 GHashTable *token_info_hash;
166 GHashTable *method_to_pinvoke_import;
167 GPtrArray *extra_methods;
168 GPtrArray *image_table;
170 GPtrArray *method_order;
171 GHashTable *export_names;
172 /* Maps MonoClass* -> blob offset */
173 GHashTable *klass_blob_hash;
174 /* Maps MonoMethod* -> blob offset */
175 GHashTable *method_blob_hash;
176 guint32 *plt_got_info_offsets;
177 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
178 /* Number of GOT entries reserved for trampolines */
179 guint32 num_trampoline_got_entries;
180 guint32 tramp_page_size;
182 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
183 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
184 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
185 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
187 MonoAotOptions aot_opts;
191 MonoMemPool *mempool;
194 char *static_linking_symbol;
196 gboolean use_bin_writer;
197 gboolean gas_line_numbers;
198 /* Whenever to emit LLVM code into a separate object file */
199 gboolean llvm_separate;
200 /* Whenever to emit an object file directly from llc */
201 gboolean llvm_owriter;
203 MonoDwarfWriter *dwarf;
210 GHashTable *unwind_info_offsets;
211 GPtrArray *unwind_ops;
212 guint32 unwind_info_offset;
213 char *got_symbol_base;
214 char *llvm_got_symbol_base;
216 char *llvm_got_symbol;
218 char *methods_symbol;
219 char *llvm_eh_frame_symbol;
220 GHashTable *method_label_hash;
221 const char *temp_prefix;
222 const char *user_symbol_prefix;
223 const char *llvm_label_prefix;
224 const char *inst_directive;
226 guint32 label_generator;
228 MonoAotFileFlags flags;
229 MonoDynamicStream blob;
230 MonoClass **typespec_classes;
233 char *assembly_name_sym;
234 GHashTable *plt_entry_debug_sym_cache;
235 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
236 GHashTable *ginst_hash;
237 GHashTable *dwarf_ln_filenames;
238 gboolean global_symbols;
239 int objc_selector_index, objc_selector_index_2;
240 GPtrArray *objc_selectors;
241 GHashTable *objc_selector_to_index;
243 FILE *instances_logfile;
248 char *symbol, *llvm_symbol, *debug_sym;
250 gboolean jit_used, llvm_used;
253 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
254 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
256 /* This points to the current acfg in LLVM mode */
257 static MonoAotCompile *llvm_acfg;
259 #ifdef HAVE_ARRAY_ELEM_INIT
260 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
261 #define MSGSTRFIELD1(line) str##line
262 static const struct msgstr_t {
263 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
264 #include "patch-info.h"
267 #define PATCH_INFO(a,b) b,
268 #include "patch-info.h"
271 static const gint16 opidx [] = {
272 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
273 #include "patch-info.h"
277 static G_GNUC_UNUSED const char*
278 get_patch_name (int info)
280 return (const char*)&opstr + opidx [info];
284 #define PATCH_INFO(a,b) b,
285 static const char* const
286 patch_types [MONO_PATCH_INFO_NUM + 1] = {
287 #include "patch-info.h"
291 static G_GNUC_UNUSED const char*
292 get_patch_name (int info)
294 return patch_types [info];
300 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
303 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
309 output = acfg->logfile;
313 va_start (args, format);
314 vfprintf (output, format, args);
319 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
325 output = acfg->logfile;
329 va_start (args, format);
330 vfprintf (output, format, args);
334 /* Wrappers around the image writer functions */
337 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
339 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
343 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
345 img_writer_emit_push_section (acfg->w, section_name, subsection);
349 emit_pop_section (MonoAotCompile *acfg)
351 img_writer_emit_pop_section (acfg->w);
355 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
357 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
361 emit_label (MonoAotCompile *acfg, const char *name)
363 img_writer_emit_label (acfg->w, name);
367 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
369 img_writer_emit_bytes (acfg->w, buf, size);
373 emit_string (MonoAotCompile *acfg, const char *value)
375 img_writer_emit_string (acfg->w, value);
379 emit_line (MonoAotCompile *acfg)
381 img_writer_emit_line (acfg->w);
385 emit_alignment (MonoAotCompile *acfg, int size)
387 img_writer_emit_alignment (acfg->w, size);
391 emit_alignment_code (MonoAotCompile *acfg, int size)
393 if (acfg->align_pad_value)
394 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
396 img_writer_emit_alignment (acfg->w, size);
400 emit_padding (MonoAotCompile *acfg, int size)
405 if (acfg->align_pad_value) {
406 for (i = 0; i < 16; ++i)
407 buf [i] = acfg->align_pad_value;
409 memset (buf, 0, sizeof (buf));
412 for (i = 0; i < size; i += 16) {
414 emit_bytes (acfg, buf, size - i);
416 emit_bytes (acfg, buf, 16);
421 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
423 img_writer_emit_pointer_unaligned (acfg->w, target);
427 emit_pointer (MonoAotCompile *acfg, const char *target)
429 img_writer_emit_pointer (acfg->w, target);
433 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
435 if (prefix [0] != '\0') {
436 char *s = g_strdup_printf ("%s%s", prefix, target);
437 img_writer_emit_pointer (acfg->w, s);
440 img_writer_emit_pointer (acfg->w, target);
445 emit_int16 (MonoAotCompile *acfg, int value)
447 img_writer_emit_int16 (acfg->w, value);
451 emit_int32 (MonoAotCompile *acfg, int value)
453 img_writer_emit_int32 (acfg->w, value);
457 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
459 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
463 emit_zero_bytes (MonoAotCompile *acfg, int num)
465 img_writer_emit_zero_bytes (acfg->w, num);
469 emit_byte (MonoAotCompile *acfg, guint8 val)
471 img_writer_emit_byte (acfg->w, val);
474 #ifdef __native_client_codegen__
476 emit_nacl_call_alignment (MonoAotCompile *acfg)
478 img_writer_emit_nacl_call_alignment (acfg->w);
482 static G_GNUC_UNUSED void
483 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
485 img_writer_emit_global (acfg->w, name, func);
489 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
491 if (acfg->aot_opts.no_dlsym) {
492 g_ptr_array_add (acfg->globals, g_strdup (name));
493 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
495 img_writer_emit_global (acfg->w, name, func);
500 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
502 img_writer_emit_symbol_size (acfg->w, name, end_label);
506 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
508 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
510 /* On apple, all symbols need to be aligned to avoid warnings from ld */
511 emit_alignment (acfg, 4);
513 img_writer_emit_label (acfg->w, name);
514 img_writer_emit_string (acfg->w, value);
517 static G_GNUC_UNUSED void
518 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
521 guint8 b = value & 0x7f;
523 if (value != 0) /* more bytes to come */
529 static G_GNUC_UNUSED void
530 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
533 gboolean negative = (value < 0);
540 /* the following is unnecessary if the
541 * implementation of >>= uses an arithmetic rather
542 * than logical shift for a signed left operand
546 value |= - ((gint64)1 <<(size - 7));
547 /* sign bit of byte is second high order bit (0x40) */
548 if ((value == 0 && !(byte & 0x40)) ||
549 (value == -1 && (byte & 0x40)))
553 emit_byte (acfg, byte);
557 static G_GNUC_UNUSED void
558 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
563 guint8 b = value & 0x7f;
565 if (value != 0) /* more bytes to come */
573 static G_GNUC_UNUSED void
574 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
577 gboolean negative = (value < 0);
585 /* the following is unnecessary if the
586 * implementation of >>= uses an arithmetic rather
587 * than logical shift for a signed left operand
591 value |= - (1 <<(size - 7));
592 /* sign bit of byte is second high order bit (0x40) */
593 if ((value == 0 && !(byte & 0x40)) ||
594 (value == -1 && (byte & 0x40)))
605 emit_unset_mode (MonoAotCompile *acfg)
607 img_writer_emit_unset_mode (acfg->w);
610 static G_GNUC_UNUSED void
611 emit_set_thumb_mode (MonoAotCompile *acfg)
613 emit_unset_mode (acfg);
614 fprintf (acfg->fp, ".code 16\n");
617 static G_GNUC_UNUSED void
618 emit_set_arm_mode (MonoAotCompile *acfg)
620 emit_unset_mode (acfg);
621 fprintf (acfg->fp, ".code 32\n");
625 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
630 g_assert (size % 4 == 0);
631 emit_unset_mode (acfg);
632 for (i = 0; i < size; i += 4)
633 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
635 emit_bytes (acfg, buf, size);
639 /* ARCHITECTURE SPECIFIC CODE */
641 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
642 #define EMIT_DWARF_INFO 1
645 #if defined(TARGET_ARM)
646 #define AOT_FUNC_ALIGNMENT 4
648 #define AOT_FUNC_ALIGNMENT 16
650 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
651 #undef AOT_FUNC_ALIGNMENT
652 #define AOT_FUNC_ALIGNMENT 32
655 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
656 #define PPC_LD_OP "ld"
657 #define PPC_LDX_OP "ldx"
659 #define PPC_LD_OP "lwz"
660 #define PPC_LDX_OP "lwzx"
664 #define AOT_TARGET_STR "AMD64"
669 #define AOT_TARGET_STR "ARM (MACH)"
671 #define AOT_TARGET_STR "ARM (!MACH)"
677 #define AOT_TARGET_STR "ARM64 (MACH)"
679 #define AOT_TARGET_STR "ARM64 (!MACH)"
683 #ifdef TARGET_POWERPC64
684 #ifdef __mono_ilp32__
685 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
687 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
690 #ifdef TARGET_POWERPC
691 #ifdef __mono_ilp32__
692 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
694 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
701 #define AOT_TARGET_STR "X86 (WIN32)"
702 #elif defined(__native_client_codegen__)
703 #define AOT_TARGET_STR "X86 (native client codegen)"
705 #define AOT_TARGET_STR "X86 (!native client codegen)"
709 #ifndef AOT_TARGET_STR
710 #define AOT_TARGET_STR ""
714 arch_init (MonoAotCompile *acfg)
716 acfg->llc_args = g_string_new ("");
717 acfg->as_args = g_string_new ("");
720 * The prefix LLVM likes to put in front of symbol names on darwin.
721 * The mach-os specs require this for globals, but LLVM puts them in front of all
722 * symbols. We need to handle this, since we need to refer to LLVM generated
725 acfg->llvm_label_prefix = "";
726 acfg->user_symbol_prefix = "";
728 #if defined(TARGET_X86)
729 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
732 #if defined(TARGET_AMD64)
733 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
735 acfg->align_pad_value = 0x90;
739 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
740 g_string_append (acfg->llc_args, "-mattr=+v6");
743 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
744 g_string_append (acfg->as_args, " -mfpu=vfp3");
746 g_string_append (acfg->llc_args, " -soft-float");
749 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
750 acfg->thumb_mixed = TRUE;
752 if (acfg->aot_opts.mtriple)
753 mono_arch_set_target (acfg->aot_opts.mtriple);
757 acfg->inst_directive = ".inst";
758 if (acfg->aot_opts.mtriple)
759 mono_arch_set_target (acfg->aot_opts.mtriple);
763 acfg->user_symbol_prefix = "_";
764 acfg->llvm_label_prefix = "_";
765 acfg->inst_directive = ".word";
766 acfg->need_no_dead_strip = TRUE;
767 acfg->aot_opts.gnu_asm = TRUE;
770 #if defined(__linux__) && !defined(TARGET_ARM)
771 acfg->need_pt_gnu_stack = TRUE;
775 acfg->global_symbols = TRUE;
781 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
785 #ifdef MONO_ARCH_AOT_SUPPORTED
787 * arch_emit_direct_call:
789 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
793 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
795 #if defined(TARGET_X86) || defined(TARGET_AMD64)
796 /* Need to make sure this is exactly 5 bytes long */
797 if (!acfg->use_bin_writer) {
798 emit_unset_mode (acfg);
799 fprintf (acfg->fp, "call %s\n", target);
801 emit_byte (acfg, '\xe8');
802 emit_symbol_diff (acfg, target, ".", -4);
805 #elif defined(TARGET_ARM)
806 if (acfg->use_bin_writer) {
813 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
814 emit_bytes (acfg, buf, 4);
816 emit_unset_mode (acfg);
818 fprintf (acfg->fp, "blx %s\n", target);
820 fprintf (acfg->fp, "bl %s\n", target);
823 #elif defined(TARGET_ARM64)
824 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
825 #elif defined(TARGET_POWERPC)
826 if (acfg->use_bin_writer) {
827 g_assert_not_reached ();
829 emit_unset_mode (acfg);
830 fprintf (acfg->fp, "bl %s\n", target);
834 g_assert_not_reached ();
841 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
843 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
844 * in in the 2. slot of every GOT, and require every method to place the GOT
845 * address in r30, even when it doesn't access the GOT otherwise. This way,
846 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
851 * PPC64 uses function descriptors which greatly complicate all code, since
852 * these are used very inconsistently in the runtime. Some functions like
853 * mono_compile_method () return ftn descriptors, while others like the
854 * trampoline creation functions do not.
855 * We assume that all GOT slots contain function descriptors, and create
856 * descriptors in aot-runtime.c when needed.
857 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
858 * from function descriptors, we could do the same, but it would require
859 * rewriting all the ppc/aot code to handle function descriptors properly.
860 * So instead, we use the same approach as on PPC32.
861 * This is a horrible mess, but fixing it would probably lead to an even bigger
867 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
870 #ifdef MONO_ARCH_AOT_SUPPORTED
872 * arch_emit_got_offset:
874 * The memory pointed to by CODE should hold native code for computing the GOT
875 * address. Emit this code while patching it with the offset between code and
876 * the GOT. CODE_SIZE is set to the number of bytes emitted.
879 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
881 #if defined(TARGET_POWERPC64)
882 g_assert (!acfg->use_bin_writer);
883 emit_unset_mode (acfg);
885 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
886 * unsupported relocations. So we store the got address into the .Lgot_addr
887 * symbol which is in the text segment, compute its address, and load it.
889 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
890 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
891 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
892 fprintf (acfg->fp, "add 30, 30, 0\n");
893 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
894 acfg->label_generator ++;
896 #elif defined(TARGET_POWERPC)
897 g_assert (!acfg->use_bin_writer);
898 emit_unset_mode (acfg);
899 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
900 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
901 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
902 acfg->label_generator ++;
905 guint32 offset = mono_arch_get_patch_offset (code);
906 emit_bytes (acfg, code, offset);
907 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
909 *code_size = offset + 4;
914 * arch_emit_got_access:
916 * The memory pointed to by CODE should hold native code for loading a GOT
917 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
918 * CODE_SIZE is set to the number of bytes emitted.
921 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
923 /* This needs to emit the same code as OP_AOTCONST */
926 /* mov reg, got+offset(%rip) */
927 if (acfg->llvm_separate) {
928 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
932 /* Decode reg, see amd64_mov_reg_membase () */
933 rex_r = code [0] & AMD64_REX_R;
934 g_assert (code [0] == 0x49 + rex_r);
935 g_assert (code [1] == 0x8b);
936 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
938 emit_unset_mode (acfg);
939 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
942 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
943 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
944 *code_size = mono_arch_get_patch_offset (code) + 4;
946 #elif defined(TARGET_X86)
947 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
948 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
949 *code_size = mono_arch_get_patch_offset (code) + 4;
950 #elif defined(TARGET_ARM)
951 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
952 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
953 *code_size = mono_arch_get_patch_offset (code) + 4;
954 #elif defined(TARGET_ARM64)
955 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
956 arm64_emit_got_access (acfg, code, got_slot, code_size);
957 #elif defined(TARGET_POWERPC)
962 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
964 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
965 g_assert (code - buf == 8);
966 emit_bytes (acfg, buf, code - buf);
967 *code_size = code - buf;
970 g_assert_not_reached ();
976 #ifdef MONO_ARCH_AOT_SUPPORTED
978 * arch_emit_objc_selector_ref:
980 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
983 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
985 #if defined(TARGET_ARM)
988 int lindex = acfg->objc_selector_index_2 ++;
991 emit_bytes (acfg, code, 8);
993 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
994 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
996 emit_label (acfg, symbol1);
997 img_writer_emit_unset_mode (acfg->w);
998 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1001 #elif defined(TARGET_ARM64)
1002 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1004 g_assert_not_reached ();
1010 * arch_emit_plt_entry:
1012 * Emit code for the PLT entry with index INDEX.
1015 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
1017 #if defined(TARGET_X86)
1018 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1019 #if defined(__default_codegen__)
1020 /* jmp *<offset>(%ebx) */
1021 emit_byte (acfg, 0xff);
1022 emit_byte (acfg, 0xa3);
1023 emit_int32 (acfg, offset);
1024 /* Used by mono_aot_get_plt_info_offset */
1025 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1026 #elif defined(__native_client_codegen__)
1027 const guint8 kSizeOfNaClJmp = 11;
1028 guint8 bytes[kSizeOfNaClJmp];
1029 guint8 *pbytes = &bytes[0];
1031 x86_jump_membase32 (pbytes, X86_EBX, offset);
1032 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1033 /* four bytes of data, used by mono_arch_patch_plt_entry */
1034 /* For Native Client, make this work with data embedded in push. */
1035 emit_byte (acfg, 0x68); /* hide data in a push */
1036 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1037 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1038 #endif /*__native_client_codegen__*/
1039 #elif defined(TARGET_AMD64)
1040 #if defined(__default_codegen__)
1041 if (acfg->use_bin_writer) {
1042 emit_byte (acfg, '\xff');
1043 emit_byte (acfg, '\x25');
1044 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1046 emit_unset_mode (acfg);
1047 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
1049 /* Used by mono_aot_get_plt_info_offset */
1050 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1051 acfg->stats.plt_size += 10;
1052 #elif defined(__native_client_codegen__)
1054 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1055 guint8 *code = buf_aligned;
1057 /* mov <OFFSET>(%rip), %r11d */
1058 emit_byte (acfg, '\x45');
1059 emit_byte (acfg, '\x8b');
1060 emit_byte (acfg, '\x1d');
1061 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1063 amd64_jump_reg (code, AMD64_R11);
1064 /* This should be constant for the plt patch */
1065 g_assert ((size_t)(code-buf_aligned) == 10);
1066 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1068 /* Hide data in a push imm32 so it passes validation */
1069 emit_byte (acfg, 0x68); /* push */
1070 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1071 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1072 #endif /*__native_client_codegen__*/
1073 #elif defined(TARGET_ARM)
1078 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1079 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1080 emit_bytes (acfg, buf, code - buf);
1081 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1082 /* Used by mono_aot_get_plt_info_offset */
1083 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1084 #elif defined(TARGET_ARM64)
1085 arm64_emit_plt_entry (acfg, index);
1086 #elif defined(TARGET_POWERPC)
1087 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1089 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1090 g_assert (!acfg->use_bin_writer);
1091 emit_unset_mode (acfg);
1092 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1093 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1094 fprintf (acfg->fp, "add 11, 11, 30\n");
1095 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1096 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1097 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1098 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1100 fprintf (acfg->fp, "mtctr 11\n");
1101 fprintf (acfg->fp, "bctr\n");
1102 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1104 g_assert_not_reached ();
1109 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1111 #if defined(TARGET_ARM)
1113 /* LLVM calls the PLT entries using bl, so emit a stub */
1114 /* FIXME: Too much overhead on every call */
1115 fprintf (acfg->fp, ".thumb_func\n");
1116 fprintf (acfg->fp, "bx pc\n");
1117 fprintf (acfg->fp, "nop\n");
1118 fprintf (acfg->fp, ".arm\n");
1120 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1121 /* The caller already transitioned to thumb */
1122 /* The code below should be 12 bytes long */
1123 /* clang has trouble encoding these instructions, so emit the binary */
1125 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1126 /* thumb can't encode ld pc, [pc, ip] */
1127 fprintf (acfg->fp, "add ip, pc, ip\n");
1128 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1129 fprintf (acfg->fp, "bx ip\n");
1131 emit_set_thumb_mode (acfg);
1132 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1133 fprintf (acfg->fp, ".2byte 0x44fc\n");
1134 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1135 fprintf (acfg->fp, ".2byte 0x4760\n");
1136 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1137 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1138 emit_unset_mode (acfg);
1139 emit_set_arm_mode (acfg);
1141 g_assert_not_reached ();
1146 * arch_emit_specific_trampoline_pages:
1148 * Emits a page full of trampolines: each trampoline uses its own address to
1149 * lookup both the generic trampoline code and the data argument.
1150 * This page can be remapped in process multiple times so we can get an
1151 * unlimited number of trampolines.
1152 * Specifically this implementation uses the following trick: two memory pages
1153 * are allocated, with the first containing the data and the second containing the trampolines.
1154 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1155 * implementation does all the lifting.
1156 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1157 * on the arm 32 bit system.
1160 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1162 #if defined(TARGET_ARM)
1165 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1167 #define COMMON_TRAMP_SIZE 16
1168 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1169 int imm8, rot_amount;
1172 if (!acfg->aot_opts.use_trampolines_page)
1175 acfg->tramp_page_size = mono_pagesize ();
1177 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1178 emit_alignment (acfg, mono_pagesize ());
1179 emit_global (acfg, symbol, TRUE);
1180 emit_label (acfg, symbol);
1182 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1184 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1185 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1186 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1187 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1189 g_assert (code - buf == COMMON_TRAMP_SIZE);
1192 emit_bytes (acfg, buf, code - buf);
1194 for (i = 0; i < count; ++i) {
1196 ARM_PUSH (code, 0x5fff);
1198 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1199 g_assert (code - buf == 8);
1200 emit_bytes (acfg, buf, code - buf);
1203 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1204 * the instruction pointer address, so the generic trampoline at the start of the page
1205 * subtracts 4096 to get to the data page and loads the values
1206 * We again fit the generic trampiline in 16 bytes.
1208 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1209 emit_global (acfg, symbol, TRUE);
1210 emit_label (acfg, symbol);
1212 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1213 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1214 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1215 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1217 g_assert (code - buf == COMMON_TRAMP_SIZE);
1220 emit_bytes (acfg, buf, code - buf);
1222 for (i = 0; i < count; ++i) {
1224 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1226 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1227 g_assert (code - buf == 8);
1228 emit_bytes (acfg, buf, code - buf);
1232 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1234 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1235 emit_global (acfg, symbol, TRUE);
1236 emit_label (acfg, symbol);
1238 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1239 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1240 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1241 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1242 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1243 g_assert (code - buf == COMMON_TRAMP_SIZE);
1245 emit_bytes (acfg, buf, code - buf);
1247 for (i = 0; i < count; ++i) {
1249 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1251 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1252 g_assert (code - buf == 8);
1253 emit_bytes (acfg, buf, code - buf);
1256 /* now the imt trampolines: each specific trampolines puts in the ip register
1257 * the instruction pointer address, so the generic trampoline at the start of the page
1258 * subtracts 4096 to get to the data page and loads the values
1259 * We again fit the generic trampiline in 16 bytes.
1261 #define IMT_TRAMP_SIZE 72
1262 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1263 emit_global (acfg, symbol, TRUE);
1264 emit_label (acfg, symbol);
1266 /* Need at least two free registers, plus a slot for storing the pc */
1267 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1269 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1270 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1271 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1273 /* The IMT method is in v5, r0 has the imt array address */
1276 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1277 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1278 imt_found_check = code;
1279 ARM_B_COND (code, ARMCOND_EQ, 0);
1281 /* End-of-loop check */
1282 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1283 loop_end_check = code;
1284 ARM_B_COND (code, ARMCOND_EQ, 0);
1287 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1288 loop_branch_back = code;
1290 arm_patch (loop_branch_back, loop_start);
1293 arm_patch (imt_found_check, code);
1294 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1295 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1296 /* Save it to the third stack slot */
1297 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1298 /* Restore the registers and branch */
1299 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1302 arm_patch (loop_end_check, code);
1303 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1304 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1305 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1309 g_assert (code - buf == IMT_TRAMP_SIZE);
1310 emit_bytes (acfg, buf, code - buf);
1312 for (i = 0; i < count; ++i) {
1314 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1316 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1317 g_assert (code - buf == 8);
1318 emit_bytes (acfg, buf, code - buf);
1321 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1322 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1323 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1325 #elif defined(TARGET_ARM64)
1326 arm64_emit_specific_trampoline_pages (acfg);
1331 * arch_emit_specific_trampoline:
1333 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1334 * two GOT slots which contain the generic trampoline address and the trampoline
1335 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1338 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1341 * The trampolines created here are variations of the specific
1342 * trampolines created in mono_arch_create_specific_trampoline (). The
1344 * - the generic trampoline address is taken from a got slot.
1345 * - the offset of the got slot where the trampoline argument is stored
1346 * is embedded in the instruction stream, and the generic trampoline
1347 * can load the argument by loading the offset, adding it to the
1348 * address of the trampoline to get the address of the got slot, and
1349 * loading the argument from there.
1350 * - all the trampolines should be of the same length.
1352 #if defined(TARGET_AMD64)
1353 #if defined(__default_codegen__)
1354 /* This should be exactly 8 bytes long */
1356 /* call *<offset>(%rip) */
1357 if (acfg->llvm_separate) {
1358 emit_unset_mode (acfg);
1359 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1360 emit_zero_bytes (acfg, 2);
1362 emit_byte (acfg, '\x41');
1363 emit_byte (acfg, '\xff');
1364 emit_byte (acfg, '\x15');
1365 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1366 emit_zero_bytes (acfg, 1);
1368 #elif defined(__native_client_codegen__)
1370 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1371 guint8 *code = buf_aligned;
1376 /* Emit this call in 'code' so we can find out how long it is. */
1377 amd64_call_reg (code, AMD64_R11);
1378 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1379 call_len = code - call_start;
1381 /* The tramp_size is twice the NaCl alignment because it starts with */
1382 /* a call which needs to be aligned to the end of the boundary. */
1383 *tramp_size = kNaClAlignment*2;
1385 /* Emit nops to align call site below which is 7 bytes plus */
1386 /* the length of the call sequence emitted above. */
1387 /* Note: this requires the specific trampoline starts on a */
1388 /* kNaclAlignedment aligned address, which it does because */
1389 /* it's its own function that is aligned. */
1390 guint8 nop_buf[256];
1391 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1392 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1393 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1395 /* The trampoline is stored at the offset'th pointer, the -4 is */
1396 /* present because RIP relative addressing starts at the end of */
1397 /* the current instruction, while the label "." is relative to */
1398 /* the beginning of the current asm location, which in this case */
1399 /* is not the mov instruction, but the offset itself, due to the */
1400 /* way the bytes and ints are emitted here. */
1401 got_offset = (offset * sizeof(gpointer)) - 4;
1403 /* mov <OFFSET>(%rip), %r11d */
1404 emit_byte (acfg, '\x45');
1405 emit_byte (acfg, '\x8b');
1406 emit_byte (acfg, '\x1d');
1407 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1410 emit_bytes (acfg, call_start, call_len);
1412 /* The arg is stored at the offset+1 pointer, relative to beginning */
1413 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1414 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1416 /* We can't emit this data directly, hide in a "push imm32" */
1417 emit_byte (acfg, '\x68'); /* push */
1418 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1419 emit_alignment (acfg, kNaClAlignment);
1420 #endif /*__native_client_codegen__*/
1421 #elif defined(TARGET_ARM)
1425 /* This should be exactly 20 bytes long */
1428 ARM_PUSH (code, 0x5fff);
1429 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1430 /* Load the value from the GOT */
1431 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1433 ARM_BLX_REG (code, ARMREG_R1);
1435 g_assert (code - buf == 16);
1438 emit_bytes (acfg, buf, code - buf);
1440 * Only one offset is needed, since the second one would be equal to the
1443 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1444 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1445 #elif defined(TARGET_ARM64)
1446 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1447 #elif defined(TARGET_POWERPC)
1454 g_assert (!acfg->use_bin_writer);
1457 * PPC has no ip relative addressing, so we need to compute the address
1458 * of the mscorlib got. That is slow and complex, so instead, we store it
1459 * in the second got slot of every aot image. The caller already computed
1460 * the address of its got and placed it into r30.
1462 emit_unset_mode (acfg);
1463 /* Load mscorlib got address */
1464 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1465 /* Load generic trampoline address */
1466 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1467 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1468 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1469 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1470 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1472 fprintf (acfg->fp, "mtctr 11\n");
1473 /* Load trampoline argument */
1474 /* On ppc, we pass it normally to the generic trampoline */
1475 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1476 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1477 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1478 /* Branch to generic trampoline */
1479 fprintf (acfg->fp, "bctr\n");
1481 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1482 *tramp_size = 10 * 4;
1484 *tramp_size = 9 * 4;
1486 #elif defined(TARGET_X86)
1490 /* Similar to the PPC code above */
1492 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1494 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1495 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1496 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1500 /* Load mscorlib got address */
1501 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1502 /* Push trampoline argument */
1503 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1504 /* Load generic trampoline address */
1505 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1506 /* Branch to generic trampoline */
1507 x86_jump_reg (code, X86_ECX);
1509 #ifdef __native_client_codegen__
1511 /* emit nops to next 32 byte alignment */
1512 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1513 while (code < (buf + a)) x86_nop(code);
1516 emit_bytes (acfg, buf, code - buf);
1518 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1519 g_assert (code - buf == *tramp_size);
1521 g_assert_not_reached ();
1526 * arch_emit_unbox_trampoline:
1528 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1529 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1532 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1534 #if defined(TARGET_AMD64)
1539 this_reg = mono_arch_get_this_arg_reg (NULL);
1541 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1543 emit_bytes (acfg, buf, code - buf);
1545 if (acfg->llvm_separate) {
1546 emit_unset_mode (acfg);
1547 fprintf (acfg->fp, "jmp %s\n", call_target);
1549 emit_byte (acfg, '\xe9');
1550 emit_symbol_diff (acfg, call_target, ".", -4);
1552 #elif defined(TARGET_X86)
1559 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1561 emit_bytes (acfg, buf, code - buf);
1564 emit_byte (acfg, '\xe9');
1565 emit_symbol_diff (acfg, call_target, ".", -4);
1566 #elif defined(TARGET_ARM)
1570 if (acfg->thumb_mixed && cfg->compile_llvm) {
1571 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1572 fprintf (acfg->fp, "b %s\n", call_target);
1573 fprintf (acfg->fp, ".arm\n");
1574 fprintf (acfg->fp, ".align 2\n");
1580 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1582 emit_bytes (acfg, buf, code - buf);
1583 /* jump to method */
1584 if (acfg->use_bin_writer) {
1591 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1592 emit_bytes (acfg, buf, 4);
1594 if (acfg->thumb_mixed && cfg->compile_llvm)
1595 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1597 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1599 #elif defined(TARGET_ARM64)
1600 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1601 #elif defined(TARGET_POWERPC)
1604 g_assert (!acfg->use_bin_writer);
1606 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1607 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1609 g_assert_not_reached ();
1614 * arch_emit_static_rgctx_trampoline:
1616 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1617 * two GOT slots which contain the rgctx argument, and the method to jump to.
1618 * TRAMP_SIZE is set to the size of the emitted trampoline.
1619 * These kinds of trampolines cannot be enumerated statically, since there could
1620 * be one trampoline per method instantiation, so we emit the same code for all
1621 * trampolines, and parameterize them using two GOT slots.
1624 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1626 #if defined(TARGET_AMD64)
1627 #if defined(__default_codegen__)
1628 /* This should be exactly 13 bytes long */
1631 if (acfg->llvm_separate) {
1632 emit_unset_mode (acfg);
1633 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1634 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1636 /* mov <OFFSET>(%rip), %r10 */
1637 emit_byte (acfg, '\x4d');
1638 emit_byte (acfg, '\x8b');
1639 emit_byte (acfg, '\x15');
1640 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1642 /* jmp *<offset>(%rip) */
1643 emit_byte (acfg, '\xff');
1644 emit_byte (acfg, '\x25');
1645 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1647 #elif defined(__native_client_codegen__)
1649 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1650 guint8 *code = buf_aligned;
1652 /* mov <OFFSET>(%rip), %r10d */
1653 emit_byte (acfg, '\x45');
1654 emit_byte (acfg, '\x8b');
1655 emit_byte (acfg, '\x15');
1656 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1658 /* mov <OFFSET>(%rip), %r11d */
1659 emit_byte (acfg, '\x45');
1660 emit_byte (acfg, '\x8b');
1661 emit_byte (acfg, '\x1d');
1662 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1665 amd64_jump_reg (code, AMD64_R11);
1666 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1668 emit_alignment (acfg, kNaClAlignment);
1669 *tramp_size = kNaClAlignment;
1670 #endif /*__native_client_codegen__*/
1672 #elif defined(TARGET_ARM)
1676 /* This should be exactly 24 bytes long */
1679 /* Load rgctx value */
1680 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1681 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1682 /* Load branch addr + branch */
1683 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1684 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1686 g_assert (code - buf == 16);
1689 emit_bytes (acfg, buf, code - buf);
1690 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1691 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1692 #elif defined(TARGET_ARM64)
1693 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1694 #elif defined(TARGET_POWERPC)
1701 g_assert (!acfg->use_bin_writer);
1704 * PPC has no ip relative addressing, so we need to compute the address
1705 * of the mscorlib got. That is slow and complex, so instead, we store it
1706 * in the second got slot of every aot image. The caller already computed
1707 * the address of its got and placed it into r30.
1709 emit_unset_mode (acfg);
1710 /* Load mscorlib got address */
1711 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1713 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1714 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1715 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1716 /* Load target address */
1717 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1718 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1719 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1720 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1721 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1722 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1724 fprintf (acfg->fp, "mtctr 11\n");
1725 /* Branch to the target address */
1726 fprintf (acfg->fp, "bctr\n");
1728 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1729 *tramp_size = 11 * 4;
1731 *tramp_size = 9 * 4;
1734 #elif defined(TARGET_X86)
1738 /* Similar to the PPC code above */
1740 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1743 /* Load mscorlib got address */
1744 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1746 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1747 /* Branch to the target address */
1748 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1750 #ifdef __native_client_codegen__
1752 /* emit nops to next 32 byte alignment */
1753 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1754 while (code < (buf + a)) x86_nop(code);
1758 emit_bytes (acfg, buf, code - buf);
1760 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1761 g_assert (code - buf == *tramp_size);
1763 g_assert_not_reached ();
1768 * arch_emit_imt_thunk:
1770 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1771 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1772 * key is the IMT key, and ptr holds the address of a memory location holding
1773 * the address to branch to if the IMT arg matches the key. The array is
1774 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1776 * TRAMP_SIZE is set to the size of the emitted trampoline.
1779 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1781 #if defined(TARGET_AMD64)
1783 #if defined(__native_client_codegen__)
1786 guint8 *labels [16];
1788 guint8 *mov_buf_ptr = mov_buf;
1790 const int kSizeOfMove = 7;
1791 #if defined(__default_codegen__)
1792 code = buf = g_malloc (256);
1793 #elif defined(__native_client_codegen__)
1794 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1795 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1796 /* The RIP relative move below is emitted first */
1801 /* FIXME: Optimize this, i.e. use binary search etc. */
1802 /* Maybe move the body into a separate function (slower, but much smaller) */
1804 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1806 if (acfg->llvm_separate) {
1807 emit_unset_mode (acfg);
1808 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1812 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1814 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1817 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1819 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1822 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1823 amd64_jump_code (code, labels [0]);
1826 mono_amd64_patch (labels [2], code);
1827 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1828 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1831 mono_amd64_patch (labels [1], code);
1832 /* Load fail tramp */
1833 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1834 /* Check if there is a fail tramp */
1835 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1837 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1838 /* Jump to fail tramp */
1839 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1842 mono_amd64_patch (labels [3], code);
1843 x86_breakpoint (code);
1845 if (!acfg->llvm_separate) {
1846 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1847 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1848 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1849 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1850 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1851 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1853 emit_bytes (acfg, buf, code - buf);
1855 *tramp_size = code - buf + kSizeOfMove;
1856 #if defined(__native_client_codegen__)
1857 /* The tramp will be padded to the next kNaClAlignment bundle. */
1858 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1861 #if defined(__default_codegen__)
1863 #elif defined(__native_client_codegen__)
1867 #elif defined(TARGET_X86)
1869 #ifdef __native_client_codegen__
1872 guint8 *labels [16];
1874 #if defined(__default_codegen__)
1875 code = buf = g_malloc (256);
1876 #elif defined(__native_client_codegen__)
1877 buf_alloc = g_malloc (256 + kNaClAlignment);
1878 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1881 /* Allocate a temporary stack slot */
1882 x86_push_reg (code, X86_EAX);
1884 x86_push_reg (code, X86_EAX);
1886 /* Load mscorlib got address */
1887 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1889 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1892 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1894 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1897 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1899 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1902 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1903 x86_jump_code (code, labels [0]);
1906 mono_x86_patch (labels [2], code);
1907 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1908 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1909 /* Save the target address to the temporary stack location */
1910 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1912 x86_pop_reg (code, X86_EAX);
1913 /* Jump to the target address */
1917 mono_x86_patch (labels [1], code);
1918 /* Load fail tramp */
1919 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1920 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1922 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1923 /* Jump to fail tramp */
1924 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1925 x86_pop_reg (code, X86_EAX);
1929 mono_x86_patch (labels [3], code);
1930 x86_breakpoint (code);
1932 #ifdef __native_client_codegen__
1934 /* emit nops to next 32 byte alignment */
1935 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1936 while (code < (buf + a)) x86_nop(code);
1939 emit_bytes (acfg, buf, code - buf);
1941 *tramp_size = code - buf;
1943 #if defined(__default_codegen__)
1945 #elif defined(__native_client_codegen__)
1949 #elif defined(TARGET_ARM)
1951 guint8 *code, *code2, *labels [16];
1955 /* The IMT method is in v5 */
1957 /* Need at least two free registers, plus a slot for storing the pc */
1958 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1960 /* Load the parameter from the GOT */
1961 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1962 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1965 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1966 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1968 ARM_B_COND (code, ARMCOND_EQ, 0);
1970 /* End-of-loop check */
1971 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1973 ARM_B_COND (code, ARMCOND_EQ, 0);
1976 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1979 arm_patch (labels [4], labels [1]);
1982 arm_patch (labels [2], code);
1983 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1984 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1985 /* Save it to the third stack slot */
1986 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1987 /* Restore the registers and branch */
1988 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1991 arm_patch (labels [3], code);
1992 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1993 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1994 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1998 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2000 emit_bytes (acfg, buf, code - buf);
2001 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2003 *tramp_size = code - buf + 4;
2004 #elif defined(TARGET_ARM64)
2005 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2006 #elif defined(TARGET_POWERPC)
2008 guint8 *code, *labels [16];
2012 /* Load the mscorlib got address */
2013 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2014 /* Load the parameter from the GOT */
2015 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2016 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2018 /* Load and check key */
2020 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2021 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2023 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2025 /* End-of-loop check */
2026 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2028 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2031 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2034 mono_ppc_patch (labels [4], labels [1]);
2037 mono_ppc_patch (labels [2], code);
2038 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2039 /* r12 now contains the value of the vtable slot */
2040 /* this is not a function descriptor on ppc64 */
2041 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2042 ppc_mtctr (code, ppc_r12);
2043 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2046 mono_ppc_patch (labels [3], code);
2050 *tramp_size = code - buf;
2052 emit_bytes (acfg, buf, code - buf);
2054 g_assert_not_reached ();
2059 * arch_emit_gsharedvt_arg_trampoline:
2061 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2062 * two GOT slots which contain the argument, and the code to jump to.
2063 * TRAMP_SIZE is set to the size of the emitted trampoline.
2064 * These kinds of trampolines cannot be enumerated statically, since there could
2065 * be one trampoline per method instantiation, so we emit the same code for all
2066 * trampolines, and parameterize them using two GOT slots.
2069 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2071 #if defined(TARGET_X86)
2075 /* Similar to the PPC code above */
2077 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2080 /* Load mscorlib got address */
2081 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2083 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2084 /* Branch to the target address */
2085 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2087 #ifdef __native_client_codegen__
2089 /* emit nops to next 32 byte alignment */
2090 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2091 while (code < (buf + a)) x86_nop(code);
2095 emit_bytes (acfg, buf, code - buf);
2097 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2098 g_assert (code - buf == *tramp_size);
2099 #elif defined(TARGET_ARM)
2103 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2104 /* Similar to arch_emit_specific_trampoline () */
2107 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2108 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2109 /* Load the arg value from the GOT */
2110 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2111 /* Load the addr from the GOT */
2112 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2114 ARM_BX (code, ARMREG_R1);
2116 g_assert (code - buf == 20);
2119 emit_bytes (acfg, buf, code - buf);
2120 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2121 #elif defined(TARGET_ARM64)
2122 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2124 g_assert_not_reached ();
2129 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2131 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2132 /* Based on code generated by gcc */
2133 emit_unset_mode (acfg);
2136 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2137 ".section .ctors,\"aw\",@progbits\n"
2141 ".section .opd,\"aw\"\n"
2144 ".long .%s,.TOC.@tocbase32\n"
2147 ".type .%s,@function\n"
2149 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2151 ".section .ctors,\"aw\",@progbits\n"
2155 ".section .opd,\"aw\"\n"
2158 ".long .%1$s,.TOC.@tocbase32\n"
2159 ".size %1$s,.-%1$s\n"
2161 ".type .%1$s,@function\n"
2163 ".%1$s:\n", symbol);
2174 "lis 3, .Lglobals@h\n"
2175 "ori 3, 3, .Lglobals@l\n"
2176 "bl .mono_aot_register_module\n"
2184 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2186 ".size .%s,.-.%s\n", symbol, symbol);
2189 ".size .%1$s,.-.%1$s\n", symbol);
2195 /* END OF ARCH SPECIFIC CODE */
2198 mono_get_field_token (MonoClassField *field)
2200 MonoClass *klass = field->parent;
2203 for (i = 0; i < klass->field.count; ++i) {
2204 if (field == &klass->fields [i])
2205 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2208 g_assert_not_reached ();
2213 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2217 //printf ("ENCODE: %d 0x%x.\n", value, value);
2220 * Same encoding as the one used in the metadata, extended to handle values
2221 * greater than 0x1fffffff.
2223 if ((value >= 0) && (value <= 127))
2225 else if ((value >= 0) && (value <= 16383)) {
2226 p [0] = 0x80 | (value >> 8);
2227 p [1] = value & 0xff;
2229 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2230 p [0] = (value >> 24) | 0xc0;
2231 p [1] = (value >> 16) & 0xff;
2232 p [2] = (value >> 8) & 0xff;
2233 p [3] = value & 0xff;
2238 p [1] = (value >> 24) & 0xff;
2239 p [2] = (value >> 16) & 0xff;
2240 p [3] = (value >> 8) & 0xff;
2241 p [4] = value & 0xff;
2249 stream_init (MonoDynamicStream *sh)
2252 sh->alloc_size = 4096;
2253 sh->data = g_malloc (4096);
2255 /* So offsets are > 0 */
2261 make_room_in_stream (MonoDynamicStream *stream, int size)
2263 if (size <= stream->alloc_size)
2266 while (stream->alloc_size <= size) {
2267 if (stream->alloc_size < 4096)
2268 stream->alloc_size = 4096;
2270 stream->alloc_size *= 2;
2273 stream->data = g_realloc (stream->data, stream->alloc_size);
2277 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2281 make_room_in_stream (stream, stream->index + len);
2282 memcpy (stream->data + stream->index, data, len);
2283 idx = stream->index;
2284 stream->index += len;
2291 * Add data to the binary blob inside the aot image. Returns the offset inside the
2292 * blob where the data was stored.
2295 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2297 if (acfg->blob.alloc_size == 0)
2298 stream_init (&acfg->blob);
2300 return add_stream_data (&acfg->blob, (char*)data, data_len);
2304 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2309 if (acfg->blob.alloc_size == 0)
2310 stream_init (&acfg->blob);
2312 count = acfg->blob.index % align;
2314 /* we assume the stream data will be aligned */
2316 add_stream_data (&acfg->blob, buf, 4 - count);
2318 return add_stream_data (&acfg->blob, (char*)data, data_len);
2322 * emit_offset_table:
2324 * Emit a table of increasing offsets in a compact form using differential encoding.
2325 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2326 * group size, the more compact the table becomes, but the slower it becomes to compute
2327 * a given entry. Returns the size of the table.
2330 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2332 gint32 current_offset;
2333 int i, buf_size, ngroups, index_entry_size;
2335 guint32 *index_offsets;
2337 ngroups = (noffsets + (group_size - 1)) / group_size;
2339 index_offsets = g_new0 (guint32, ngroups);
2341 buf_size = noffsets * 4;
2342 p = buf = g_malloc0 (buf_size);
2345 for (i = 0; i < noffsets; ++i) {
2346 //printf ("D: %d -> %d\n", i, offsets [i]);
2347 if ((i % group_size) == 0) {
2348 index_offsets [i / group_size] = p - buf;
2349 /* Emit the full value for these entries */
2350 encode_value (offsets [i], p, &p);
2352 /* The offsets are allowed to be non-increasing */
2353 //g_assert (offsets [i] >= current_offset);
2354 encode_value (offsets [i] - current_offset, p, &p);
2356 current_offset = offsets [i];
2359 if (ngroups && index_offsets [ngroups - 1] < 65000)
2360 index_entry_size = 2;
2362 index_entry_size = 4;
2364 /* Emit the header */
2365 emit_int32 (acfg, noffsets);
2366 emit_int32 (acfg, group_size);
2367 emit_int32 (acfg, ngroups);
2368 emit_int32 (acfg, index_entry_size);
2370 /* Emit the index */
2371 for (i = 0; i < ngroups; ++i) {
2372 if (index_entry_size == 2)
2373 emit_int16 (acfg, index_offsets [i]);
2375 emit_int32 (acfg, index_offsets [i]);
2379 emit_bytes (acfg, buf, p - buf);
2381 return (int)(p - buf) + (ngroups * 4);
2385 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2389 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2393 index = g_hash_table_size (cfg->image_hash);
2394 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2395 g_ptr_array_add (cfg->image_table, image);
2401 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2404 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2406 /* FIXME: Search referenced images as well */
2407 if (!acfg->typespec_classes) {
2408 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2409 for (i = 0; i < len; ++i) {
2411 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2412 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2415 for (i = 0; i < len; ++i) {
2416 if (acfg->typespec_classes [i] == klass)
2421 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2427 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2430 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2433 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2436 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2439 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2444 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2448 if (klass->generic_class) {
2450 g_assert (klass->type_token);
2452 /* Find a typespec for a class if possible */
2453 token = find_typespec_for_class (acfg, klass);
2455 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2456 encode_value (token, p, &p);
2458 MonoClass *gclass = klass->generic_class->container_class;
2459 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2460 static int count = 0;
2463 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2464 encode_klass_ref (acfg, gclass, p, &p);
2465 encode_ginst (acfg, inst, p, &p);
2469 } else if (klass->type_token) {
2470 int iindex = get_image_index (acfg, klass->image);
2472 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2474 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2475 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2477 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2478 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2479 encode_value (get_image_index (acfg, klass->image), p, &p);
2481 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2482 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2483 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2485 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2486 encode_value (klass->byval_arg.type, p, &p);
2487 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2489 encode_value (container ? 1 : 0, p, &p);
2491 encode_value (container->is_method, p, &p);
2492 g_assert (par->serial == 0);
2493 if (container->is_method)
2494 encode_method_ref (acfg, container->owner.method, p, &p);
2496 encode_klass_ref (acfg, container->owner.klass, p, &p);
2498 encode_value (par->serial, p, &p);
2500 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2501 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2502 encode_type (acfg, &klass->byval_arg, p, &p);
2505 g_assert (klass->rank > 0);
2506 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2507 encode_value (klass->rank, p, &p);
2508 encode_klass_ref (acfg, klass->element_class, p, &p);
2516 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2517 * standard metadata encoding.
2520 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2522 gboolean shared = FALSE;
2525 * The encoding of generic instances is large so emit them only once.
2527 if (klass->generic_class) {
2529 g_assert (klass->type_token);
2531 /* Find a typespec for a class if possible */
2532 token = find_typespec_for_class (acfg, klass);
2535 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2540 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2544 buf2 = g_malloc (1024);
2547 encode_klass_ref_inner (acfg, klass, p, &p);
2548 g_assert (p - buf2 < 1024);
2550 offset = add_to_blob (acfg, buf2, p - buf2);
2553 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2559 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2560 encode_value (offset, p, &p);
2565 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2569 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2571 guint32 token = mono_get_field_token (field);
2574 encode_klass_ref (cfg, field->parent, p, &p);
2575 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2576 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2581 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2586 encode_value (inst->type_argc, p, &p);
2587 for (i = 0; i < inst->type_argc; ++i)
2588 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2593 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2596 MonoGenericInst *inst;
2598 inst = context->class_inst;
2600 g_assert (inst->type_argc);
2601 encode_ginst (acfg, inst, p, &p);
2603 encode_value (0, p, &p);
2605 inst = context->method_inst;
2607 g_assert (inst->type_argc);
2608 encode_ginst (acfg, inst, p, &p);
2610 encode_value (0, p, &p);
2616 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2620 g_assert (t->num_mods == 0);
2621 /* t->attrs can be ignored */
2622 //g_assert (t->attrs == 0);
2625 *p = MONO_TYPE_PINNED;
2629 *p = MONO_TYPE_BYREF;
2637 case MONO_TYPE_VOID:
2638 case MONO_TYPE_BOOLEAN:
2639 case MONO_TYPE_CHAR:
2652 case MONO_TYPE_STRING:
2653 case MONO_TYPE_OBJECT:
2654 case MONO_TYPE_TYPEDBYREF:
2656 case MONO_TYPE_VALUETYPE:
2657 case MONO_TYPE_CLASS:
2658 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2660 case MONO_TYPE_SZARRAY:
2661 encode_klass_ref (acfg, t->data.klass, p, &p);
2664 encode_type (acfg, t->data.type, p, &p);
2666 case MONO_TYPE_GENERICINST: {
2667 MonoClass *gclass = t->data.generic_class->container_class;
2668 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2670 encode_klass_ref (acfg, gclass, p, &p);
2671 encode_ginst (acfg, inst, p, &p);
2674 case MONO_TYPE_ARRAY: {
2675 MonoArrayType *array = t->data.array;
2678 encode_klass_ref (acfg, array->eklass, p, &p);
2679 encode_value (array->rank, p, &p);
2680 encode_value (array->numsizes, p, &p);
2681 for (i = 0; i < array->numsizes; ++i)
2682 encode_value (array->sizes [i], p, &p);
2683 encode_value (array->numlobounds, p, &p);
2684 for (i = 0; i < array->numlobounds; ++i)
2685 encode_value (array->lobounds [i], p, &p);
2689 case MONO_TYPE_MVAR:
2690 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2693 g_assert_not_reached ();
2700 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2706 /* Similar to the metadata encoding */
2707 if (sig->generic_param_count)
2711 if (sig->explicit_this)
2713 flags |= (sig->call_convention & 0x0F);
2717 if (sig->generic_param_count)
2718 encode_value (sig->generic_param_count, p, &p);
2719 encode_value (sig->param_count, p, &p);
2721 encode_type (acfg, sig->ret, p, &p);
2722 for (i = 0; i < sig->param_count; ++i) {
2723 if (sig->sentinelpos == i) {
2724 *p = MONO_TYPE_SENTINEL;
2727 encode_type (acfg, sig->params [i], p, &p);
2733 #define MAX_IMAGE_INDEX 250
2736 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2738 guint32 image_index = get_image_index (acfg, method->klass->image);
2739 guint32 token = method->token;
2740 MonoJumpInfoToken *ji;
2744 * The encoding for most methods is as follows:
2745 * - image index encoded as a leb128
2746 * - token index encoded as a leb128
2747 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2748 * types of method encodings.
2751 /* Mark methods which can't use aot trampolines because they need the further
2752 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2754 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2755 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2756 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2758 if (method->wrapper_type) {
2759 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2761 encode_value (method->wrapper_type, p, &p);
2763 switch (method->wrapper_type) {
2764 case MONO_WRAPPER_REMOTING_INVOKE:
2765 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2766 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2769 m = mono_marshal_method_from_wrapper (method);
2771 encode_method_ref (acfg, m, p, &p);
2774 case MONO_WRAPPER_PROXY_ISINST:
2775 case MONO_WRAPPER_LDFLD:
2776 case MONO_WRAPPER_LDFLDA:
2777 case MONO_WRAPPER_STFLD:
2778 case MONO_WRAPPER_ISINST: {
2779 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2782 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2785 case MONO_WRAPPER_LDFLD_REMOTE:
2786 case MONO_WRAPPER_STFLD_REMOTE:
2788 case MONO_WRAPPER_ALLOC: {
2789 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2791 /* The GC name is saved once in MonoAotFileInfo */
2792 g_assert (info->alloc_type != -1);
2793 encode_value (info->alloc_type, p, &p);
2796 case MONO_WRAPPER_WRITE_BARRIER:
2798 case MONO_WRAPPER_STELEMREF: {
2799 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2802 encode_value (info->subtype, p, &p);
2803 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2804 encode_value (info->d.virtual_stelemref.kind, p, &p);
2807 case MONO_WRAPPER_UNKNOWN: {
2808 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2811 encode_value (info->subtype, p, &p);
2812 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2813 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2814 encode_klass_ref (acfg, method->klass, p, &p);
2815 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2816 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2817 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2818 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2821 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2822 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2825 encode_value (info->subtype, p, &p);
2826 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2827 strcpy ((char*)p, method->name);
2828 p += strlen (method->name) + 1;
2829 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2830 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2832 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2833 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2837 case MONO_WRAPPER_SYNCHRONIZED: {
2840 m = mono_marshal_method_from_wrapper (method);
2842 g_assert (m != method);
2843 encode_method_ref (acfg, m, p, &p);
2846 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2847 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2850 encode_value (info->subtype, p, &p);
2852 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2853 encode_value (info->d.element_addr.rank, p, &p);
2854 encode_value (info->d.element_addr.elem_size, p, &p);
2855 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2856 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2858 g_assert_not_reached ();
2862 case MONO_WRAPPER_CASTCLASS: {
2863 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2866 encode_value (info->subtype, p, &p);
2869 case MONO_WRAPPER_RUNTIME_INVOKE: {
2870 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2873 encode_value (info->subtype, p, &p);
2874 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2875 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2876 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2877 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2880 case MONO_WRAPPER_DELEGATE_INVOKE:
2881 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2882 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2883 if (method->is_inflated) {
2884 /* These wrappers are identified by their class */
2885 encode_value (1, p, &p);
2886 encode_klass_ref (acfg, method->klass, p, &p);
2888 MonoMethodSignature *sig = mono_method_signature (method);
2889 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2891 encode_value (0, p, &p);
2892 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2893 encode_value (info ? info->subtype : 0, p, &p);
2894 encode_signature (acfg, sig, p, &p);
2898 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2899 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2902 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2903 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2907 g_assert_not_reached ();
2909 } else if (mono_method_signature (method)->is_inflated) {
2911 * This is a generic method, find the original token which referenced it and
2913 * Obtain the token from information recorded by the JIT.
2915 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2917 image_index = get_image_index (acfg, ji->image);
2918 g_assert (image_index < MAX_IMAGE_INDEX);
2921 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2922 encode_value (image_index, p, &p);
2923 encode_value (token, p, &p);
2925 MonoMethod *declaring;
2926 MonoGenericContext *context = mono_method_get_context (method);
2928 g_assert (method->is_inflated);
2929 declaring = ((MonoMethodInflated*)method)->declaring;
2932 * This might be a non-generic method of a generic instance, which
2933 * doesn't have a token since the reference is generated by the JIT
2934 * like Nullable:Box/Unbox, or by generic sharing.
2936 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2937 /* Encode the klass */
2938 encode_klass_ref (acfg, method->klass, p, &p);
2939 /* Encode the method */
2940 image_index = get_image_index (acfg, method->klass->image);
2941 g_assert (image_index < MAX_IMAGE_INDEX);
2942 g_assert (declaring->token);
2943 token = declaring->token;
2944 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2945 encode_value (image_index, p, &p);
2946 encode_value (token, p, &p);
2947 encode_generic_context (acfg, context, p, &p);
2949 } else if (token == 0) {
2950 /* This might be a method of a constructed type like int[,].Set */
2951 /* Obtain the token from information recorded by the JIT */
2952 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2954 image_index = get_image_index (acfg, ji->image);
2955 g_assert (image_index < MAX_IMAGE_INDEX);
2958 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2959 encode_value (image_index, p, &p);
2960 encode_value (token, p, &p);
2963 g_assert (method->klass->rank);
2965 /* Encode directly */
2966 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2967 encode_klass_ref (acfg, method->klass, p, &p);
2968 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2969 encode_value (0, p, &p);
2970 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2971 encode_value (1, p, &p);
2972 else if (!strcmp (method->name, "Get"))
2973 encode_value (2, p, &p);
2974 else if (!strcmp (method->name, "Address"))
2975 encode_value (3, p, &p);
2976 else if (!strcmp (method->name, "Set"))
2977 encode_value (4, p, &p);
2979 g_assert_not_reached ();
2982 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2984 if (image_index >= MONO_AOT_METHODREF_MIN) {
2985 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2986 encode_value (image_index, p, &p);
2987 encode_value (mono_metadata_token_index (token), p, &p);
2989 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2996 compare_patches (gconstpointer a, gconstpointer b)
3000 i = (*(MonoJumpInfo**)a)->ip.i;
3001 j = (*(MonoJumpInfo**)b)->ip.i;
3012 static G_GNUC_UNUSED char*
3013 patch_to_string (MonoJumpInfo *patch_info)
3017 str = g_string_new ("");
3019 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3021 switch (patch_info->type) {
3022 case MONO_PATCH_INFO_VTABLE:
3023 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3028 g_string_append_printf (str, ")");
3029 return g_string_free (str, FALSE);
3035 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3038 static inline gboolean
3039 is_plt_patch (MonoJumpInfo *patch_info)
3041 switch (patch_info->type) {
3042 case MONO_PATCH_INFO_METHOD:
3043 case MONO_PATCH_INFO_INTERNAL_METHOD:
3044 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3045 case MONO_PATCH_INFO_ICALL_ADDR:
3046 case MONO_PATCH_INFO_CLASS_INIT:
3047 case MONO_PATCH_INFO_RGCTX_FETCH:
3048 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3049 case MONO_PATCH_INFO_MONITOR_ENTER:
3050 case MONO_PATCH_INFO_MONITOR_EXIT:
3051 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3061 * Return the symbol identifying the plt entry PLT_OFFSET.
3064 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3068 * The Apple linker reorganizes object files, so it doesn't like branches to local
3069 * labels, since those have no relocations.
3071 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3073 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3080 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3082 static MonoPltEntry*
3083 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3087 if (!is_plt_patch (patch_info))
3090 if (!acfg->patch_to_plt_entry [patch_info->type])
3091 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3092 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3094 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3096 * Allocate a separate PLT slot for each such patch, since some plt
3097 * entries will refer to the method itself, and some will refer to the
3104 MonoJumpInfo *new_ji;
3106 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3108 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3109 res->plt_offset = acfg->plt_offset;
3111 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3112 if (acfg->aot_opts.write_symbols)
3113 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3115 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3117 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3119 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3121 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3123 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3124 //mono_print_ji (patch_info); printf ("\n");
3125 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3127 acfg->plt_offset ++;
3136 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3137 * JI could be found if it exists, otherwise allocates a new one.
3140 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3143 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3145 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3147 return got_offset - 1;
3150 got_offset = acfg->llvm_got_offset;
3151 acfg->llvm_got_offset ++;
3153 got_offset = acfg->got_offset;
3154 acfg->got_offset ++;
3157 acfg->stats.got_slots ++;
3158 acfg->stats.got_slot_types [ji->type] ++;
3160 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3161 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3162 g_ptr_array_add (info->got_patches, ji);
3167 /* Add a method to the list of methods which need to be emitted */
3169 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3172 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3173 g_ptr_array_add (acfg->methods, method);
3174 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3175 acfg->nmethods = acfg->methods->len + 1;
3178 if (method->wrapper_type || extra)
3179 g_ptr_array_add (acfg->extra_methods, method);
3183 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3185 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3193 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3197 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3201 index = acfg->method_index;
3202 add_method_with_index (acfg, method, index, extra);
3204 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3206 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3208 acfg->method_index ++;
3214 add_method (MonoAotCompile *acfg, MonoMethod *method)
3216 return add_method_full (acfg, method, FALSE, 0);
3220 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3222 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3223 method = mini_get_shared_method (method);
3225 if (acfg->aot_opts.log_generics)
3226 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3228 add_method_full (acfg, method, TRUE, depth);
3232 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3234 add_extra_method_with_depth (acfg, method, 0);
3238 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3240 MonoAotCompile *acfg = user_data;
3241 MonoJitICallInfo *callinfo = value;
3242 MonoMethod *wrapper;
3248 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3249 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3252 add_method (acfg, wrapper);
3256 get_runtime_invoke_sig (MonoMethodSignature *sig)
3258 MonoMethodBuilder *mb;
3261 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3262 m = mono_mb_create_method (mb, sig, 16);
3263 return mono_marshal_get_runtime_invoke (m, FALSE);
3267 can_marshal_struct (MonoClass *klass)
3269 MonoClassField *field;
3270 gboolean can_marshal = TRUE;
3271 gpointer iter = NULL;
3272 MonoMarshalType *info;
3275 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3278 info = mono_marshal_load_type_info (klass);
3280 /* Only allow a few field types to avoid asserts in the marshalling code */
3281 while ((field = mono_class_get_fields (klass, &iter))) {
3282 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3285 switch (field->type->type) {
3290 case MONO_TYPE_BOOLEAN:
3293 case MONO_TYPE_CHAR:
3301 case MONO_TYPE_STRING:
3303 case MONO_TYPE_VALUETYPE:
3304 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3305 can_marshal = FALSE;
3307 case MONO_TYPE_SZARRAY: {
3308 gboolean has_mspec = FALSE;
3311 for (i = 0; i < info->num_fields; ++i) {
3312 if (info->fields [i].field == field && info->fields [i].mspec)
3317 can_marshal = FALSE;
3321 can_marshal = FALSE;
3327 /* Its hard to compute whenever these can be marshalled or not */
3328 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3335 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3337 /* Create a vtype instantiation */
3338 MonoGenericContext shared_context;
3340 MonoGenericInst *inst;
3341 MonoGenericContainer *container;
3342 MonoClass **constraints;
3345 memset (ctx, 0, sizeof (MonoGenericContext));
3347 if (method->klass->generic_container) {
3348 shared_context = method->klass->generic_container->context;
3349 inst = shared_context.class_inst;
3351 args = g_new0 (MonoType*, inst->type_argc);
3352 for (i = 0; i < inst->type_argc; ++i) {
3353 args [i] = &mono_defaults.int_class->byval_arg;
3355 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3357 if (method->is_generic) {
3358 container = mono_method_get_generic_container (method);
3359 shared_context = container->context;
3360 inst = shared_context.method_inst;
3362 args = g_new0 (MonoType*, inst->type_argc);
3363 for (i = 0; i < container->type_argc; ++i) {
3364 MonoGenericParamInfo *info = &container->type_params [i].info;
3365 gboolean ref_only = FALSE;
3367 if (info && info->constraints) {
3368 constraints = info->constraints;
3370 while (*constraints) {
3371 MonoClass *cklass = *constraints;
3372 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3373 /* Inflaring the method with our vtype would not be valid */
3380 args [i] = &mono_defaults.object_class->byval_arg;
3382 args [i] = &mono_defaults.int_class->byval_arg;
3384 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3389 add_wrappers (MonoAotCompile *acfg)
3391 MonoMethod *method, *m;
3393 MonoMethodSignature *sig, *csig;
3397 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3398 * so there is only one wrapper of a given type, or inlining their contents into their
3401 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3403 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3404 gboolean skip = FALSE;
3406 method = mono_get_method (acfg->image, token, NULL);
3408 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3409 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3410 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3413 /* Skip methods which can not be handled by get_runtime_invoke () */
3414 sig = mono_method_signature (method);
3417 if ((sig->ret->type == MONO_TYPE_PTR) ||
3418 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3420 if (mono_class_is_open_constructed_type (sig->ret))
3423 for (j = 0; j < sig->param_count; j++) {
3424 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3426 if (mono_class_is_open_constructed_type (sig->params [j]))
3430 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3431 if (!mono_class_is_contextbound (method->klass)) {
3432 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3433 gboolean has_nullable = FALSE;
3435 for (j = 0; j < sig->param_count; j++) {
3436 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3437 has_nullable = TRUE;
3440 if (info && !has_nullable) {
3441 /* Supported by the dynamic runtime-invoke wrapper */
3445 mono_arch_dyn_call_free (info);
3450 //printf ("%s\n", mono_method_full_name (method, TRUE));
3451 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3455 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3456 MonoMethodDesc *desc;
3457 MonoMethod *orig_method;
3460 /* Runtime invoke wrappers */
3462 /* void runtime-invoke () [.cctor] */
3463 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3464 csig->ret = &mono_defaults.void_class->byval_arg;
3465 add_method (acfg, get_runtime_invoke_sig (csig));
3467 /* void runtime-invoke () [Finalize] */
3468 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3470 csig->ret = &mono_defaults.void_class->byval_arg;
3471 add_method (acfg, get_runtime_invoke_sig (csig));
3473 /* void runtime-invoke (string) [exception ctor] */
3474 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3476 csig->ret = &mono_defaults.void_class->byval_arg;
3477 csig->params [0] = &mono_defaults.string_class->byval_arg;
3478 add_method (acfg, get_runtime_invoke_sig (csig));
3480 /* void runtime-invoke (string, string) [exception ctor] */
3481 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3483 csig->ret = &mono_defaults.void_class->byval_arg;
3484 csig->params [0] = &mono_defaults.string_class->byval_arg;
3485 csig->params [1] = &mono_defaults.string_class->byval_arg;
3486 add_method (acfg, get_runtime_invoke_sig (csig));
3488 /* string runtime-invoke () [Exception.ToString ()] */
3489 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3491 csig->ret = &mono_defaults.string_class->byval_arg;
3492 add_method (acfg, get_runtime_invoke_sig (csig));
3494 /* void runtime-invoke (string, Exception) [exception ctor] */
3495 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3497 csig->ret = &mono_defaults.void_class->byval_arg;
3498 csig->params [0] = &mono_defaults.string_class->byval_arg;
3499 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3500 add_method (acfg, get_runtime_invoke_sig (csig));
3502 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3503 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3505 csig->ret = &(mono_class_from_name (
3506 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3507 csig->params [0] = &mono_defaults.string_class->byval_arg;
3508 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3509 add_method (acfg, get_runtime_invoke_sig (csig));
3511 /* runtime-invoke used by finalizers */
3512 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3514 /* This is used by mono_runtime_capture_context () */
3515 method = mono_get_context_capture_method ();
3517 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3519 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3520 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3524 add_method (acfg, mono_marshal_get_stelemref ());
3526 if (MONO_ARCH_HAVE_TLS_GET) {
3527 /* Managed Allocators */
3528 nallocators = mono_gc_get_managed_allocator_types ();
3529 for (i = 0; i < nallocators; ++i) {
3530 m = mono_gc_get_managed_allocator_by_type (i);
3532 add_method (acfg, m);
3535 /* Monitor Enter/Exit */
3536 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3537 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3538 /* This is a v4 method */
3540 method = mono_monitor_get_fast_path (orig_method);
3542 add_method (acfg, method);
3544 mono_method_desc_free (desc);
3546 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3547 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3548 g_assert (orig_method);
3549 mono_method_desc_free (desc);
3550 method = mono_monitor_get_fast_path (orig_method);
3552 add_method (acfg, method);
3555 /* Stelemref wrappers */
3557 MonoMethod **wrappers;
3560 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3561 for (i = 0; i < nwrappers; ++i)
3562 add_method (acfg, wrappers [i]);
3566 /* castclass_with_check wrapper */
3567 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3568 /* isinst_with_check wrapper */
3569 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3571 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3573 MonoMethodDesc *desc;
3576 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3577 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3578 mono_method_desc_free (desc);
3580 m = mono_monitor_get_fast_path (m);
3582 add_method (acfg, m);
3587 /* JIT icall wrappers */
3588 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3589 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3593 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3594 * we use the original method instead at runtime.
3595 * Since full-aot doesn't support remoting, this is not a problem.
3598 /* remoting-invoke wrappers */
3599 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3600 MonoMethodSignature *sig;
3602 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3603 method = mono_get_method (acfg->image, token, NULL);
3605 sig = mono_method_signature (method);
3607 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3608 m = mono_marshal_get_remoting_invoke_with_check (method);
3610 add_method (acfg, m);
3615 /* delegate-invoke wrappers */
3616 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3619 MonoCustomAttrInfo *cattr;
3621 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3622 klass = mono_class_get_checked (acfg->image, token, &error);
3625 mono_error_cleanup (&error);
3629 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3632 if (!klass->generic_container) {
3633 method = mono_get_delegate_invoke (klass);
3635 m = mono_marshal_get_delegate_invoke (method, NULL);
3637 add_method (acfg, m);
3639 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3641 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3643 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3645 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3647 cattr = mono_custom_attrs_from_class (klass);
3652 for (j = 0; j < cattr->num_attrs; ++j)
3653 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3655 if (j < cattr->num_attrs)
3656 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3658 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3659 MonoGenericContext ctx;
3660 MonoMethod *inst, *gshared;
3663 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3666 method = mono_get_delegate_invoke (klass);
3667 create_gsharedvt_inst (acfg, method, &ctx);
3669 inst = mono_class_inflate_generic_method (method, &ctx);
3671 m = mono_marshal_get_delegate_invoke (inst, NULL);
3672 g_assert (m->is_inflated);
3674 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3675 add_extra_method (acfg, gshared);
3678 method = mono_get_delegate_begin_invoke (klass);
3679 create_gsharedvt_inst (acfg, method, &ctx);
3681 inst = mono_class_inflate_generic_method (method, &ctx);
3683 m = mono_marshal_get_delegate_begin_invoke (inst);
3684 g_assert (m->is_inflated);
3686 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3687 add_extra_method (acfg, gshared);
3690 method = mono_get_delegate_end_invoke (klass);
3691 create_gsharedvt_inst (acfg, method, &ctx);
3693 inst = mono_class_inflate_generic_method (method, &ctx);
3695 m = mono_marshal_get_delegate_end_invoke (inst);
3696 g_assert (m->is_inflated);
3698 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3699 add_extra_method (acfg, gshared);
3704 /* array access wrappers */
3705 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3709 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3710 klass = mono_class_get_checked (acfg->image, token, &error);
3713 mono_error_cleanup (&error);
3717 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3718 MonoMethod *m, *wrapper;
3720 /* Add runtime-invoke wrappers too */
3722 m = mono_class_get_method_from_name (klass, "Get", -1);
3724 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3725 add_extra_method (acfg, wrapper);
3726 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3728 m = mono_class_get_method_from_name (klass, "Set", -1);
3730 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3731 add_extra_method (acfg, wrapper);
3732 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3736 /* Synchronized wrappers */
3737 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3738 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3739 method = mono_get_method (acfg->image, token, NULL);
3741 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3742 if (method->is_generic) {
3744 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3745 MonoGenericContext ctx;
3746 MonoMethod *inst, *gshared, *m;
3749 * Create a generic wrapper for a generic instance, and AOT that.
3751 create_gsharedvt_inst (acfg, method, &ctx);
3752 inst = mono_class_inflate_generic_method (method, &ctx);
3753 m = mono_marshal_get_synchronized_wrapper (inst);
3754 g_assert (m->is_inflated);
3755 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3756 add_method (acfg, gshared);
3758 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3763 /* pinvoke wrappers */
3764 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3766 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3768 method = mono_get_method (acfg->image, token, NULL);
3770 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3771 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3772 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3776 /* native-to-managed wrappers */
3777 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3779 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3780 MonoCustomAttrInfo *cattr;
3783 method = mono_get_method (acfg->image, token, NULL);
3786 * Only generate native-to-managed wrappers for methods which have an
3787 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3788 * name to avoid defining a new assembly to contain it.
3790 cattr = mono_custom_attrs_from_method (method);
3793 for (j = 0; j < cattr->num_attrs; ++j)
3794 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3796 if (j < cattr->num_attrs) {
3797 MonoCustomAttrEntry *e = &cattr->attrs [j];
3798 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3799 const char *p = (const char*)e->data;
3801 int slen, num_named, named_type, data_type;
3805 char *export_name = NULL;
3806 MonoMethod *wrapper;
3808 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3809 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3810 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3811 mono_method_full_name (method, TRUE));
3815 g_assert (sig->param_count == 1);
3816 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3819 * Decode the cattr manually since we can't create objects
3820 * during aot compilation.
3826 /* From load_cattr_value () in reflection.c */
3827 slen = mono_metadata_decode_value (p, &p);
3828 n = g_memdup (p, slen + 1);
3830 t = mono_reflection_type_from_name (n, acfg->image);
3834 klass = mono_class_from_mono_type (t);
3835 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3839 num_named = read16 (p);
3842 g_assert (num_named < 2);
3843 if (num_named == 1) {
3846 MonoType *prop_type;
3848 /* parse ExportSymbol attribute */
3850 named_type = *named;
3855 name_len = mono_metadata_decode_blob_size (named, &named);
3856 name = g_malloc (name_len + 1);
3857 memcpy (name, named, name_len);
3858 name [name_len] = 0;
3861 g_assert (named_type == 0x54);
3862 g_assert (!strcmp (name, "ExportSymbol"));
3864 prop_type = &mono_defaults.string_class->byval_arg;
3866 /* load_cattr_value (), string case */
3867 g_assert (*named != (char)0xff);
3868 slen = mono_metadata_decode_value (named, &named);
3869 export_name = g_malloc (slen + 1);
3870 memcpy (export_name, named, slen);
3871 export_name [slen] = 0;
3875 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3876 add_method (acfg, wrapper);
3878 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3882 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3883 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3884 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3888 /* StructureToPtr/PtrToStructure wrappers */
3889 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3893 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3894 klass = mono_class_get_checked (acfg->image, token, &error);
3897 mono_error_cleanup (&error);
3901 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3902 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3903 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3904 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3910 has_type_vars (MonoClass *klass)
3912 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3915 return has_type_vars (klass->element_class);
3916 if (klass->generic_class) {
3917 MonoGenericContext *context = &klass->generic_class->context;
3918 if (context->class_inst) {
3921 for (i = 0; i < context->class_inst->type_argc; ++i)
3922 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3926 if (klass->generic_container)
3932 is_vt_inst (MonoGenericInst *inst)
3936 for (i = 0; i < inst->type_argc; ++i) {
3937 MonoType *t = inst->type_argv [i];
3938 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3945 method_has_type_vars (MonoMethod *method)
3947 if (has_type_vars (method->klass))
3950 if (method->is_inflated) {
3951 MonoGenericContext *context = mono_method_get_context (method);
3952 if (context->method_inst) {
3955 for (i = 0; i < context->method_inst->type_argc; ++i)
3956 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3963 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3966 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3968 /* This might lead to a huge code blowup so only do it if neccesary */
3969 if (!acfg->aot_opts.full_aot && !force)
3972 add_generic_class_with_depth (acfg, klass, 0, ref);
3976 check_type_depth (MonoType *t, int depth)
3984 case MONO_TYPE_GENERICINST: {
3985 MonoGenericClass *gklass = t->data.generic_class;
3986 MonoGenericInst *ginst = gklass->context.class_inst;
3989 for (i = 0; i < ginst->type_argc; ++i) {
3990 if (check_type_depth (ginst->type_argv [i], depth + 1))
4004 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4007 * add_generic_class:
4009 * Add all methods of a generic class.
4012 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4015 MonoClassField *field;
4017 gboolean use_gsharedvt = FALSE;
4019 if (!acfg->ginst_hash)
4020 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4022 mono_class_init (klass);
4024 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4027 if (has_type_vars (klass))
4030 if (!klass->generic_class && !klass->rank)
4033 if (klass->exception_type)
4036 if (!acfg->ginst_hash)
4037 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4039 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4042 if (check_type_depth (&klass->byval_arg, 0))
4045 if (acfg->aot_opts.log_generics)
4046 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4048 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4051 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4052 * Enable this only for some classes since gsharedvt might not support all methods.
4054 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) &&
4055 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4056 use_gsharedvt = TRUE;
4059 while ((method = mono_class_get_methods (klass, &iter))) {
4060 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4062 * This is partial sharing, and we can't handle it yet
4067 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4069 add_types_from_method_header (acfg, method);
4073 if (method->is_generic)
4078 * FIXME: Instances which are referenced by these methods are not added,
4079 * for example Array.Resize<int> for List<int>.Add ().
4081 add_extra_method_with_depth (acfg, method, depth + 1);
4085 while ((field = mono_class_get_fields (klass, &iter))) {
4086 if (field->type->type == MONO_TYPE_GENERICINST)
4087 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4090 if (klass->delegate) {
4091 method = mono_get_delegate_invoke (klass);
4093 method = mono_marshal_get_delegate_invoke (method, NULL);
4095 if (acfg->aot_opts.log_generics)
4096 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4098 add_method (acfg, method);
4101 /* Add superclasses */
4103 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4106 * For ICollection<T>, add instances of the helper methods
4107 * in Array, since a T[] could be cast to ICollection<T>.
4109 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4110 (!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"))) {
4111 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4112 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4116 if (!strcmp (klass->name, "IEnumerator`1"))
4117 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4119 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4121 /* Add the T[]/InternalEnumerator class */
4122 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4126 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4127 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4131 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4132 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4136 while ((method = mono_class_get_methods (array_class, &iter))) {
4137 if (strstr (method->name, name_prefix)) {
4138 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4140 add_extra_method_with_depth (acfg, m, depth);
4144 g_free (name_prefix);
4147 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4148 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4149 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4150 MonoClass *icomparable, *gcomparer;
4151 MonoGenericContext ctx;
4152 MonoType *args [16];
4154 memset (&ctx, 0, sizeof (ctx));
4156 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4157 g_assert (icomparable);
4158 args [0] = &tclass->byval_arg;
4159 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4161 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4162 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4163 g_assert (gcomparer);
4164 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4168 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4169 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4170 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4171 MonoClass *iface, *gcomparer;
4172 MonoGenericContext ctx;
4173 MonoType *args [16];
4175 memset (&ctx, 0, sizeof (ctx));
4177 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4179 args [0] = &tclass->byval_arg;
4180 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4182 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4183 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4184 g_assert (gcomparer);
4185 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4191 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4194 MonoGenericContext ctx;
4195 MonoType *args [16];
4197 if (acfg->aot_opts.no_instances)
4200 memset (&ctx, 0, sizeof (ctx));
4202 for (i = 0; i < ninsts; ++i) {
4203 args [0] = insts [i];
4204 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4205 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4210 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4212 MonoMethodHeader *header;
4213 MonoMethodSignature *sig;
4216 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4218 sig = mono_method_signature (method);
4221 for (j = 0; j < sig->param_count; ++j)
4222 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4223 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4226 header = mono_method_get_header (method);
4229 for (j = 0; j < header->num_locals; ++j)
4230 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4231 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4233 mono_loader_clear_error ();
4238 * add_generic_instances:
4240 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4243 add_generic_instances (MonoAotCompile *acfg)
4248 MonoGenericContext *context;
4250 if (acfg->aot_opts.no_instances)
4253 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4254 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4255 method = mono_get_method (acfg->image, token, NULL);
4260 if (method->klass->image != acfg->image)
4263 context = mono_method_get_context (method);
4265 if (context && ((context->class_inst && context->class_inst->is_open)))
4269 * For open methods, create an instantiation which can be passed to the JIT.
4270 * FIXME: Handle class_inst as well.
4272 if (context && context->method_inst && context->method_inst->is_open) {
4273 MonoGenericContext shared_context;
4274 MonoGenericInst *inst;
4275 MonoType **type_argv;
4277 MonoMethod *declaring_method;
4278 gboolean supported = TRUE;
4280 /* Check that the context doesn't contain open constructed types */
4281 if (context->class_inst) {
4282 inst = context->class_inst;
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)
4286 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4290 if (context->method_inst) {
4291 inst = context->method_inst;
4292 for (i = 0; i < inst->type_argc; ++i) {
4293 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)
4295 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4303 memset (&shared_context, 0, sizeof (MonoGenericContext));
4305 inst = context->class_inst;
4307 type_argv = g_new0 (MonoType*, inst->type_argc);
4308 for (i = 0; i < inst->type_argc; ++i) {
4309 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)
4310 type_argv [i] = &mono_defaults.object_class->byval_arg;
4312 type_argv [i] = inst->type_argv [i];
4315 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4319 inst = context->method_inst;
4321 type_argv = g_new0 (MonoType*, inst->type_argc);
4322 for (i = 0; i < inst->type_argc; ++i) {
4323 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)
4324 type_argv [i] = &mono_defaults.object_class->byval_arg;
4326 type_argv [i] = inst->type_argv [i];
4329 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4333 if (method->is_generic || method->klass->generic_container)
4334 declaring_method = method;
4336 declaring_method = mono_method_get_declaring_generic_method (method);
4338 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4342 * If the method is fully sharable, it was already added in place of its
4343 * generic definition.
4345 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4349 * FIXME: Partially shared methods are not shared here, so we end up with
4350 * many identical methods.
4352 add_extra_method (acfg, method);
4355 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4359 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4361 klass = mono_class_get_checked (acfg->image, token, &error);
4362 if (!klass || klass->rank) {
4363 mono_error_cleanup (&error);
4367 add_generic_class (acfg, klass, FALSE, "typespec");
4370 /* Add types of args/locals */
4371 for (i = 0; i < acfg->methods->len; ++i) {
4372 method = g_ptr_array_index (acfg->methods, i);
4373 add_types_from_method_header (acfg, method);
4376 if (acfg->image == mono_defaults.corlib) {
4378 MonoType *insts [256];
4381 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4382 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4383 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4384 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4385 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4386 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4387 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4388 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4389 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4390 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4391 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4392 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4394 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4395 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4397 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4398 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4400 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4402 /* Add instances of the array generic interfaces for primitive types */
4403 /* This will add instances of the InternalArray_ helper methods in Array too */
4404 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4406 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4407 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4409 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4410 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4412 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4415 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4416 * used for all instances of GetGenericValueImpl by the AOT runtime.
4419 MonoGenericContext ctx;
4420 MonoType *args [16];
4421 MonoMethod *get_method;
4422 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4424 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4427 memset (&ctx, 0, sizeof (ctx));
4428 args [0] = &mono_defaults.object_class->byval_arg;
4429 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4430 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4434 /* Same for CompareExchange<T>/Exchange<T> */
4436 MonoGenericContext ctx;
4437 MonoType *args [16];
4439 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4440 gpointer iter = NULL;
4442 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4443 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && 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 (m, &ctx), TRUE, TRUE));
4452 /* Same for Volatile.Read/Write<T> */
4454 MonoGenericContext ctx;
4455 MonoType *args [16];
4457 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4458 gpointer iter = NULL;
4460 if (volatile_klass) {
4461 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4462 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4463 memset (&ctx, 0, sizeof (ctx));
4464 args [0] = &mono_defaults.object_class->byval_arg;
4465 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4466 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4475 * is_direct_callable:
4477 * Return whenever the method identified by JI is directly callable without
4478 * going through the PLT.
4481 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4483 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4484 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4486 gboolean direct_callable = TRUE;
4488 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4489 direct_callable = FALSE;
4490 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4491 // FIXME: Maybe call the wrapper directly ?
4492 direct_callable = FALSE;
4494 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4495 /* Disable this so all calls go through load_method (), see the
4496 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4497 * mono_debugger_agent_init ().
4499 direct_callable = FALSE;
4502 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4503 /* sgen does some initialization when the allocator method is created */
4504 direct_callable = FALSE;
4506 if (direct_callable)
4509 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4510 if (acfg->aot_opts.direct_pinvoke)
4512 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4513 if (acfg->aot_opts.direct_icalls)
4521 #ifdef MONO_ARCH_AOT_SUPPORTED
4523 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4525 MonoImage *image = method->klass->image;
4526 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4527 MonoTableInfo *tables = image->tables;
4528 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4529 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4530 guint32 im_cols [MONO_IMPLMAP_SIZE];
4533 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4537 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4540 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4542 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4545 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4547 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4554 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4556 if (a->native_offset == b->native_offset)
4557 return a->il_offset - b->il_offset;
4559 return a->native_offset - b->native_offset;
4563 * compute_line_numbers:
4565 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4568 static MonoDebugSourceLocation**
4569 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4571 MonoDebugMethodInfo *minfo;
4572 MonoDebugLineNumberEntry *ln_array;
4573 MonoDebugSourceLocation *loc;
4574 int i, prev_line, prev_il_offset;
4575 int *native_to_il_offset = NULL;
4576 MonoDebugSourceLocation **res;
4579 minfo = mono_debug_lookup_method (method);
4582 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4583 if (debug_info->code_size != code_size)
4586 g_assert (code_size);
4588 /* Compute the native->IL offset mapping */
4590 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4591 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4593 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4595 native_to_il_offset = g_new0 (int, code_size + 1);
4597 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4599 MonoDebugLineNumberEntry *lne = &ln_array [i];
4602 for (j = 0; j < lne->native_offset; ++j)
4603 native_to_il_offset [j] = -1;
4606 if (i < debug_info->num_line_numbers - 1) {
4607 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4609 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4610 native_to_il_offset [j] = lne->il_offset;
4612 for (j = lne->native_offset; j < code_size; ++j)
4613 native_to_il_offset [j] = lne->il_offset;
4618 /* Compute the native->line number mapping */
4619 res = g_new0 (MonoDebugSourceLocation*, code_size);
4620 prev_il_offset = -1;
4623 for (i = 0; i < code_size; ++i) {
4624 int il_offset = native_to_il_offset [i];
4626 if (il_offset == -1 || il_offset == prev_il_offset)
4628 prev_il_offset = il_offset;
4629 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4630 if (!(loc && loc->source_file))
4632 if (loc->row == prev_line) {
4633 mono_debug_symfile_free_location (loc);
4636 prev_line = loc->row;
4637 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4639 /* This will cover the prolog too */
4649 get_file_index (MonoAotCompile *acfg, const char *source_file)
4653 // FIXME: Free these
4654 if (!acfg->dwarf_ln_filenames)
4655 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4656 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4658 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4659 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4660 emit_unset_mode (acfg);
4661 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4673 * emit_and_reloc_code:
4675 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4676 * is true, calls are made through the GOT too. This is used for emitting trampolines
4677 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4678 * since trampolines are needed to make PTL work.
4681 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4683 int i, pindex, start_index, method_index;
4685 MonoJumpInfo *patch_info;
4686 MonoMethodHeader *header;
4687 MonoDebugSourceLocation **locs = NULL;
4689 #ifdef MONO_ARCH_AOT_SUPPORTED
4690 gboolean direct_call, external_call;
4692 const char *direct_call_target = 0;
4693 const char *direct_pinvoke;
4697 header = mono_method_get_header (method);
4699 method_index = get_method_index (acfg, method);
4702 if (acfg->gas_line_numbers && method && debug_info) {
4703 locs = compute_line_numbers (method, code_len, debug_info);
4705 int findex = get_file_index (acfg, "<unknown>");
4706 emit_unset_mode (acfg);
4707 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4711 /* Collect and sort relocations */
4712 patches = g_ptr_array_new ();
4713 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4714 g_ptr_array_add (patches, patch_info);
4715 g_ptr_array_sort (patches, compare_patches);
4718 for (i = 0; i < code_len; i += INST_LEN) {
4720 for (pindex = start_index; pindex < patches->len; ++pindex) {
4721 patch_info = g_ptr_array_index (patches, pindex);
4722 if (patch_info->ip.i >= i)
4726 if (locs && locs [i]) {
4727 MonoDebugSourceLocation *loc = locs [i];
4730 findex = get_file_index (acfg, loc->source_file);
4731 emit_unset_mode (acfg);
4732 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4733 mono_debug_symfile_free_location (loc);
4737 #ifdef MONO_ARCH_AOT_SUPPORTED
4738 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4739 start_index = pindex;
4741 switch (patch_info->type) {
4742 case MONO_PATCH_INFO_NONE:
4744 case MONO_PATCH_INFO_GOT_OFFSET: {
4747 arch_emit_got_offset (acfg, code + i, &code_size);
4748 i += code_size - INST_LEN;
4750 patch_info->type = MONO_PATCH_INFO_NONE;
4753 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4754 int code_size, index;
4755 char *selector = (void*)patch_info->data.target;
4757 if (!acfg->objc_selector_to_index)
4758 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4759 if (!acfg->objc_selectors)
4760 acfg->objc_selectors = g_ptr_array_new ();
4761 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4765 index = acfg->objc_selector_index;
4766 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4767 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4768 acfg->objc_selector_index ++;
4771 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4772 i += code_size - INST_LEN;
4774 patch_info->type = MONO_PATCH_INFO_NONE;
4779 * If this patch is a call, try emitting a direct call instead of
4780 * through a PLT entry. This is possible if the called method is in
4781 * the same assembly and requires no initialization.
4783 direct_call = FALSE;
4784 external_call = FALSE;
4785 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4786 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4787 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4788 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4790 direct_call_target = callee_cfg->asm_symbol;
4791 patch_info->type = MONO_PATCH_INFO_NONE;
4792 acfg->stats.direct_calls ++;
4795 acfg->stats.all_calls ++;
4796 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4797 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4798 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4799 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4801 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4802 if (direct_pinvoke) {
4804 g_assert (strlen (direct_pinvoke) < 1000);
4805 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4808 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4809 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4810 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4811 /* Call to a C function implementing a jit icall */
4813 external_call = TRUE;
4814 g_assert (strlen (sym) < 1000);
4815 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4817 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4818 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4819 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4820 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4821 /* Call to a jit icall without a wrapper */
4823 external_call = TRUE;
4824 g_assert (strlen (sym) < 1000);
4825 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4830 patch_info->type = MONO_PATCH_INFO_NONE;
4831 acfg->stats.direct_calls ++;
4834 if (!got_only && !direct_call) {
4835 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4837 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4839 direct_call_target = plt_entry->symbol;
4841 /* Nullify the patch */
4842 patch_info->type = MONO_PATCH_INFO_NONE;
4843 plt_entry->jit_used = TRUE;
4850 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4851 i += call_size - INST_LEN;
4855 got_slot = get_got_offset (acfg, FALSE, patch_info);
4857 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4858 i += code_size - INST_LEN;
4864 #endif /* MONO_ARCH_AOT_SUPPORTED */
4867 /* Find next patch */
4869 for (pindex = start_index; pindex < patches->len; ++pindex) {
4870 patch_info = g_ptr_array_index (patches, pindex);
4871 if (patch_info->ip.i >= i)
4875 /* Try to emit multiple bytes at once */
4876 if (pindex < patches->len && patch_info->ip.i > i) {
4879 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4880 if (locs && locs [limit])
4884 emit_code_bytes (acfg, code + i, limit - i);
4885 i = limit - INST_LEN;
4887 emit_code_bytes (acfg, code + i, INST_LEN);
4898 * Return a modified version of S which only includes characters permissible in symbols.
4901 sanitize_symbol (MonoAotCompile *acfg, char *s)
4903 gboolean process = FALSE;
4912 for (i = 0; i < len; ++i)
4913 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4918 gs = g_string_sized_new (len);
4919 for (i = 0; i < len; ++i) {
4921 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4922 g_string_append_c (gs, c);
4923 } else if (c > 0x7f) {
4924 /* multi-byte utf8 */
4925 g_string_append_printf (gs, "_0x%x", c);
4928 while (c >> 6 == 0x2) {
4929 g_string_append_printf (gs, "%x", c);
4933 g_string_append_printf (gs, "_");
4936 g_string_append_c (gs, '_');
4940 res = mono_mempool_strdup (acfg->mempool, gs->str);
4941 g_string_free (gs, TRUE);
4946 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4948 char *name1, *name2, *cached;
4949 int i, j, len, count;
4950 MonoMethod *cached_method;
4952 name1 = mono_method_full_name (method, TRUE);
4955 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4956 if ((!prefix || !*prefix) && name1 [0] == 'L')
4960 len = strlen (name1);
4961 name2 = malloc (strlen (prefix) + len + 16);
4962 memcpy (name2, prefix, strlen (prefix));
4963 j = strlen (prefix);
4964 for (i = 0; i < len; ++i) {
4965 if (isalnum (name1 [i])) {
4966 name2 [j ++] = name1 [i];
4967 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4969 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4972 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4982 cached_method = g_hash_table_lookup (cache, name2);
4983 if (!(cached_method && cached_method != method))
4985 sprintf (name2 + j, "_%d", count);
4989 cached = g_strdup (name2);
4990 g_hash_table_insert (cache, cached, method);
4996 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5001 char *debug_sym = NULL;
5002 char *symbol = NULL;
5003 int func_alignment = AOT_FUNC_ALIGNMENT;
5004 MonoMethodHeader *header;
5007 method = cfg->orig_method;
5008 code = cfg->native_code;
5009 header = cfg->header;
5011 method_index = get_method_index (acfg, method);
5012 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5014 /* Make the labels local */
5015 emit_section_change (acfg, ".text", 0);
5016 emit_alignment_code (acfg, func_alignment);
5018 if (acfg->global_symbols && acfg->need_no_dead_strip)
5019 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5021 emit_label (acfg, cfg->asm_symbol);
5023 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm_separate) {
5025 * Write a C style symbol for every method, this has two uses:
5026 * - it works on platforms where the dwarf debugging info is not
5028 * - it allows the setting of breakpoints of aot-ed methods.
5030 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5032 if (acfg->need_no_dead_strip)
5033 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5034 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5035 emit_label (acfg, debug_sym);
5038 export_name = g_hash_table_lookup (acfg->export_names, method);
5040 /* Emit a global symbol for the method */
5041 emit_global_inner (acfg, export_name, TRUE);
5042 emit_label (acfg, export_name);
5045 if (cfg->verbose_level > 0)
5046 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5048 acfg->stats.code_size += cfg->code_len;
5050 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5052 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 ()));
5056 if (acfg->aot_opts.write_symbols) {
5057 emit_symbol_size (acfg, debug_sym, ".");
5061 emit_label (acfg, symbol);
5068 * Encode PATCH_INFO into its disk representation.
5071 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5075 switch (patch_info->type) {
5076 case MONO_PATCH_INFO_NONE:
5078 case MONO_PATCH_INFO_IMAGE:
5079 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5081 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5082 case MONO_PATCH_INFO_JIT_TLS_ID:
5083 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5085 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5086 encode_value (patch_info->data.index, p, &p);
5088 case MONO_PATCH_INFO_METHOD_REL:
5089 encode_value ((gint)patch_info->data.offset, p, &p);
5091 case MONO_PATCH_INFO_SWITCH: {
5092 gpointer *table = (gpointer *)patch_info->data.table->table;
5095 encode_value (patch_info->data.table->table_size, p, &p);
5096 for (k = 0; k < patch_info->data.table->table_size; k++)
5097 encode_value ((int)(gssize)table [k], p, &p);
5100 case MONO_PATCH_INFO_METHODCONST:
5101 case MONO_PATCH_INFO_METHOD:
5102 case MONO_PATCH_INFO_METHOD_JUMP:
5103 case MONO_PATCH_INFO_ICALL_ADDR:
5104 case MONO_PATCH_INFO_METHOD_RGCTX:
5105 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5106 encode_method_ref (acfg, patch_info->data.method, p, &p);
5108 case MONO_PATCH_INFO_INTERNAL_METHOD:
5109 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5110 guint32 len = strlen (patch_info->data.name);
5112 encode_value (len, p, &p);
5114 memcpy (p, patch_info->data.name, len);
5119 case MONO_PATCH_INFO_LDSTR: {
5120 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5121 guint32 token = patch_info->data.token->token;
5122 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5123 encode_value (image_index, p, &p);
5124 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5127 case MONO_PATCH_INFO_RVA:
5128 case MONO_PATCH_INFO_DECLSEC:
5129 case MONO_PATCH_INFO_LDTOKEN:
5130 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5131 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5132 encode_value (patch_info->data.token->token, p, &p);
5133 encode_value (patch_info->data.token->has_context, p, &p);
5134 if (patch_info->data.token->has_context)
5135 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5137 case MONO_PATCH_INFO_EXC_NAME: {
5138 MonoClass *ex_class;
5141 mono_class_from_name (mono_defaults.exception_class->image,
5142 "System", patch_info->data.target);
5143 g_assert (ex_class);
5144 encode_klass_ref (acfg, ex_class, p, &p);
5147 case MONO_PATCH_INFO_R4:
5148 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5150 case MONO_PATCH_INFO_R8:
5151 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5152 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5154 case MONO_PATCH_INFO_VTABLE:
5155 case MONO_PATCH_INFO_CLASS:
5156 case MONO_PATCH_INFO_IID:
5157 case MONO_PATCH_INFO_ADJUSTED_IID:
5158 case MONO_PATCH_INFO_CLASS_INIT:
5159 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5161 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5162 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5163 if (patch_info->data.del_tramp->method) {
5164 encode_value (1, p, &p);
5165 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5167 encode_value (0, p, &p);
5169 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5171 case MONO_PATCH_INFO_FIELD:
5172 case MONO_PATCH_INFO_SFLDA:
5173 encode_field_info (acfg, patch_info->data.field, p, &p);
5175 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5177 case MONO_PATCH_INFO_RGCTX_FETCH: {
5178 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5183 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5184 * reference the same method, so encode the method only once.
5186 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5188 buf2 = g_malloc (1024);
5191 encode_method_ref (acfg, entry->method, p2, &p2);
5192 g_assert (p2 - buf2 < 1024);
5194 offset = add_to_blob (acfg, buf2, p2 - buf2);
5197 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5202 encode_value (offset, p, &p);
5203 g_assert ((int)entry->info_type < 256);
5204 g_assert (entry->data->type < 256);
5205 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5206 encode_patch (acfg, entry->data, p, &p);
5209 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5210 case MONO_PATCH_INFO_MONITOR_ENTER:
5211 case MONO_PATCH_INFO_MONITOR_EXIT:
5212 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5214 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5215 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5216 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5218 case MONO_PATCH_INFO_SIGNATURE:
5219 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5221 case MONO_PATCH_INFO_TLS_OFFSET:
5222 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5224 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5225 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5226 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5228 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5229 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5232 encode_method_ref (acfg, info->method, p, &p);
5233 encode_value (info->num_entries, p, &p);
5234 for (i = 0; i < info->num_entries; ++i) {
5235 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5237 encode_value (template->info_type, p, &p);
5238 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5239 case MONO_PATCH_INFO_CLASS:
5240 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5242 case MONO_PATCH_INFO_FIELD:
5243 encode_field_info (acfg, template->data, p, &p);
5246 g_assert_not_reached ();
5252 case MONO_PATCH_INFO_LDSTR_LIT: {
5253 const char *s = patch_info->data.target;
5255 encode_value (strlen (s), p, &p);
5256 memcpy (p, s, strlen (s) + 1);
5260 g_warning ("unable to handle jump info %d", patch_info->type);
5261 g_assert_not_reached ();
5268 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5271 guint32 pindex, offset;
5272 MonoJumpInfo *patch_info;
5274 encode_value (n_patches, p, &p);
5276 for (pindex = 0; pindex < patches->len; ++pindex) {
5277 patch_info = g_ptr_array_index (patches, pindex);
5279 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5283 offset = get_got_offset (acfg, llvm, patch_info);
5284 encode_value (offset, p, &p);
5291 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5295 int pindex, buf_size, n_patches;
5297 MonoJumpInfo *patch_info;
5298 MonoMethodHeader *header;
5299 guint32 method_index;
5301 guint32 first_got_offset;
5303 method = cfg->orig_method;
5304 header = mono_method_get_header (method);
5306 method_index = get_method_index (acfg, method);
5308 /* Sort relocations */
5309 patches = g_ptr_array_new ();
5310 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5311 g_ptr_array_add (patches, patch_info);
5312 g_ptr_array_sort (patches, compare_patches);
5314 first_got_offset = acfg->cfgs [method_index]->got_offset;
5316 /**********************/
5317 /* Encode method info */
5318 /**********************/
5320 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5321 p = buf = g_malloc (buf_size);
5323 if (mono_class_get_cctor (method->klass))
5324 encode_klass_ref (acfg, method->klass, p, &p);
5326 /* Not needed when loading the method */
5327 encode_value (0, p, &p);
5330 if (cfg->opt & MONO_OPT_SHARED) {
5331 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5332 for (l = cfg->ldstr_list; l; l = l->next) {
5333 encode_value ((long)l->data, p, &p);
5337 /* Used only in shared mode */
5338 g_assert (!cfg->ldstr_list);
5341 for (pindex = 0; pindex < patches->len; ++pindex) {
5342 patch_info = g_ptr_array_index (patches, pindex);
5344 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5345 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5346 patch_info->type = MONO_PATCH_INFO_NONE;
5351 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5352 /* Stored in a GOT slot initialized at module load time */
5353 patch_info->type = MONO_PATCH_INFO_NONE;
5357 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5358 /* Stored in a GOT slot initialized at module load time */
5359 patch_info->type = MONO_PATCH_INFO_NONE;
5363 if (is_plt_patch (patch_info)) {
5364 /* Calls are made through the PLT */
5365 patch_info->type = MONO_PATCH_INFO_NONE;
5373 g_assert (cfg->has_got_slots);
5375 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5377 acfg->stats.info_size += p - buf;
5379 g_assert (p - buf < buf_size);
5381 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5386 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5388 guint32 cache_index;
5391 /* Reuse the unwind module to canonize and store unwind info entries */
5392 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5394 /* Use +/- 1 to distinguish 0s from missing entries */
5395 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5403 * It would be easier to use assembler symbols, but the caller needs an
5406 offset = acfg->unwind_info_offset;
5407 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5408 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5411 encode_value (encoded_len, p, &p);
5413 acfg->unwind_info_offset += encoded_len + (p - buf);
5419 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5422 int i, k, buf_size, method_index;
5423 guint32 debug_info_size, seq_points_size;
5425 MonoMethodHeader *header;
5426 guint8 *p, *buf, *debug_info;
5427 MonoJitInfo *jinfo = cfg->jit_info;
5429 gboolean use_unwind_ops = FALSE;
5430 MonoSeqPointInfo *seq_points;
5432 method = cfg->orig_method;
5433 code = cfg->native_code;
5434 header = cfg->header;
5436 method_index = get_method_index (acfg, method);
5438 if (!acfg->aot_opts.nodebug) {
5439 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5442 debug_info_size = 0;
5445 seq_points = cfg->seq_point_info;
5447 seq_points_size = (cfg->gen_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5449 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5450 p = buf = g_malloc (buf_size);
5452 use_unwind_ops = cfg->unwind_ops != NULL;
5454 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);
5456 encode_value (flags, p, &p);
5458 if (use_unwind_ops) {
5459 guint32 encoded_len;
5461 guint32 unwind_desc;
5463 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5465 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5466 encode_value (unwind_desc, p, &p);
5468 encode_value (jinfo->unwind_info, p, &p);
5471 /*Encode the number of holes before the number of clauses to make decoding easier*/
5472 if (jinfo->has_try_block_holes) {
5473 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5474 encode_value (table->num_holes, p, &p);
5477 if (jinfo->has_arch_eh_info) {
5479 * In AOT mode, the code length is calculated from the address of the previous method,
5480 * which could include alignment padding, so calculating the start of the epilog as
5481 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5483 encode_value (jinfo->code_size, p, &p);
5486 /* Exception table */
5487 if (cfg->compile_llvm) {
5489 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5490 * since the information is only available to llc. Instead, we let llc save the data
5491 * into the LSDA, and read it from there at runtime.
5493 /* The assembly might be CIL stripped so emit the data ourselves */
5494 if (header->num_clauses)
5495 encode_value (header->num_clauses, p, &p);
5497 for (k = 0; k < header->num_clauses; ++k) {
5498 MonoExceptionClause *clause;
5500 clause = &header->clauses [k];
5502 encode_value (clause->flags, p, &p);
5503 if (clause->data.catch_class) {
5504 encode_value (1, p, &p);
5505 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5507 encode_value (0, p, &p);
5510 /* Emit a list of nesting clauses */
5511 for (i = 0; i < header->num_clauses; ++i) {
5513 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5515 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5517 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5518 encode_value (i, p, &p);
5520 encode_value (-1, p, &p);
5523 if (jinfo->num_clauses)
5524 encode_value (jinfo->num_clauses, p, &p);
5526 for (k = 0; k < jinfo->num_clauses; ++k) {
5527 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5529 encode_value (ei->flags, p, &p);
5530 encode_value (ei->exvar_offset, p, &p);
5532 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5533 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5535 if (ei->data.catch_class) {
5539 buf2 = g_malloc (4096);
5541 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5543 g_assert (len < 4096);
5544 encode_value (len, p, &p);
5545 memcpy (p, buf2, len);
5549 encode_value (0, p, &p);
5553 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5554 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5555 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5559 if (jinfo->has_try_block_holes) {
5560 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5561 for (i = 0; i < table->num_holes; ++i) {
5562 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5563 encode_value (hole->clause, p, &p);
5564 encode_value (hole->length, p, &p);
5565 encode_value (hole->offset, p, &p);
5569 if (jinfo->has_arch_eh_info) {
5570 MonoArchEHJitInfo *eh_info;
5572 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5573 encode_value (eh_info->stack_size, p, &p);
5574 encode_value (eh_info->epilog_size, p, &p);
5577 if (jinfo->has_generic_jit_info) {
5578 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5579 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5585 encode_value (gi->nlocs, p, &p);
5587 for (i = 0; i < gi->nlocs; ++i) {
5588 MonoDwarfLocListEntry *entry = &gi->locations [i];
5590 encode_value (entry->is_reg ? 1 : 0, p, &p);
5591 encode_value (entry->reg, p, &p);
5593 encode_value (entry->offset, p, &p);
5595 g_assert (entry->from == 0);
5597 encode_value (entry->from, p, &p);
5598 encode_value (entry->to, p, &p);
5601 if (!cfg->compile_llvm) {
5602 encode_value (gi->has_this ? 1 : 0, p, &p);
5603 encode_value (gi->this_reg, p, &p);
5604 encode_value (gi->this_offset, p, &p);
5609 * Need to encode jinfo->method too, since it is not equal to 'method'
5610 * when using generic sharing.
5612 buf2 = g_malloc (4096);
5614 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5616 g_assert (len < 4096);
5617 encode_value (len, p, &p);
5618 memcpy (p, buf2, len);
5622 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5623 MonoMethodInflated *inflated;
5624 MonoGenericContext *context;
5625 MonoGenericInst *inst;
5627 g_assert (jinfo->d.method->is_inflated);
5628 inflated = (MonoMethodInflated*)jinfo->d.method;
5629 context = &inflated->context;
5631 encode_value (1, p, &p);
5632 if (context->class_inst) {
5633 inst = context->class_inst;
5635 encode_value (inst->type_argc, p, &p);
5636 for (i = 0; i < inst->type_argc; ++i)
5637 encode_value (gsctx->var_is_vt [i], p, &p);
5639 encode_value (0, p, &p);
5641 if (context->method_inst) {
5642 inst = context->method_inst;
5644 encode_value (inst->type_argc, p, &p);
5645 for (i = 0; i < inst->type_argc; ++i)
5646 encode_value (gsctx->mvar_is_vt [i], p, &p);
5648 encode_value (0, p, &p);
5651 encode_value (0, p, &p);
5656 p += seq_point_info_write (seq_points, p);
5658 g_assert (debug_info_size < buf_size);
5660 encode_value (debug_info_size, p, &p);
5661 if (debug_info_size) {
5662 memcpy (p, debug_info, debug_info_size);
5663 p += debug_info_size;
5664 g_free (debug_info);
5669 encode_value (cfg->gc_map_size, p, &p);
5670 /* The GC map requires 4 bytes of alignment */
5671 while ((gsize)p % 4)
5673 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5674 p += cfg->gc_map_size;
5677 acfg->stats.ex_info_size += p - buf;
5679 g_assert (p - buf < buf_size);
5682 /* The GC Map requires 4 byte alignment */
5683 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5688 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5691 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5693 int i, buf_size, res;
5694 gboolean no_special_static, cant_encode;
5695 gpointer iter = NULL;
5698 mono_error_cleanup (&error);
5702 p = buf = g_malloc (buf_size);
5704 /* Mark as unusable */
5705 encode_value (-1, p, &p);
5707 res = add_to_blob (acfg, buf, p - buf);
5713 buf_size = 10240 + (klass->vtable_size * 16);
5714 p = buf = g_malloc (buf_size);
5718 mono_class_init (klass);
5720 mono_class_get_nested_types (klass, &iter);
5721 g_assert (klass->nested_classes_inited);
5723 mono_class_setup_vtable (klass);
5726 * Emit all the information which is required for creating vtables so
5727 * the runtime does not need to create the MonoMethod structures which
5728 * take up a lot of space.
5731 no_special_static = !mono_class_has_special_static_fields (klass);
5733 /* Check whenever we have enough info to encode the vtable */
5734 cant_encode = FALSE;
5735 for (i = 0; i < klass->vtable_size; ++i) {
5736 MonoMethod *cm = klass->vtable [i];
5738 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5742 mono_class_has_finalizer (klass);
5744 if (klass->generic_container || cant_encode) {
5745 encode_value (-1, p, &p);
5747 encode_value (klass->vtable_size, p, &p);
5748 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);
5749 if (klass->has_cctor)
5750 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5751 if (klass->has_finalize)
5752 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5754 encode_value (klass->instance_size, p, &p);
5755 encode_value (mono_class_data_size (klass), p, &p);
5756 encode_value (klass->packing_size, p, &p);
5757 encode_value (klass->min_align, p, &p);
5759 for (i = 0; i < klass->vtable_size; ++i) {
5760 MonoMethod *cm = klass->vtable [i];
5763 encode_method_ref (acfg, cm, p, &p);
5765 encode_value (0, p, &p);
5769 acfg->stats.class_info_size += p - buf;
5771 g_assert (p - buf < buf_size);
5772 res = add_to_blob (acfg, buf, p - buf);
5779 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5781 char *debug_sym = NULL;
5785 if (acfg->llvm_separate && llvm_acfg->aot_opts.static_link) {
5786 /* Need to add a prefix to create unique symbols */
5787 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5789 prefix = g_strdup ("plt_");
5793 case MONO_PATCH_INFO_METHOD:
5794 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5796 case MONO_PATCH_INFO_INTERNAL_METHOD:
5797 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5799 case MONO_PATCH_INFO_CLASS_INIT:
5800 s = mono_type_get_name (&ji->data.klass->byval_arg);
5801 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5804 case MONO_PATCH_INFO_RGCTX_FETCH:
5805 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5807 case MONO_PATCH_INFO_ICALL_ADDR: {
5808 char *s = get_debug_sym (ji->data.method, "", cache);
5810 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5814 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5815 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5817 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5818 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5826 return sanitize_symbol (acfg, debug_sym);
5830 * Calls made from AOTed code are routed through a table of jumps similar to the
5831 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5832 * control to the AOT runtime through a trampoline.
5835 emit_plt (MonoAotCompile *acfg)
5841 sprintf (symbol, "plt");
5843 emit_section_change (acfg, ".text", 0);
5844 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5845 emit_label (acfg, symbol);
5846 emit_label (acfg, acfg->plt_symbol);
5848 for (i = 0; i < acfg->plt_offset; ++i) {
5849 char *debug_sym = NULL;
5850 MonoPltEntry *plt_entry = NULL;
5855 * The first plt entry is unused.
5859 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5862 debug_sym = plt_entry->debug_sym;
5864 if (acfg->thumb_mixed && !plt_entry->jit_used)
5865 /* Emit only a thumb version */
5868 /* Skip plt entries not actually called */
5869 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5872 if (acfg->llvm && !acfg->thumb_mixed) {
5873 emit_label (acfg, plt_entry->llvm_symbol);
5874 if (acfg->llvm_separate) {
5875 emit_global (acfg, plt_entry->llvm_symbol, TRUE);
5876 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5881 if (acfg->need_no_dead_strip) {
5882 emit_unset_mode (acfg);
5883 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5885 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5886 emit_label (acfg, debug_sym);
5889 emit_label (acfg, plt_entry->symbol);
5891 arch_emit_plt_entry (acfg, i);
5894 emit_symbol_size (acfg, debug_sym, ".");
5897 if (acfg->thumb_mixed) {
5898 /* Make sure the ARM symbols don't alias the thumb ones */
5899 emit_zero_bytes (acfg, 16);
5902 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5905 for (i = 0; i < acfg->plt_offset; ++i) {
5906 char *debug_sym = NULL;
5907 MonoPltEntry *plt_entry = NULL;
5913 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5916 /* Skip plt entries not actually called by LLVM code */
5917 if (!plt_entry->llvm_used)
5920 if (acfg->aot_opts.write_symbols) {
5921 if (plt_entry->debug_sym)
5922 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5926 #if defined(TARGET_MACH)
5927 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5928 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5930 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5931 emit_label (acfg, debug_sym);
5933 fprintf (acfg->fp, "\n.thumb_func\n");
5935 emit_label (acfg, plt_entry->llvm_symbol);
5937 arch_emit_llvm_plt_entry (acfg, i);
5940 emit_symbol_size (acfg, debug_sym, ".");
5946 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5948 sprintf (symbol, "plt_end");
5949 emit_label (acfg, symbol);
5953 * emit_trampoline_full:
5955 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5956 * create_jit_info_for_trampoline ().
5958 static G_GNUC_UNUSED void
5959 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5961 char start_symbol [256];
5962 char end_symbol [256];
5964 guint32 buf_size, info_offset;
5965 MonoJumpInfo *patch_info;
5978 code_size = info->code_size;
5980 unwind_ops = info->unwind_ops;
5982 #ifdef __native_client_codegen__
5983 mono_nacl_fix_patches (code, ji);
5988 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5990 emit_section_change (acfg, ".text", 0);
5991 emit_global (acfg, start_symbol, TRUE);
5992 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
5993 emit_label (acfg, start_symbol);
5995 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5996 emit_label (acfg, symbol);
5999 * The code should access everything through the GOT, so we pass
6002 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6004 emit_symbol_size (acfg, start_symbol, ".");
6007 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6008 emit_label (acfg, end_symbol);
6013 /* Sort relocations */
6014 patches = g_ptr_array_new ();
6015 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6016 if (patch_info->type != MONO_PATCH_INFO_NONE)
6017 g_ptr_array_add (patches, patch_info);
6018 g_ptr_array_sort (patches, compare_patches);
6020 buf_size = patches->len * 128 + 128;
6021 buf = g_malloc (buf_size);
6024 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6025 g_assert (p - buf < buf_size);
6027 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6029 info_offset = add_to_blob (acfg, buf, p - buf);
6031 emit_section_change (acfg, RODATA_SECT, 0);
6032 emit_global (acfg, symbol, FALSE);
6033 emit_label (acfg, symbol);
6035 emit_int32 (acfg, info_offset);
6039 guint32 encoded_len;
6043 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6045 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6046 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6049 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6050 emit_int32 (acfg, uw_offset);
6053 /* Emit debug info */
6057 sprintf (symbol, "%s", name);
6058 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6061 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6065 static G_GNUC_UNUSED void
6066 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6068 emit_trampoline_full (acfg, got_offset, info, FALSE);
6072 emit_trampolines (MonoAotCompile *acfg)
6075 char end_symbol [256];
6076 int i, tramp_got_offset;
6077 MonoAotTrampoline ntype;
6078 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6082 if (!acfg->aot_opts.full_aot)
6085 g_assert (acfg->image->assembly);
6087 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6088 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6089 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6090 MonoTrampInfo *info;
6093 * Emit the generic trampolines.
6095 * We could save some code by treating the generic trampolines as a wrapper
6096 * method, but that approach has its own complexities, so we choose the simpler
6099 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6100 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6101 #ifdef DISABLE_REMOTING
6102 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6105 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6106 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6109 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6110 emit_trampoline (acfg, acfg->got_offset, info);
6113 mono_arch_get_nullified_class_init_trampoline (&info);
6114 emit_trampoline (acfg, acfg->got_offset, info);
6115 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6116 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
6117 emit_trampoline (acfg, acfg->got_offset, info);
6118 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6119 emit_trampoline (acfg, acfg->got_offset, info);
6122 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6123 emit_trampoline (acfg, acfg->got_offset, info);
6125 /* Emit the exception related code pieces */
6126 mono_arch_get_restore_context (&info, TRUE);
6127 emit_trampoline (acfg, acfg->got_offset, info);
6128 mono_arch_get_call_filter (&info, TRUE);
6129 emit_trampoline (acfg, acfg->got_offset, info);
6130 mono_arch_get_throw_exception (&info, TRUE);
6131 emit_trampoline (acfg, acfg->got_offset, info);
6132 mono_arch_get_rethrow_exception (&info, TRUE);
6133 emit_trampoline (acfg, acfg->got_offset, info);
6134 mono_arch_get_throw_corlib_exception (&info, TRUE);
6135 emit_trampoline (acfg, acfg->got_offset, info);
6137 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6138 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6140 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6142 /* Create a separate out trampoline for more information in stack traces */
6143 info->name = g_strdup ("gsharedvt_out_trampoline");
6144 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6148 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6150 GSList *l = mono_arch_get_trampolines (TRUE);
6153 MonoTrampInfo *info = l->data;
6155 emit_trampoline (acfg, acfg->got_offset, info);
6161 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6164 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6165 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6166 emit_trampoline (acfg, acfg->got_offset, info);
6168 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6169 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6170 emit_trampoline (acfg, acfg->got_offset, info);
6173 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6174 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6175 emit_trampoline (acfg, acfg->got_offset, info);
6181 /* delegate_invoke_impl trampolines */
6182 l = mono_arch_get_delegate_invoke_impls ();
6184 MonoTrampInfo *info = l->data;
6186 emit_trampoline (acfg, acfg->got_offset, info);
6191 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6193 /* Emit trampolines which are numerous */
6196 * These include the following:
6197 * - specific trampolines
6198 * - static rgctx invoke trampolines
6200 * These trampolines have the same code, they are parameterized by GOT
6202 * They are defined in this file, in the arch_... routines instead of
6203 * in tramp-<ARCH>.c, since it is easier to do it this way.
6207 * When running in aot-only mode, we can't create specific trampolines at
6208 * runtime, so we create a few, and save them in the AOT file.
6209 * Normal trampolines embed their argument as a literal inside the
6210 * trampoline code, we can't do that here, so instead we embed an offset
6211 * which needs to be added to the trampoline address to get the address of
6212 * the GOT slot which contains the argument value.
6213 * The generated trampolines jump to the generic trampolines using another
6214 * GOT slot, which will be setup by the AOT loader to point to the
6215 * generic trampoline code of the given type.
6219 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6223 emit_section_change (acfg, ".text", 0);
6225 tramp_got_offset = acfg->got_offset;
6227 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6229 case MONO_AOT_TRAMP_SPECIFIC:
6230 sprintf (symbol, "specific_trampolines");
6232 case MONO_AOT_TRAMP_STATIC_RGCTX:
6233 sprintf (symbol, "static_rgctx_trampolines");
6235 case MONO_AOT_TRAMP_IMT_THUNK:
6236 sprintf (symbol, "imt_thunks");
6238 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6239 sprintf (symbol, "gsharedvt_arg_trampolines");
6242 g_assert_not_reached ();
6245 sprintf (end_symbol, "%s_e", symbol);
6247 if (acfg->aot_opts.write_symbols)
6248 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6250 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6251 emit_label (acfg, symbol);
6253 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6255 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6259 case MONO_AOT_TRAMP_SPECIFIC:
6260 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6261 tramp_got_offset += 2;
6263 case MONO_AOT_TRAMP_STATIC_RGCTX:
6264 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6265 tramp_got_offset += 2;
6267 case MONO_AOT_TRAMP_IMT_THUNK:
6268 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6269 tramp_got_offset += 1;
6271 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6272 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6273 tramp_got_offset += 2;
6276 g_assert_not_reached ();
6278 #ifdef __native_client_codegen__
6279 /* align to avoid 32-byte boundary crossings */
6280 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6283 if (!acfg->trampoline_size [ntype]) {
6284 g_assert (tramp_size);
6285 acfg->trampoline_size [ntype] = tramp_size;
6289 emit_label (acfg, end_symbol);
6290 emit_int32 (acfg, 0);
6293 arch_emit_specific_trampoline_pages (acfg);
6295 /* Reserve some entries at the end of the GOT for our use */
6296 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6299 acfg->got_offset += acfg->num_trampoline_got_entries;
6303 str_begins_with (const char *str1, const char *str2)
6305 int len = strlen (str2);
6306 return strncmp (str1, str2, len) == 0;
6310 mono_aot_readonly_field_override (MonoClassField *field)
6313 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6314 char *p = rdv->name;
6316 len = strlen (field->parent->name_space);
6317 if (strncmp (p, field->parent->name_space, len))
6322 len = strlen (field->parent->name);
6323 if (strncmp (p, field->parent->name, len))
6328 if (strcmp (p, field->name))
6330 switch (rdv->type) {
6332 return &rdv->value.i1;
6334 return &rdv->value.i2;
6336 return &rdv->value.i4;
6345 add_readonly_value (MonoAotOptions *opts, const char *val)
6350 /* the format of val is:
6351 * namespace.typename.fieldname=type/value
6352 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6354 fval = strrchr (val, '/');
6356 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6359 tval = strrchr (val, '=');
6361 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6364 rdv = g_new0 (ReadOnlyValue, 1);
6365 rdv->name = g_malloc0 (tval - val + 1);
6366 memcpy (rdv->name, val, tval - val);
6369 if (strncmp (tval, "i1", 2) == 0) {
6370 rdv->value.i1 = atoi (fval);
6371 rdv->type = MONO_TYPE_I1;
6372 } else if (strncmp (tval, "i2", 2) == 0) {
6373 rdv->value.i2 = atoi (fval);
6374 rdv->type = MONO_TYPE_I2;
6375 } else if (strncmp (tval, "i4", 2) == 0) {
6376 rdv->value.i4 = atoi (fval);
6377 rdv->type = MONO_TYPE_I4;
6379 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6382 rdv->next = readonly_values;
6383 readonly_values = rdv;
6387 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6389 gchar **args, **ptr;
6391 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6392 for (ptr = args; ptr && *ptr; ptr ++) {
6393 const char *arg = *ptr;
6395 if (str_begins_with (arg, "outfile=")) {
6396 opts->outfile = g_strdup (arg + strlen ("outfile="));
6397 } else if (str_begins_with (arg, "llvm-outfile=")) {
6398 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6399 } else if (str_begins_with (arg, "save-temps")) {
6400 opts->save_temps = TRUE;
6401 } else if (str_begins_with (arg, "keep-temps")) {
6402 opts->save_temps = TRUE;
6403 } else if (str_begins_with (arg, "write-symbols")) {
6404 opts->write_symbols = TRUE;
6405 } else if (str_begins_with (arg, "no-write-symbols")) {
6406 opts->write_symbols = FALSE;
6407 } else if (str_begins_with (arg, "metadata-only")) {
6408 opts->metadata_only = TRUE;
6409 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6410 opts->bind_to_runtime_version = TRUE;
6411 } else if (str_begins_with (arg, "full")) {
6412 opts->full_aot = TRUE;
6413 } else if (str_begins_with (arg, "threads=")) {
6414 opts->nthreads = atoi (arg + strlen ("threads="));
6415 } else if (str_begins_with (arg, "static")) {
6416 opts->static_link = TRUE;
6417 opts->no_dlsym = TRUE;
6418 } else if (str_begins_with (arg, "asmonly")) {
6419 opts->asm_only = TRUE;
6420 } else if (str_begins_with (arg, "asmwriter")) {
6421 opts->asm_writer = TRUE;
6422 } else if (str_begins_with (arg, "nodebug")) {
6423 opts->nodebug = TRUE;
6424 } else if (str_begins_with (arg, "dwarfdebug")) {
6425 opts->dwarf_debug = TRUE;
6426 } else if (str_begins_with (arg, "nopagetrampolines")) {
6427 opts->use_trampolines_page = FALSE;
6428 } else if (str_begins_with (arg, "ntrampolines=")) {
6429 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6430 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6431 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6432 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6433 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6434 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6435 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6436 } else if (str_begins_with (arg, "autoreg")) {
6437 opts->autoreg = TRUE;
6438 } else if (str_begins_with (arg, "tool-prefix=")) {
6439 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6440 } else if (str_begins_with (arg, "soft-debug")) {
6441 opts->soft_debug = TRUE;
6442 } else if (str_begins_with (arg, "direct-pinvoke")) {
6443 opts->direct_pinvoke = TRUE;
6444 } else if (str_begins_with (arg, "direct-icalls")) {
6445 opts->direct_icalls = TRUE;
6446 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6447 } else if (str_begins_with (arg, "iphone-abi")) {
6448 // older full-aot users did depend on this.
6450 } else if (str_begins_with (arg, "no-direct-calls")) {
6451 opts->no_direct_calls = TRUE;
6452 } else if (str_begins_with (arg, "print-skipped")) {
6453 opts->print_skipped_methods = TRUE;
6454 } else if (str_begins_with (arg, "stats")) {
6456 } else if (str_begins_with (arg, "no-instances")) {
6457 opts->no_instances = TRUE;
6458 } else if (str_begins_with (arg, "log-generics")) {
6459 opts->log_generics = TRUE;
6460 } else if (str_begins_with (arg, "log-instances=")) {
6461 opts->log_instances = TRUE;
6462 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6463 } else if (str_begins_with (arg, "log-instances")) {
6464 opts->log_instances = TRUE;
6465 } else if (str_begins_with (arg, "internal-logfile=")) {
6466 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6467 } else if (str_begins_with (arg, "mtriple=")) {
6468 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6469 } else if (str_begins_with (arg, "llvm-path=")) {
6470 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6471 } else if (!strcmp (arg, "llvm")) {
6473 } else if (str_begins_with (arg, "readonly-value=")) {
6474 add_readonly_value (opts, arg + strlen ("readonly-value="));
6475 } else if (str_begins_with (arg, "info")) {
6476 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6478 } else if (str_begins_with (arg, "gc-maps")) {
6479 mini_gc_enable_gc_maps_for_aot ();
6480 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6481 printf ("Supported options for --aot:\n");
6482 printf (" outfile=\n");
6483 printf (" llvm-outfile=\n");
6484 printf (" save-temps\n");
6485 printf (" keep-temps\n");
6486 printf (" write-symbols\n");
6487 printf (" metadata-only\n");
6488 printf (" bind-to-runtime-version\n");
6490 printf (" threads=\n");
6491 printf (" static\n");
6492 printf (" asmonly\n");
6493 printf (" asmwriter\n");
6494 printf (" nodebug\n");
6495 printf (" dwarfdebug\n");
6496 printf (" ntrampolines=\n");
6497 printf (" nrgctx-trampolines=\n");
6498 printf (" nimt-trampolines=\n");
6499 printf (" ngsharedvt-trampolines=\n");
6500 printf (" autoreg\n");
6501 printf (" tool-prefix=\n");
6502 printf (" readonly-value=\n");
6503 printf (" soft-debug\n");
6504 printf (" gc-maps\n");
6505 printf (" print-skipped\n");
6506 printf (" no-instances\n");
6507 printf (" stats\n");
6509 printf (" help/?\n");
6512 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6517 if (opts->use_trampolines_page) {
6518 opts->ntrampolines = 0;
6519 opts->nrgctx_trampolines = 0;
6520 opts->nimt_trampolines = 0;
6521 opts->ngsharedvt_arg_trampolines = 0;
6527 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6529 MonoMethod *method = (MonoMethod*)key;
6530 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6531 MonoAotCompile *acfg = user_data;
6532 MonoJumpInfoToken *new_ji;
6534 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6535 new_ji->image = ji->image;
6536 new_ji->token = ji->token;
6537 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6541 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6543 if (klass->type_token)
6545 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6548 return can_encode_class (acfg, klass->element_class);
6553 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6555 if (method->wrapper_type) {
6556 switch (method->wrapper_type) {
6557 case MONO_WRAPPER_NONE:
6558 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6559 case MONO_WRAPPER_XDOMAIN_INVOKE:
6560 case MONO_WRAPPER_STFLD:
6561 case MONO_WRAPPER_LDFLD:
6562 case MONO_WRAPPER_LDFLDA:
6563 case MONO_WRAPPER_LDFLD_REMOTE:
6564 case MONO_WRAPPER_STFLD_REMOTE:
6565 case MONO_WRAPPER_STELEMREF:
6566 case MONO_WRAPPER_ISINST:
6567 case MONO_WRAPPER_PROXY_ISINST:
6568 case MONO_WRAPPER_ALLOC:
6569 case MONO_WRAPPER_REMOTING_INVOKE:
6570 case MONO_WRAPPER_UNKNOWN:
6571 case MONO_WRAPPER_WRITE_BARRIER:
6572 case MONO_WRAPPER_DELEGATE_INVOKE:
6573 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6574 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6575 case MONO_WRAPPER_SYNCHRONIZED:
6577 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6578 case MONO_WRAPPER_CASTCLASS: {
6579 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6588 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6592 if (!method->token) {
6593 /* The method is part of a constructed type like Int[,].Set (). */
6594 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6595 if (method->klass->rank)
6605 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6607 switch (patch_info->type) {
6608 case MONO_PATCH_INFO_METHOD:
6609 case MONO_PATCH_INFO_METHODCONST:
6610 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6611 MonoMethod *method = patch_info->data.method;
6613 return can_encode_method (acfg, method);
6615 case MONO_PATCH_INFO_VTABLE:
6616 case MONO_PATCH_INFO_CLASS_INIT:
6617 case MONO_PATCH_INFO_CLASS:
6618 case MONO_PATCH_INFO_IID:
6619 case MONO_PATCH_INFO_ADJUSTED_IID:
6620 if (!can_encode_class (acfg, patch_info->data.klass)) {
6621 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6625 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6626 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6627 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6632 case MONO_PATCH_INFO_RGCTX_FETCH: {
6633 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6635 if (!can_encode_method (acfg, entry->method))
6637 if (!can_encode_patch (acfg, entry->data))
6651 * AOT compile a given method.
6652 * This function might be called by multiple threads, so it must be thread-safe.
6655 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6658 MonoJumpInfo *patch_info;
6661 MonoMethod *wrapped;
6664 if (acfg->aot_opts.metadata_only)
6667 mono_acfg_lock (acfg);
6668 index = get_method_index (acfg, method);
6669 mono_acfg_unlock (acfg);
6671 /* fixme: maybe we can also precompile wrapper methods */
6672 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6673 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6674 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6675 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6679 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6682 wrapped = mono_marshal_method_from_wrapper (method);
6683 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6684 // FIXME: The wrapper should be generic too, but it is not
6687 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6690 InterlockedIncrement (&acfg->stats.mcount);
6693 if (method->is_generic || method->klass->generic_container) {
6694 InterlockedIncrement (&acfg->stats.genericcount);
6699 //acfg->aot_opts.print_skipped_methods = TRUE;
6702 * Since these methods are the only ones which are compiled with
6703 * AOT support, and they are not used by runtime startup/shutdown code,
6704 * the runtime will not see AOT methods during AOT compilation,so it
6705 * does not need to support them by creating a fake GOT etc.
6707 flags = JIT_FLAG_AOT;
6708 if (acfg->aot_opts.full_aot)
6709 flags |= JIT_FLAG_FULL_AOT;
6711 flags |= JIT_FLAG_LLVM;
6712 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6713 mono_loader_clear_error ();
6715 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6716 if (acfg->aot_opts.print_skipped_methods)
6717 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6718 InterlockedIncrement (&acfg->stats.genericcount);
6721 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6722 if (acfg->aot_opts.print_skipped_methods)
6723 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6724 /* Let the exception happen at runtime */
6728 if (cfg->disable_aot) {
6729 if (acfg->aot_opts.print_skipped_methods)
6730 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6731 InterlockedIncrement (&acfg->stats.ocount);
6732 mono_destroy_compile (cfg);
6735 cfg->method_index = index;
6737 /* Nullify patches which need no aot processing */
6738 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6739 switch (patch_info->type) {
6740 case MONO_PATCH_INFO_LABEL:
6741 case MONO_PATCH_INFO_BB:
6742 patch_info->type = MONO_PATCH_INFO_NONE;
6749 /* Collect method->token associations from the cfg */
6750 mono_acfg_lock (acfg);
6751 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6752 mono_acfg_unlock (acfg);
6753 g_hash_table_destroy (cfg->token_info_hash);
6754 cfg->token_info_hash = NULL;
6757 * Check for absolute addresses.
6760 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6761 switch (patch_info->type) {
6762 case MONO_PATCH_INFO_ABS:
6763 /* unable to handle this */
6772 if (acfg->aot_opts.print_skipped_methods)
6773 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6774 InterlockedIncrement (&acfg->stats.abscount);
6775 mono_destroy_compile (cfg);
6779 /* Lock for the rest of the code */
6780 mono_acfg_lock (acfg);
6783 * Check for methods/klasses we can't encode.
6786 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6787 if (!can_encode_patch (acfg, patch_info))
6792 if (acfg->aot_opts.print_skipped_methods)
6793 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6794 acfg->stats.ocount++;
6795 mono_destroy_compile (cfg);
6796 mono_acfg_unlock (acfg);
6800 if (method->is_inflated && acfg->aot_opts.log_instances) {
6801 if (acfg->instances_logfile)
6802 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6804 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6807 /* Adds generic instances referenced by this method */
6809 * The depth is used to avoid infinite loops when generic virtual recursion is
6812 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6813 if (!acfg->aot_opts.no_instances && depth < 32) {
6814 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6815 switch (patch_info->type) {
6816 case MONO_PATCH_INFO_METHOD: {
6817 MonoMethod *m = patch_info->data.method;
6818 if (m->is_inflated) {
6819 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6820 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6821 !method_has_type_vars (m)) {
6822 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6823 if (acfg->aot_opts.full_aot)
6824 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6826 add_extra_method_with_depth (acfg, m, depth + 1);
6827 add_types_from_method_header (acfg, m);
6830 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6832 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6833 add_extra_method_with_depth (acfg, m, depth + 1);
6836 case MONO_PATCH_INFO_VTABLE: {
6837 MonoClass *klass = patch_info->data.klass;
6839 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6840 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6843 case MONO_PATCH_INFO_SFLDA: {
6844 MonoClass *klass = patch_info->data.field->parent;
6846 /* The .cctor needs to run at runtime. */
6847 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6848 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6857 /* Determine whenever the method has GOT slots */
6858 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6859 switch (patch_info->type) {
6860 case MONO_PATCH_INFO_GOT_OFFSET:
6861 case MONO_PATCH_INFO_NONE:
6862 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6864 case MONO_PATCH_INFO_IMAGE:
6865 /* The assembly is stored in GOT slot 0 */
6866 if (patch_info->data.image != acfg->image)
6867 cfg->has_got_slots = TRUE;
6870 if (!is_plt_patch (patch_info))
6871 cfg->has_got_slots = TRUE;
6876 if (!cfg->has_got_slots)
6877 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6880 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6882 /* Make a copy of the patch info which is in the mempool */
6884 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6886 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6887 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6890 patches = new_patch_info;
6892 patches_end->next = new_patch_info;
6893 patches_end = new_patch_info;
6895 cfg->patch_info = patches;
6897 /* Make a copy of the unwind info */
6899 GSList *l, *unwind_ops;
6903 for (l = cfg->unwind_ops; l; l = l->next) {
6904 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6905 memcpy (op, l->data, sizeof (MonoUnwindOp));
6906 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6908 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6910 /* Make a copy of the argument/local info */
6912 MonoInst **args, **locals;
6913 MonoMethodSignature *sig;
6914 MonoMethodHeader *header;
6917 sig = mono_method_signature (method);
6918 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6919 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6920 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6921 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6925 header = mono_method_get_header (method);
6926 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6927 for (i = 0; i < header->num_locals; ++i) {
6928 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6929 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6931 cfg->locals = locals;
6934 /* Free some fields used by cfg to conserve memory */
6935 mono_mempool_destroy (cfg->mempool);
6936 cfg->mempool = NULL;
6937 g_free (cfg->varinfo);
6938 cfg->varinfo = NULL;
6942 mono_regstate_free (cfg->rs);
6946 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6948 while (index >= acfg->cfgs_size) {
6949 MonoCompile **new_cfgs;
6952 new_size = acfg->cfgs_size * 2;
6953 new_cfgs = g_new0 (MonoCompile*, new_size);
6954 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6955 g_free (acfg->cfgs);
6956 acfg->cfgs = new_cfgs;
6957 acfg->cfgs_size = new_size;
6959 acfg->cfgs [index] = cfg;
6961 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6964 if (cfg->orig_method->wrapper_type)
6965 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6968 mono_acfg_unlock (acfg);
6970 InterlockedIncrement (&acfg->stats.ccount);
6974 compile_thread_main (gpointer *user_data)
6976 MonoDomain *domain = user_data [0];
6977 MonoAotCompile *acfg = user_data [1];
6978 GPtrArray *methods = user_data [2];
6981 mono_thread_attach (domain);
6983 for (i = 0; i < methods->len; ++i)
6984 compile_method (acfg, g_ptr_array_index (methods, i));
6988 load_profile_files (MonoAotCompile *acfg)
6992 int file_index, res, method_index, i;
6995 GList *unordered, *l;
7000 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7002 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7007 infile = fopen (tmp, "r");
7010 printf ("Using profile data file '%s'\n", tmp);
7015 res = fscanf (infile, "%32s\n", ver);
7016 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7017 printf ("Profile file has wrong version or invalid.\n");
7024 MonoMethodDesc *desc;
7027 if (fgets (name, 1023, infile) == NULL)
7030 /* Kill the newline */
7031 if (strlen (name) > 0)
7032 name [strlen (name) - 1] = '\0';
7034 desc = mono_method_desc_new (name, TRUE);
7036 method = mono_method_desc_search_in_image (desc, acfg->image);
7038 if (method && mono_method_get_token (method)) {
7039 token = mono_method_get_token (method);
7040 method_index = mono_metadata_token_index (token) - 1;
7043 for (i = 0; i < acfg->method_order->len; ++i) {
7044 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7050 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7052 //printf ("No method found matching '%s'.\n", name);
7058 /* Add missing methods */
7060 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7062 for (i = 0; i < acfg->method_order->len; ++i) {
7063 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7069 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7071 unordered = g_list_reverse (unordered);
7072 for (l = unordered; l; l = l->next)
7073 g_ptr_array_add (acfg->method_order, l->data);
7076 /* Used by the LLVM backend */
7078 mono_aot_get_got_offset (MonoJumpInfo *ji)
7080 return get_got_offset (llvm_acfg, TRUE, ji);
7084 mono_aot_get_method_name (MonoCompile *cfg)
7086 if (llvm_acfg->aot_opts.static_link)
7087 /* Include the assembly name too to avoid duplicate symbol errors */
7088 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7090 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7094 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7096 return is_direct_callable (llvm_acfg, NULL, patch_info);
7100 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7102 MonoPltEntry *plt_entry;
7104 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7105 plt_entry->llvm_used = FALSE;
7109 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7111 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7112 MonoPltEntry *plt_entry;
7115 ji->data.target = data;
7117 if (!can_encode_patch (llvm_acfg, ji))
7120 plt_entry = get_plt_entry (llvm_acfg, ji);
7121 plt_entry->llvm_used = TRUE;
7123 #if defined(TARGET_MACH)
7124 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7126 return g_strdup_printf (plt_entry->llvm_symbol);
7131 mono_aot_get_method_index (MonoMethod *method)
7133 g_assert (llvm_acfg);
7134 return get_method_index (llvm_acfg, method);
7138 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7142 mono_acfg_lock (llvm_acfg);
7143 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7144 mono_acfg_unlock (llvm_acfg);
7154 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7158 emit_llvm_file (MonoAotCompile *acfg)
7160 char *command, *opts, *tempbc, *output_fname;
7162 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7163 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7167 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7168 * a lot of time, and doesn't seem to save much space.
7169 * The following optimizations cannot be enabled:
7171 * - 'jump-threading' changes our blockaddress references to int constants.
7172 * - 'basiccg' fails because it contains:
7173 * if (CS && !isa<IntrinsicInst>(II)) {
7174 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7175 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7176 * The opt list below was produced by taking the output of:
7177 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7178 * then removing tailcallelim + the global opts.
7179 * strip-dead-prototypes deletes unused intrinsics definitions.
7181 opts = g_strdup ("-instcombine -simplifycfg");
7182 //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");
7183 /* The dse pass is disabled because of #13734 and #17616 */
7185 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7186 * // If we have no DataLayout information around, then the size of the store
7187 * // is inferrable from the pointee type. If they are the same type, then
7188 * // we know that the store is safe.
7189 * if (AA.getDataLayout() == 0 &&
7190 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7191 * return OverwriteComplete;
7192 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7194 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");
7196 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7197 aot_printf (acfg, "Executing opt: %s\n", command);
7198 if (system (command) != 0)
7203 if (!acfg->llc_args)
7204 acfg->llc_args = g_string_new ("");
7206 /* Verbose asm slows down llc greatly */
7207 g_string_append (acfg->llc_args, " -asm-verbose=false");
7209 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7211 if (acfg->aot_opts.mtriple)
7212 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7214 if (acfg->llvm_separate)
7215 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7217 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7218 /* ios requires PIC code now */
7219 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7221 if (llvm_acfg->aot_opts.static_link)
7222 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7224 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7226 unlink (acfg->tmpfname);
7228 if (acfg->llvm_separate) {
7229 if (acfg->llvm_owriter) {
7230 /* Emit an object file directly */
7231 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7232 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7234 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7237 output_fname = g_strdup (acfg->tmpfname);
7239 command = g_strdup_printf ("%sllc %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7241 aot_printf (acfg, "Executing llc: %s\n", command);
7243 if (system (command) != 0)
7250 emit_code (MonoAotCompile *acfg)
7252 int oindex, i, prev_index;
7255 #if defined(TARGET_POWERPC64)
7256 sprintf (symbol, ".Lgot_addr");
7257 emit_section_change (acfg, ".text", 0);
7258 emit_alignment (acfg, 8);
7259 emit_label (acfg, symbol);
7260 emit_pointer (acfg, acfg->got_symbol);
7264 * This global symbol is used to compute the address of each method using the
7265 * code_offsets array. It is also used to compute the memory ranges occupied by
7266 * AOT code, so it must be equal to the address of the first emitted method.
7268 emit_section_change (acfg, ".text", 0);
7269 emit_alignment_code (acfg, 8);
7271 for (i = 0; i < acfg->nmethods; ++i) {
7272 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7273 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7278 if (!acfg->methods_symbol) {
7279 sprintf (symbol, "methods");
7280 emit_label (acfg, symbol);
7281 acfg->methods_symbol = g_strdup (symbol);
7283 emit_label (acfg, "jit_code_start");
7286 * Emit some padding so the local symbol for the first method doesn't have the
7287 * same address as 'methods'.
7289 #if defined(__default_codegen__)
7290 emit_padding (acfg, 16);
7291 #elif defined(__native_client_codegen__)
7293 const int kPaddingSize = 16;
7294 guint8 pad_buffer[kPaddingSize];
7295 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7296 emit_bytes (acfg, pad_buffer, kPaddingSize);
7300 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7304 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7306 cfg = acfg->cfgs [i];
7311 method = cfg->orig_method;
7313 /* Emit unbox trampoline */
7314 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7315 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7317 emit_section_change (acfg, ".text", 0);
7318 #ifdef __native_client_codegen__
7319 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7322 if (acfg->thumb_mixed && cfg->compile_llvm) {
7323 emit_set_thumb_mode (acfg);
7324 fprintf (acfg->fp, "\n.thumb_func\n");
7327 emit_label (acfg, symbol);
7329 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7331 if (acfg->thumb_mixed && cfg->compile_llvm)
7332 emit_set_arm_mode (acfg);
7335 if (cfg->compile_llvm)
7336 acfg->stats.llvm_count ++;
7338 emit_method_code (acfg, cfg);
7341 sprintf (symbol, "methods_end");
7342 emit_section_change (acfg, ".text", 0);
7343 emit_alignment_code (acfg, 8);
7344 emit_label (acfg, symbol);
7346 emit_label (acfg, "jit_code_end");
7348 /* To distinguish it from the next symbol */
7349 emit_padding (acfg, 4);
7352 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7353 * from optimizing them away, since it doesn't see that code_offsets references them.
7354 * JITted methods don't need this since they are referenced using assembler local
7356 * FIXME: This is why write-symbols doesn't work on OSX ?
7358 if (acfg->llvm && acfg->need_no_dead_strip) {
7359 fprintf (acfg->fp, "\n");
7360 for (i = 0; i < acfg->nmethods; ++i) {
7361 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7362 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7367 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7368 * This is PIE code, and the linker can update it if needed.
7370 sprintf (symbol, "method_addresses");
7371 emit_section_change (acfg, ".text", 1);
7372 emit_alignment_code (acfg, 8);
7373 emit_label (acfg, symbol);
7374 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7375 emit_unset_mode (acfg);
7376 if (acfg->need_no_dead_strip)
7377 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7379 for (i = 0; i < acfg->nmethods; ++i) {
7380 #ifdef MONO_ARCH_AOT_SUPPORTED
7384 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7386 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7390 sprintf (symbol, "method_addresses_end");
7391 emit_label (acfg, symbol);
7394 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7395 sprintf (symbol, "unbox_trampolines");
7396 emit_section_change (acfg, RODATA_SECT, 0);
7397 emit_alignment (acfg, 8);
7398 emit_label (acfg, symbol);
7401 for (i = 0; i < acfg->nmethods; ++i) {
7406 cfg = acfg->cfgs [i];
7410 method = cfg->orig_method;
7412 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7413 index = get_method_index (acfg, method);
7415 emit_int32 (acfg, index);
7416 /* Make sure the table is sorted by index */
7417 g_assert (index > prev_index);
7421 sprintf (symbol, "unbox_trampolines_end");
7422 emit_label (acfg, symbol);
7423 emit_int32 (acfg, 0);
7425 /* Emit a separate table with the trampoline addresses/offsets */
7426 sprintf (symbol, "unbox_trampoline_addresses");
7427 emit_section_change (acfg, ".text", 0);
7428 emit_alignment_code (acfg, 8);
7429 emit_label (acfg, symbol);
7431 for (i = 0; i < acfg->nmethods; ++i) {
7436 cfg = acfg->cfgs [i];
7440 method = cfg->orig_method;
7442 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7443 #ifdef MONO_ARCH_AOT_SUPPORTED
7446 index = get_method_index (acfg, method);
7447 sprintf (symbol, "ut_%d", index);
7449 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7456 emit_info (MonoAotCompile *acfg)
7462 offsets = g_new0 (gint32, acfg->nmethods);
7464 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7465 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7467 if (acfg->cfgs [i]) {
7468 emit_method_info (acfg, acfg->cfgs [i]);
7469 offsets [i] = acfg->cfgs [i]->method_info_offset;
7475 sprintf (symbol, "method_info_offsets");
7476 emit_section_change (acfg, RODATA_SECT, 1);
7477 emit_alignment (acfg, 8);
7478 emit_label (acfg, symbol);
7480 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7485 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7487 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7488 #define mix(a,b,c) { \
7489 a -= c; a ^= rot(c, 4); c += b; \
7490 b -= a; b ^= rot(a, 6); a += c; \
7491 c -= b; c ^= rot(b, 8); b += a; \
7492 a -= c; a ^= rot(c,16); c += b; \
7493 b -= a; b ^= rot(a,19); a += c; \
7494 c -= b; c ^= rot(b, 4); b += a; \
7496 #define final(a,b,c) { \
7497 c ^= b; c -= rot(b,14); \
7498 a ^= c; a -= rot(c,11); \
7499 b ^= a; b -= rot(a,25); \
7500 c ^= b; c -= rot(b,16); \
7501 a ^= c; a -= rot(c,4); \
7502 b ^= a; b -= rot(a,14); \
7503 c ^= b; c -= rot(b,24); \
7507 mono_aot_type_hash (MonoType *t1)
7509 guint hash = t1->type;
7511 hash |= t1->byref << 6; /* do not collide with t1->type values */
7513 case MONO_TYPE_VALUETYPE:
7514 case MONO_TYPE_CLASS:
7515 case MONO_TYPE_SZARRAY:
7516 /* check if the distribution is good enough */
7517 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7519 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7520 case MONO_TYPE_ARRAY:
7521 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7522 case MONO_TYPE_GENERICINST:
7523 return ((hash << 5) - hash) ^ 0;
7530 * mono_aot_method_hash:
7532 * Return a hash code for methods which only depends on metadata.
7535 mono_aot_method_hash (MonoMethod *method)
7537 MonoMethodSignature *sig;
7541 guint32 *hashes_start, *hashes;
7543 MonoGenericInst *ginst = NULL;
7545 /* Similar to the hash in mono_method_get_imt_slot () */
7547 sig = mono_method_signature (method);
7549 if (method->is_inflated)
7550 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7552 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7553 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7554 hashes = hashes_start;
7556 /* Some wrappers are assigned to random classes */
7557 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7558 klass = method->klass;
7560 klass = mono_defaults.object_class;
7562 if (!method->wrapper_type) {
7563 char *full_name = mono_type_full_name (&klass->byval_arg);
7565 hashes [0] = mono_metadata_str_hash (full_name);
7569 hashes [0] = mono_metadata_str_hash (klass->name);
7570 hashes [1] = mono_metadata_str_hash (klass->name_space);
7572 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7573 /* The method name includes a stringified pointer */
7576 hashes [2] = mono_metadata_str_hash (method->name);
7577 hashes [3] = method->wrapper_type;
7578 hashes [4] = mono_aot_type_hash (sig->ret);
7580 for (i = 0; i < sig->param_count; i++) {
7581 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7584 for (i = 0; i < ginst->type_argc; ++i)
7585 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7587 g_assert (hindex == hashes_count);
7589 /* Setup internal state */
7590 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7592 /* Handle most of the hashes */
7593 while (hashes_count > 3) {
7602 /* Handle the last 3 hashes (all the case statements fall through) */
7603 switch (hashes_count) {
7604 case 3 : c += hashes [2];
7605 case 2 : b += hashes [1];
7606 case 1 : a += hashes [0];
7608 case 0: /* nothing left to add */
7612 free (hashes_start);
7621 * mono_aot_get_array_helper_from_wrapper;
7623 * Get the helper method in Array called by an array wrapper method.
7626 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7630 MonoGenericContext ctx;
7631 MonoType *args [16];
7632 char *mname, *iname, *s, *s2, *helper_name = NULL;
7634 prefix = "System.Collections.Generic";
7635 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7636 s2 = strstr (s, "`1.");
7642 //printf ("X: %s %s\n", iname, mname);
7644 if (!strcmp (iname, "IList"))
7645 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7647 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7648 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7650 g_free (helper_name);
7653 if (m->is_generic) {
7654 memset (&ctx, 0, sizeof (ctx));
7655 args [0] = &method->klass->element_class->byval_arg;
7656 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7657 m = mono_class_inflate_generic_method (m, &ctx);
7663 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7665 typedef struct HashEntry {
7666 guint32 key, value, index;
7667 struct HashEntry *next;
7671 * emit_extra_methods:
7673 * Emit methods which are not in the METHOD table, like wrappers.
7676 emit_extra_methods (MonoAotCompile *acfg)
7678 int i, table_size, buf_size;
7681 guint32 *info_offsets;
7684 HashEntry *entry, *new_entry;
7685 int nmethods, max_chain_length;
7688 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7690 /* Emit method info */
7692 for (i = 0; i < acfg->extra_methods->len; ++i) {
7693 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7694 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7700 p = buf = g_malloc (buf_size);
7704 method = cfg->method_to_register;
7706 encode_method_ref (acfg, method, p, &p);
7708 g_assert ((p - buf) < buf_size);
7710 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7715 * Construct a chained hash table for mapping indexes in extra_method_info to
7718 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7719 table = g_ptr_array_sized_new (table_size);
7720 for (i = 0; i < table_size; ++i)
7721 g_ptr_array_add (table, NULL);
7722 chain_lengths = g_new0 (int, table_size);
7723 max_chain_length = 0;
7724 for (i = 0; i < acfg->extra_methods->len; ++i) {
7725 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7726 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7732 key = info_offsets [i];
7733 value = get_method_index (acfg, method);
7735 hash = mono_aot_method_hash (method) % table_size;
7736 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7738 chain_lengths [hash] ++;
7739 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7741 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7742 new_entry->key = key;
7743 new_entry->value = value;
7745 entry = g_ptr_array_index (table, hash);
7746 if (entry == NULL) {
7747 new_entry->index = hash;
7748 g_ptr_array_index (table, hash) = new_entry;
7751 entry = entry->next;
7753 entry->next = new_entry;
7754 new_entry->index = table->len;
7755 g_ptr_array_add (table, new_entry);
7759 //printf ("MAX: %d\n", max_chain_length);
7761 /* Emit the table */
7762 sprintf (symbol, "extra_method_table");
7763 emit_section_change (acfg, RODATA_SECT, 0);
7764 emit_alignment (acfg, 8);
7765 emit_label (acfg, symbol);
7767 emit_int32 (acfg, table_size);
7768 for (i = 0; i < table->len; ++i) {
7769 HashEntry *entry = g_ptr_array_index (table, i);
7771 if (entry == NULL) {
7772 emit_int32 (acfg, 0);
7773 emit_int32 (acfg, 0);
7774 emit_int32 (acfg, 0);
7776 //g_assert (entry->key > 0);
7777 emit_int32 (acfg, entry->key);
7778 emit_int32 (acfg, entry->value);
7780 emit_int32 (acfg, entry->next->index);
7782 emit_int32 (acfg, 0);
7787 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7788 * This is used by mono_aot_find_jit_info ().
7790 sprintf (symbol, "extra_method_info_offsets");
7791 emit_section_change (acfg, RODATA_SECT, 0);
7792 emit_alignment (acfg, 8);
7793 emit_label (acfg, symbol);
7795 emit_int32 (acfg, acfg->extra_methods->len);
7796 for (i = 0; i < acfg->extra_methods->len; ++i) {
7797 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7799 emit_int32 (acfg, get_method_index (acfg, method));
7800 emit_int32 (acfg, info_offsets [i]);
7805 emit_exception_info (MonoAotCompile *acfg)
7811 offsets = g_new0 (gint32, acfg->nmethods);
7812 for (i = 0; i < acfg->nmethods; ++i) {
7813 if (acfg->cfgs [i]) {
7814 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7815 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7821 sprintf (symbol, "ex_info_offsets");
7822 emit_section_change (acfg, RODATA_SECT, 1);
7823 emit_alignment (acfg, 8);
7824 emit_label (acfg, symbol);
7826 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7831 emit_unwind_info (MonoAotCompile *acfg)
7837 * The unwind info contains a lot of duplicates so we emit each unique
7838 * entry once, and only store the offset from the start of the table in the
7842 sprintf (symbol, "unwind_info");
7843 emit_section_change (acfg, RODATA_SECT, 1);
7844 emit_alignment (acfg, 8);
7845 emit_label (acfg, symbol);
7847 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7848 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7849 guint8 *unwind_info;
7850 guint32 unwind_info_len;
7854 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7857 encode_value (unwind_info_len, p, &p);
7858 emit_bytes (acfg, buf, p - buf);
7859 emit_bytes (acfg, unwind_info, unwind_info_len);
7861 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7866 emit_class_info (MonoAotCompile *acfg)
7872 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7873 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7874 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7876 sprintf (symbol, "class_info_offsets");
7877 emit_section_change (acfg, RODATA_SECT, 1);
7878 emit_alignment (acfg, 8);
7879 emit_label (acfg, symbol);
7881 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7885 typedef struct ClassNameTableEntry {
7886 guint32 token, index;
7887 struct ClassNameTableEntry *next;
7888 } ClassNameTableEntry;
7891 emit_class_name_table (MonoAotCompile *acfg)
7894 guint32 token, hash;
7899 ClassNameTableEntry *entry, *new_entry;
7902 * Construct a chained hash table for mapping class names to typedef tokens.
7904 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7905 table = g_ptr_array_sized_new (table_size);
7906 for (i = 0; i < table_size; ++i)
7907 g_ptr_array_add (table, NULL);
7908 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7910 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7911 klass = mono_class_get_checked (acfg->image, token, &error);
7913 mono_error_cleanup (&error);
7916 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7917 hash = mono_metadata_str_hash (full_name) % table_size;
7920 /* FIXME: Allocate from the mempool */
7921 new_entry = g_new0 (ClassNameTableEntry, 1);
7922 new_entry->token = token;
7924 entry = g_ptr_array_index (table, hash);
7925 if (entry == NULL) {
7926 new_entry->index = hash;
7927 g_ptr_array_index (table, hash) = new_entry;
7930 entry = entry->next;
7932 entry->next = new_entry;
7933 new_entry->index = table->len;
7934 g_ptr_array_add (table, new_entry);
7938 /* Emit the table */
7939 sprintf (symbol, "class_name_table");
7940 emit_section_change (acfg, RODATA_SECT, 0);
7941 emit_alignment (acfg, 8);
7942 emit_label (acfg, symbol);
7944 /* FIXME: Optimize memory usage */
7945 g_assert (table_size < 65000);
7946 emit_int16 (acfg, table_size);
7947 g_assert (table->len < 65000);
7948 for (i = 0; i < table->len; ++i) {
7949 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7951 if (entry == NULL) {
7952 emit_int16 (acfg, 0);
7953 emit_int16 (acfg, 0);
7955 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7957 emit_int16 (acfg, entry->next->index);
7959 emit_int16 (acfg, 0);
7965 emit_image_table (MonoAotCompile *acfg)
7971 * The image table is small but referenced in a lot of places.
7972 * So we emit it at once, and reference its elements by an index.
7975 sprintf (symbol, "image_table");
7976 emit_section_change (acfg, RODATA_SECT, 1);
7977 emit_alignment (acfg, 8);
7978 emit_label (acfg, symbol);
7980 emit_int32 (acfg, acfg->image_table->len);
7981 for (i = 0; i < acfg->image_table->len; i++) {
7982 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7983 MonoAssemblyName *aname = &image->assembly->aname;
7985 /* FIXME: Support multi-module assemblies */
7986 g_assert (image->assembly->image == image);
7988 emit_string (acfg, image->assembly_name);
7989 emit_string (acfg, image->guid);
7990 emit_string (acfg, aname->culture ? aname->culture : "");
7991 emit_string (acfg, (const char*)aname->public_key_token);
7993 emit_alignment (acfg, 8);
7994 emit_int32 (acfg, aname->flags);
7995 emit_int32 (acfg, aname->major);
7996 emit_int32 (acfg, aname->minor);
7997 emit_int32 (acfg, aname->build);
7998 emit_int32 (acfg, aname->revision);
8003 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8006 int i, first_plt_got_patch, buf_size;
8008 guint32 *got_info_offsets;
8009 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8011 /* Add the patches needed by the PLT to the GOT */
8013 acfg->plt_got_offset_base = acfg->got_offset;
8014 first_plt_got_patch = info->got_patches->len;
8015 for (i = 1; i < acfg->plt_offset; ++i) {
8016 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8018 g_ptr_array_add (info->got_patches, plt_entry->ji);
8020 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8023 acfg->got_offset += acfg->plt_offset;
8028 * - optimize offsets table.
8029 * - reduce number of exported symbols.
8030 * - emit info for a klass only once.
8031 * - determine when a method uses a GOT slot which is guaranteed to be already
8033 * - clean up and document the code.
8034 * - use String.Empty in class libs.
8037 /* Encode info required to decode shared GOT entries */
8038 buf_size = info->got_patches->len * 128;
8039 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8040 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8042 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8044 if (acfg->plt_offset)
8045 acfg->plt_got_info_offsets [0] = 0;
8047 for (i = 0; i < info->got_patches->len; ++i) {
8048 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8053 encode_value (ji->type, p, &p);
8055 encode_patch (acfg, ji, p, &p);
8056 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8057 g_assert (p - buf <= buf_size);
8058 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8060 if (!llvm && i >= first_plt_got_patch)
8061 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8062 acfg->stats.got_info_size += p - buf;
8065 /* Emit got_info_offsets table */
8067 sprintf (symbol, "llvm_got_info_offsets");
8069 sprintf (symbol, "got_info_offsets");
8070 emit_section_change (acfg, RODATA_SECT, 1);
8071 emit_alignment (acfg, 8);
8072 emit_label (acfg, symbol);
8074 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8075 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8079 emit_got (MonoAotCompile *acfg)
8083 /* Don't make GOT global so accesses to it don't need relocations */
8084 sprintf (symbol, "%s", acfg->got_symbol);
8085 emit_section_change (acfg, ".bss", 0);
8086 emit_alignment (acfg, 8);
8087 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8088 emit_label (acfg, symbol);
8089 if (acfg->got_offset > 0)
8090 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8092 sprintf (symbol, "got_end");
8093 emit_label (acfg, symbol);
8096 typedef struct GlobalsTableEntry {
8097 guint32 value, index;
8098 struct GlobalsTableEntry *next;
8099 } GlobalsTableEntry;
8102 emit_globals (MonoAotCompile *acfg)
8108 GlobalsTableEntry *entry, *new_entry;
8110 if (!acfg->aot_opts.static_link)
8114 * When static linking, we emit a table containing our globals.
8118 * Construct a chained hash table for mapping global names to their index in
8119 * the globals table.
8121 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8122 table = g_ptr_array_sized_new (table_size);
8123 for (i = 0; i < table_size; ++i)
8124 g_ptr_array_add (table, NULL);
8125 for (i = 0; i < acfg->globals->len; ++i) {
8126 char *name = g_ptr_array_index (acfg->globals, i);
8128 hash = mono_metadata_str_hash (name) % table_size;
8130 /* FIXME: Allocate from the mempool */
8131 new_entry = g_new0 (GlobalsTableEntry, 1);
8132 new_entry->value = i;
8134 entry = g_ptr_array_index (table, hash);
8135 if (entry == NULL) {
8136 new_entry->index = hash;
8137 g_ptr_array_index (table, hash) = new_entry;
8140 entry = entry->next;
8142 entry->next = new_entry;
8143 new_entry->index = table->len;
8144 g_ptr_array_add (table, new_entry);
8148 /* Emit the table */
8149 sprintf (symbol, ".Lglobals_hash");
8150 emit_section_change (acfg, RODATA_SECT, 0);
8151 emit_alignment (acfg, 8);
8152 emit_label (acfg, symbol);
8154 /* FIXME: Optimize memory usage */
8155 g_assert (table_size < 65000);
8156 emit_int16 (acfg, table_size);
8157 for (i = 0; i < table->len; ++i) {
8158 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8160 if (entry == NULL) {
8161 emit_int16 (acfg, 0);
8162 emit_int16 (acfg, 0);
8164 emit_int16 (acfg, entry->value + 1);
8166 emit_int16 (acfg, entry->next->index);
8168 emit_int16 (acfg, 0);
8172 /* Emit the names */
8173 for (i = 0; i < acfg->globals->len; ++i) {
8174 char *name = g_ptr_array_index (acfg->globals, i);
8176 sprintf (symbol, "name_%d", i);
8177 emit_section_change (acfg, RODATA_SECT, 1);
8179 emit_alignment (acfg, 4);
8181 emit_label (acfg, symbol);
8182 emit_string (acfg, name);
8185 /* Emit the globals table */
8186 sprintf (symbol, "globals");
8187 emit_section_change (acfg, ".data", 0);
8188 /* This is not a global, since it is accessed by the init function */
8189 emit_alignment (acfg, 8);
8190 emit_label (acfg, symbol);
8192 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8193 emit_pointer (acfg, symbol);
8195 for (i = 0; i < acfg->globals->len; ++i) {
8196 char *name = g_ptr_array_index (acfg->globals, i);
8198 sprintf (symbol, "name_%d", i);
8199 emit_pointer (acfg, symbol);
8201 g_assert (strlen (name) < sizeof (symbol));
8202 sprintf (symbol, "%s", name);
8203 emit_pointer (acfg, symbol);
8205 /* Null terminate the table */
8206 emit_int32 (acfg, 0);
8207 emit_int32 (acfg, 0);
8211 emit_autoreg (MonoAotCompile *acfg)
8216 * Emit a function into the .ctor section which will be called by the ELF
8217 * loader to register this module with the runtime.
8219 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8222 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8224 arch_emit_autoreg (acfg, symbol);
8230 emit_mem_end (MonoAotCompile *acfg)
8234 sprintf (symbol, "mem_end");
8235 emit_section_change (acfg, ".text", 1);
8236 emit_alignment_code (acfg, 8);
8237 emit_label (acfg, symbol);
8241 * Emit a structure containing all the information not stored elsewhere.
8244 emit_file_info (MonoAotCompile *acfg)
8249 const char *gc_name;
8252 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8254 if (acfg->aot_opts.bind_to_runtime_version) {
8255 build_info = mono_get_runtime_build_info ();
8256 emit_string_symbol (acfg, "runtime_version", build_info);
8257 g_free (build_info);
8259 emit_string_symbol (acfg, "runtime_version", "");
8262 /* Emit a string holding the assembly name */
8263 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8266 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8269 gc_name = mono_gc_get_gc_name ();
8270 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8272 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8273 emit_section_change (acfg, ".data", 0);
8274 emit_alignment (acfg, 8);
8275 emit_label (acfg, symbol);
8276 if (!acfg->aot_opts.static_link)
8277 emit_global (acfg, symbol, FALSE);
8279 /* The data emitted here must match MonoAotFileInfo. */
8281 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8282 emit_int32 (acfg, 0);
8285 * We emit pointers to our data structures instead of emitting global symbols which
8286 * point to them, to reduce the number of globals, and because using globals leads to
8287 * various problems (i.e. arm/thumb).
8289 emit_pointer (acfg, acfg->got_symbol);
8291 emit_pointer (acfg, acfg->llvm_got_symbol);
8293 emit_pointer (acfg, NULL);
8294 emit_pointer (acfg, acfg->methods_symbol);
8295 emit_pointer (acfg, "jit_code_start");
8296 emit_pointer (acfg, "jit_code_end");
8299 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8301 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8303 emit_pointer (acfg, NULL);
8305 emit_pointer (acfg, "blob");
8306 emit_pointer (acfg, "class_name_table");
8307 emit_pointer (acfg, "class_info_offsets");
8308 emit_pointer (acfg, "method_info_offsets");
8309 emit_pointer (acfg, "ex_info_offsets");
8310 emit_pointer (acfg, "method_addresses");
8311 emit_pointer (acfg, "extra_method_info_offsets");
8312 emit_pointer (acfg, "extra_method_table");
8313 emit_pointer (acfg, "got_info_offsets");
8315 emit_pointer (acfg, "llvm_got_info_offsets");
8317 emit_pointer (acfg, NULL);
8318 emit_pointer (acfg, "methods_end");
8319 emit_pointer (acfg, "unwind_info");
8320 emit_pointer (acfg, "mem_end");
8321 emit_pointer (acfg, "image_table");
8322 emit_pointer (acfg, "plt");
8323 emit_pointer (acfg, "plt_end");
8324 emit_pointer (acfg, "assembly_guid");
8325 emit_pointer (acfg, "runtime_version");
8326 if (acfg->num_trampoline_got_entries) {
8327 emit_pointer (acfg, "specific_trampolines");
8328 emit_pointer (acfg, "static_rgctx_trampolines");
8329 emit_pointer (acfg, "imt_thunks");
8330 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8332 emit_pointer (acfg, NULL);
8333 emit_pointer (acfg, NULL);
8334 emit_pointer (acfg, NULL);
8335 emit_pointer (acfg, NULL);
8337 if (acfg->thumb_mixed) {
8338 emit_pointer (acfg, "thumb_end");
8340 emit_pointer (acfg, NULL);
8342 if (acfg->aot_opts.static_link) {
8343 emit_pointer (acfg, "globals");
8345 emit_pointer (acfg, NULL);
8347 emit_pointer (acfg, "assembly_name");
8348 emit_pointer (acfg, "unbox_trampolines");
8349 emit_pointer (acfg, "unbox_trampolines_end");
8350 emit_pointer (acfg, "unbox_trampoline_addresses");
8352 emit_int32 (acfg, acfg->plt_got_offset_base);
8353 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8354 emit_int32 (acfg, acfg->plt_offset);
8355 emit_int32 (acfg, acfg->nmethods);
8356 emit_int32 (acfg, acfg->flags);
8357 emit_int32 (acfg, acfg->opts);
8358 emit_int32 (acfg, acfg->simd_opts);
8359 emit_int32 (acfg, gc_name_offset);
8361 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8362 emit_int32 (acfg, acfg->num_trampolines [i]);
8363 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8364 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8365 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8366 emit_int32 (acfg, acfg->trampoline_size [i]);
8367 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8369 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8374 memset (&t, 0, sizeof (MonoType));
8375 t.type = MONO_TYPE_R8;
8376 mono_type_size (&t, &align);
8377 emit_int32 (acfg, align);
8379 memset (&t, 0, sizeof (MonoType));
8380 t.type = MONO_TYPE_I8;
8381 mono_type_size (&t, &align);
8383 emit_int32 (acfg, align);
8386 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8387 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8389 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8390 emit_int32 (acfg, acfg->tramp_page_size);
8391 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8392 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8394 if (acfg->aot_opts.static_link) {
8398 * Emit a global symbol which can be passed by an embedding app to
8399 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8402 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8404 /* Get rid of characters which cannot occur in symbols */
8406 for (p = symbol; *p; ++p) {
8407 if (!(isalnum (*p) || *p == '_'))
8410 acfg->static_linking_symbol = g_strdup (symbol);
8411 emit_global_inner (acfg, symbol, FALSE);
8412 emit_alignment (acfg, sizeof (gpointer));
8413 emit_label (acfg, symbol);
8414 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8419 emit_blob (MonoAotCompile *acfg)
8423 sprintf (symbol, "blob");
8424 emit_section_change (acfg, RODATA_SECT, 1);
8425 emit_alignment (acfg, 8);
8426 emit_label (acfg, symbol);
8428 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8432 emit_objc_selectors (MonoAotCompile *acfg)
8436 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8441 * cat > foo.m << EOF
8444 * return @selector(print:);
8449 img_writer_emit_unset_mode (acfg->w);
8450 g_assert (acfg->fp);
8451 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8452 fprintf (acfg->fp, ".align 3\n");
8453 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8454 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8455 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8457 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8458 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8459 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8460 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8463 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8464 fprintf (acfg->fp, ".align 3\n");
8465 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8466 fprintf (acfg->fp, ".long 0\n");
8467 fprintf (acfg->fp, ".long 16\n");
8471 emit_dwarf_info (MonoAotCompile *acfg)
8473 #ifdef EMIT_DWARF_INFO
8477 /* DIEs for methods */
8478 for (i = 0; i < acfg->nmethods; ++i) {
8479 MonoCompile *cfg = acfg->cfgs [i];
8484 // FIXME: LLVM doesn't define .Lme_...
8485 if (cfg->compile_llvm)
8488 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8490 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 ()));
8496 collect_methods (MonoAotCompile *acfg)
8499 MonoImage *image = acfg->image;
8501 /* Collect methods */
8502 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8504 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8506 method = mono_get_method (acfg->image, token, NULL);
8509 aot_printerrf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8510 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8514 /* Load all methods eagerly to skip the slower lazy loading code */
8515 mono_class_setup_methods (method->klass);
8517 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8518 /* Compile the wrapper instead */
8519 /* We do this here instead of add_wrappers () because it is easy to do it here */
8520 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8524 /* FIXME: Some mscorlib methods don't have debug info */
8526 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8527 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8528 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8529 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8530 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8531 if (!mono_debug_lookup_method (method)) {
8532 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8539 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8540 add_method_with_index (acfg, method, i, FALSE);
8541 acfg->method_index ++;
8544 /* gsharedvt methods */
8545 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8547 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8549 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8552 method = mono_get_method (acfg->image, token, NULL);
8556 if (strcmp (method->name, "gshared2"))
8560 if (!strstr (method->klass->image->name, "mini"))
8563 if (method->is_generic || method->klass->generic_container) {
8564 MonoMethod *gshared;
8566 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8567 add_extra_method (acfg, gshared);
8571 add_generic_instances (acfg);
8573 if (acfg->aot_opts.full_aot)
8574 add_wrappers (acfg);
8579 compile_methods (MonoAotCompile *acfg)
8583 if (acfg->aot_opts.nthreads > 0) {
8588 gpointer *user_data;
8589 MonoMethod **methods;
8591 methods_len = acfg->methods->len;
8593 len = acfg->methods->len / acfg->aot_opts.nthreads;
8596 * Partition the list of methods into fragments, and hand it to threads to
8599 threads = g_ptr_array_new ();
8600 /* Make a copy since acfg->methods is modified by compile_method () */
8601 methods = g_new0 (MonoMethod*, methods_len);
8602 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8603 for (i = 0; i < methods_len; ++i)
8604 methods [i] = g_ptr_array_index (acfg->methods, i);
8606 while (i < methods_len) {
8607 frag = g_ptr_array_new ();
8608 for (j = 0; j < len; ++j) {
8609 if (i < methods_len) {
8610 g_ptr_array_add (frag, methods [i]);
8615 user_data = g_new0 (gpointer, 3);
8616 user_data [0] = mono_domain_get ();
8617 user_data [1] = acfg;
8618 user_data [2] = frag;
8620 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8621 g_ptr_array_add (threads, handle);
8625 for (i = 0; i < threads->len; ++i) {
8626 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8632 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8633 for (i = methods_len; i < acfg->methods->len; ++i) {
8634 /* This can new methods to acfg->methods */
8635 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8640 compile_asm (MonoAotCompile *acfg)
8642 char *command, *objfile;
8643 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8644 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8646 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8647 #define AS_OPTIONS "--64"
8648 #elif defined(TARGET_POWERPC64)
8649 #define AS_OPTIONS "-a64 -mppc64"
8650 #define LD_OPTIONS "-m elf64ppc"
8651 #elif defined(sparc) && SIZEOF_VOID_P == 8
8652 #define AS_OPTIONS "-xarch=v9"
8653 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8654 #define AS_OPTIONS "-arch i386"
8656 #define AS_OPTIONS ""
8659 #ifdef __native_client_codegen__
8660 #if defined(TARGET_AMD64)
8661 #define AS_NAME "nacl64-as"
8663 #define AS_NAME "nacl-as"
8665 #elif defined(TARGET_OSX)
8666 #define AS_NAME "clang -c -x assembler"
8668 #define AS_NAME "as"
8672 #define LD_OPTIONS ""
8676 #define LD_NAME "ld -shared -G"
8677 #elif defined(__ppc__) && defined(TARGET_MACH)
8678 #define LD_NAME "gcc -dynamiclib"
8679 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8680 #define LD_NAME "clang --shared"
8681 #elif defined(HOST_WIN32)
8682 #define LD_NAME "gcc -shared --dll"
8683 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8684 #define LD_NAME "clang -m32 -dynamiclib"
8687 if (acfg->aot_opts.asm_only) {
8688 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8689 if (acfg->aot_opts.static_link)
8690 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8691 if (acfg->llvm_separate)
8692 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8696 if (acfg->aot_opts.static_link) {
8697 if (acfg->aot_opts.outfile)
8698 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8700 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8702 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8704 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);
8705 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8706 if (system (command) != 0) {
8712 if (acfg->llvm_separate && !acfg->llvm_owriter) {
8713 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);
8714 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8715 if (system (command) != 0) {
8724 if (acfg->aot_opts.static_link) {
8725 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8726 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8731 if (acfg->aot_opts.outfile)
8732 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8734 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8736 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8738 if (acfg->llvm_separate) {
8739 llvm_ofile = g_strdup (acfg->llvm_ofile);
8741 llvm_ofile = g_strdup ("");
8745 command = g_strdup_printf ("%s -o %s %s %s.o", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8747 command = g_strdup_printf ("%sld %s -shared -o %s %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8749 aot_printf (acfg, "Executing the native linker: %s\n", command);
8750 if (system (command) != 0) {
8751 g_free (tmp_outfile_name);
8752 g_free (outfile_name);
8760 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8761 printf ("Stripping the binary: %s\n", com);
8765 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8767 * gas generates 'mapping symbols' each time code and data is mixed, which
8768 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8770 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8771 aot_printf (acfg, "Stripping the binary: %s\n", command);
8772 if (system (command) != 0) {
8773 g_free (tmp_outfile_name);
8774 g_free (outfile_name);
8781 rename (tmp_outfile_name, outfile_name);
8783 #if defined(TARGET_MACH)
8784 command = g_strdup_printf ("dsymutil %s", outfile_name);
8785 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8786 if (system (command) != 0) {
8791 if (!acfg->aot_opts.save_temps)
8794 g_free (tmp_outfile_name);
8795 g_free (outfile_name);
8798 if (acfg->aot_opts.save_temps)
8799 aot_printf (acfg, "Retained input file.\n");
8801 unlink (acfg->tmpfname);
8806 static void init_got_info (GotInfo *info)
8810 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8811 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8812 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8813 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8814 info->got_patches = g_ptr_array_new ();
8817 static MonoAotCompile*
8818 acfg_create (MonoAssembly *ass, guint32 opts)
8820 MonoImage *image = ass->image;
8821 MonoAotCompile *acfg;
8823 acfg = g_new0 (MonoAotCompile, 1);
8824 acfg->methods = g_ptr_array_new ();
8825 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8826 acfg->method_depth = g_hash_table_new (NULL, NULL);
8827 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8828 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8829 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8830 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8831 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8832 acfg->image_hash = g_hash_table_new (NULL, NULL);
8833 acfg->image_table = g_ptr_array_new ();
8834 acfg->globals = g_ptr_array_new ();
8835 acfg->image = image;
8837 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8838 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8839 acfg->mempool = mono_mempool_new ();
8840 acfg->extra_methods = g_ptr_array_new ();
8841 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8842 acfg->unwind_ops = g_ptr_array_new ();
8843 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8844 acfg->method_order = g_ptr_array_new ();
8845 acfg->export_names = g_hash_table_new (NULL, NULL);
8846 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8847 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8848 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8849 mono_mutex_init_recursive (&acfg->mutex);
8851 init_got_info (&acfg->got_info);
8852 init_got_info (&acfg->llvm_got_info);
8858 got_info_free (GotInfo *info)
8862 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8863 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8864 g_free (info->patch_to_got_offset_by_type);
8865 g_hash_table_destroy (info->patch_to_got_offset);
8866 g_ptr_array_free (info->got_patches, TRUE);
8870 acfg_free (MonoAotCompile *acfg)
8874 img_writer_destroy (acfg->w);
8875 for (i = 0; i < acfg->nmethods; ++i)
8877 g_free (acfg->cfgs [i]);
8878 g_free (acfg->cfgs);
8879 g_free (acfg->static_linking_symbol);
8880 g_free (acfg->got_symbol);
8881 g_free (acfg->plt_symbol);
8882 g_ptr_array_free (acfg->methods, TRUE);
8883 g_ptr_array_free (acfg->image_table, TRUE);
8884 g_ptr_array_free (acfg->globals, TRUE);
8885 g_ptr_array_free (acfg->unwind_ops, TRUE);
8886 g_hash_table_destroy (acfg->method_indexes);
8887 g_hash_table_destroy (acfg->method_depth);
8888 g_hash_table_destroy (acfg->plt_offset_to_entry);
8889 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8890 if (acfg->patch_to_plt_entry [i])
8891 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8893 g_free (acfg->patch_to_plt_entry);
8894 g_hash_table_destroy (acfg->method_to_cfg);
8895 g_hash_table_destroy (acfg->token_info_hash);
8896 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8897 g_hash_table_destroy (acfg->image_hash);
8898 g_hash_table_destroy (acfg->unwind_info_offsets);
8899 g_hash_table_destroy (acfg->method_label_hash);
8900 g_hash_table_destroy (acfg->export_names);
8901 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8902 g_hash_table_destroy (acfg->klass_blob_hash);
8903 g_hash_table_destroy (acfg->method_blob_hash);
8904 got_info_free (&acfg->got_info);
8905 got_info_free (&acfg->llvm_got_info);
8906 mono_mempool_destroy (acfg->mempool);
8911 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8913 MonoImage *image = ass->image;
8914 int i, res, all_sizes;
8915 MonoAotCompile *acfg;
8916 char *outfile_name, *tmp_outfile_name, *p;
8917 char llvm_stats_msg [256];
8921 acfg = acfg_create (ass, opts);
8923 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8924 acfg->aot_opts.write_symbols = TRUE;
8925 acfg->aot_opts.ntrampolines = 1024;
8926 acfg->aot_opts.nrgctx_trampolines = 1024;
8927 acfg->aot_opts.nimt_trampolines = 128;
8928 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8929 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8930 acfg->aot_opts.llvm_path = g_strdup ("");
8932 acfg->aot_opts.use_trampolines_page = TRUE;
8935 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8937 if (acfg->aot_opts.logfile) {
8938 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
8941 if (acfg->aot_opts.static_link)
8942 acfg->aot_opts.autoreg = TRUE;
8944 //acfg->aot_opts.print_skipped_methods = TRUE;
8946 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8947 if (opts & MONO_OPT_GSHAREDVT) {
8948 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
8953 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8955 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8956 if (acfg->aot_opts.full_aot) {
8957 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
8962 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8963 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8967 if (acfg->aot_opts.static_link)
8968 acfg->aot_opts.asm_writer = TRUE;
8970 if (acfg->aot_opts.soft_debug) {
8971 MonoDebugOptions *opt = mini_get_debug_options ();
8973 opt->mdb_optimizations = TRUE;
8974 opt->gen_seq_points_debug_data = TRUE;
8976 if (!mono_debug_enabled ()) {
8977 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
8980 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8983 if (mono_use_llvm || acfg->aot_opts.llvm) {
8985 acfg->aot_opts.asm_writer = TRUE;
8986 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8988 if (acfg->aot_opts.soft_debug) {
8989 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8995 if (!acfg->aot_opts.asm_only || acfg->aot_opts.llvm_outfile) {
8997 * Emit all LLVM code into a separate assembly/object file and link with it
9000 #if LLVM_API_VERSION >= 3
9001 acfg->llvm_separate = TRUE;
9002 if (!acfg->aot_opts.asm_only)
9003 acfg->llvm_owriter = TRUE;
9006 if (acfg->aot_opts.llvm_outfile && !acfg->llvm_separate) {
9007 aot_printerrf (acfg, "The llvm-outputfile= option is not supported on this platform.\n");
9012 if (acfg->aot_opts.full_aot)
9013 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9015 if (acfg->aot_opts.instances_logfile_path) {
9016 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9017 if (!acfg->instances_logfile) {
9018 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9023 load_profile_files (acfg);
9025 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9026 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9027 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9029 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9030 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9031 if (acfg->opts & MONO_OPT_GSHAREDVT)
9032 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9035 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9039 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9040 /* Get rid of characters which cannot occur in symbols */
9041 for (p = acfg->assembly_name_sym; *p; ++p) {
9042 if (!(isalnum (*p) || *p == '_'))
9046 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9047 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9048 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9050 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9052 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9053 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9056 acfg->method_index = 1;
9060 if (acfg->aot_opts.full_aot)
9061 mono_set_partial_sharing_supported (TRUE);
9064 res = collect_methods (acfg);
9068 acfg->cfgs_size = acfg->methods->len + 32;
9069 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9071 /* PLT offset 0 is reserved for the PLT trampoline */
9072 acfg->plt_offset = 1;
9077 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, acfg->llvm_separate, acfg->llvm_separate);
9081 /* GOT offset 0 is reserved for the address of the current assembly */
9085 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9086 ji->type = MONO_PATCH_INFO_IMAGE;
9087 ji->data.image = acfg->image;
9089 get_got_offset (acfg, FALSE, ji);
9090 get_got_offset (acfg, TRUE, ji);
9092 /* Slot 1 is reserved for the mscorlib got addr */
9093 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9094 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9095 get_got_offset (acfg, FALSE, ji);
9096 get_got_offset (acfg, TRUE, ji);
9098 /* This is very common */
9099 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9100 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9101 get_got_offset (acfg, FALSE, ji);
9102 get_got_offset (acfg, TRUE, ji);
9104 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9105 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9106 get_got_offset (acfg, FALSE, ji);
9107 get_got_offset (acfg, TRUE, ji);
9112 compile_methods (acfg);
9116 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9124 if (acfg->aot_opts.asm_only) {
9125 if (acfg->aot_opts.outfile) {
9126 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9127 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9129 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9130 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9132 if (acfg->llvm_separate) {
9133 g_assert (acfg->aot_opts.llvm_outfile);
9134 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9137 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9138 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9139 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9140 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9143 res = emit_llvm_file (acfg);
9149 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9150 if (acfg->aot_opts.outfile)
9151 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9153 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9156 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9157 * it might be in another file system so the rename () won't work.
9159 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9161 acfg->fp = fopen (tmp_outfile_name, "w");
9163 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9167 acfg->w = img_writer_create (acfg->fp, TRUE);
9168 acfg->use_bin_writer = TRUE;
9170 if (acfg->llvm && !acfg->llvm_separate) {
9171 /* Append to the .s file created by llvm */
9172 /* FIXME: Use multiple files instead */
9173 acfg->fp = fopen (acfg->tmpfname, "a+");
9175 if (acfg->aot_opts.asm_only) {
9176 if (acfg->aot_opts.outfile)
9177 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9179 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9180 acfg->fp = fopen (acfg->tmpfname, "w+");
9182 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9183 acfg->fp = fdopen (i, "w+");
9186 if (acfg->fp == 0) {
9187 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9190 acfg->w = img_writer_create (acfg->fp, FALSE);
9192 tmp_outfile_name = NULL;
9193 outfile_name = NULL;
9196 /* Compute symbols for methods */
9197 for (i = 0; i < acfg->nmethods; ++i) {
9198 if (acfg->cfgs [i]) {
9199 MonoCompile *cfg = acfg->cfgs [i];
9200 int method_index = get_method_index (acfg, cfg->orig_method);
9202 if (COMPILE_LLVM (cfg))
9203 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9204 else if (acfg->global_symbols || acfg->llvm_separate)
9205 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9207 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9211 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9213 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9214 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9217 //acfg->gas_line_numbers = TRUE;
9220 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9221 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9222 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9225 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9228 img_writer_emit_start (acfg->w);
9231 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9233 if (acfg->thumb_mixed) {
9236 * This global symbol marks the end of THUMB code, and the beginning of ARM
9237 * code generated by our JIT.
9239 sprintf (symbol, "thumb_end");
9240 emit_section_change (acfg, ".text", 0);
9241 emit_alignment_code (acfg, 8);
9242 emit_label (acfg, symbol);
9243 emit_zero_bytes (acfg, 16);
9245 fprintf (acfg->fp, ".arm\n");
9252 emit_extra_methods (acfg);
9254 emit_trampolines (acfg);
9256 emit_class_name_table (acfg);
9258 emit_got_info (acfg, FALSE);
9260 emit_got_info (acfg, TRUE);
9262 emit_exception_info (acfg);
9264 emit_unwind_info (acfg);
9266 emit_class_info (acfg);
9270 emit_image_table (acfg);
9274 emit_file_info (acfg);
9278 emit_objc_selectors (acfg);
9280 emit_globals (acfg);
9282 emit_autoreg (acfg);
9285 emit_dwarf_info (acfg);
9286 mono_dwarf_writer_close (acfg->dwarf);
9289 emit_mem_end (acfg);
9291 if (acfg->need_pt_gnu_stack) {
9292 /* This is required so the .so doesn't have an executable stack */
9293 /* The bin writer already emits this */
9294 if (!acfg->use_bin_writer)
9295 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9300 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9303 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9305 strcpy (llvm_stats_msg, "");
9307 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;
9309 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",
9310 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9311 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9312 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9313 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9314 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9315 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9316 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9317 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9318 (int)(acfg->got_offset * sizeof (gpointer)));
9319 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9320 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9322 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9323 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9324 if (acfg->stats.genericcount)
9325 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9326 if (acfg->stats.abscount)
9327 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9328 if (acfg->stats.lmfcount)
9329 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9330 if (acfg->stats.ocount)
9331 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9334 res = img_writer_emit_writeout (acfg->w);
9339 if (acfg->use_bin_writer) {
9340 int err = rename (tmp_outfile_name, outfile_name);
9343 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9347 res = compile_asm (acfg);
9354 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9356 if (acfg->aot_opts.stats) {
9359 aot_printf (acfg, "GOT slot distribution:\n");
9360 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9361 if (acfg->stats.got_slot_types [i])
9362 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]);
9365 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);
9377 mono_aot_readonly_field_override (MonoClassField *field)
9383 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)