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);
1497 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1498 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1503 /* Load mscorlib got address */
1504 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1505 /* Push trampoline argument */
1506 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1507 /* Load generic trampoline address */
1508 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1509 /* Branch to generic trampoline */
1510 x86_jump_reg (code, X86_ECX);
1512 #ifdef __native_client_codegen__
1514 /* emit nops to next 32 byte alignment */
1515 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1516 while (code < (buf + a)) x86_nop(code);
1519 emit_bytes (acfg, buf, code - buf);
1521 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1522 g_assert (code - buf == *tramp_size);
1524 g_assert_not_reached ();
1529 * arch_emit_unbox_trampoline:
1531 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1532 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1535 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1537 #if defined(TARGET_AMD64)
1542 this_reg = mono_arch_get_this_arg_reg (NULL);
1544 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1546 emit_bytes (acfg, buf, code - buf);
1548 if (acfg->llvm_separate) {
1549 emit_unset_mode (acfg);
1550 fprintf (acfg->fp, "jmp %s\n", call_target);
1552 emit_byte (acfg, '\xe9');
1553 emit_symbol_diff (acfg, call_target, ".", -4);
1555 #elif defined(TARGET_X86)
1562 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1564 emit_bytes (acfg, buf, code - buf);
1567 emit_byte (acfg, '\xe9');
1568 emit_symbol_diff (acfg, call_target, ".", -4);
1569 #elif defined(TARGET_ARM)
1573 if (acfg->thumb_mixed && cfg->compile_llvm) {
1574 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1575 fprintf (acfg->fp, "b %s\n", call_target);
1576 fprintf (acfg->fp, ".arm\n");
1577 fprintf (acfg->fp, ".align 2\n");
1583 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1585 emit_bytes (acfg, buf, code - buf);
1586 /* jump to method */
1587 if (acfg->use_bin_writer) {
1594 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1595 emit_bytes (acfg, buf, 4);
1597 if (acfg->thumb_mixed && cfg->compile_llvm)
1598 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1600 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1602 #elif defined(TARGET_ARM64)
1603 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1604 #elif defined(TARGET_POWERPC)
1607 g_assert (!acfg->use_bin_writer);
1609 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1610 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1612 g_assert_not_reached ();
1617 * arch_emit_static_rgctx_trampoline:
1619 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1620 * two GOT slots which contain the rgctx argument, and the method to jump to.
1621 * TRAMP_SIZE is set to the size of the emitted trampoline.
1622 * These kinds of trampolines cannot be enumerated statically, since there could
1623 * be one trampoline per method instantiation, so we emit the same code for all
1624 * trampolines, and parameterize them using two GOT slots.
1627 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1629 #if defined(TARGET_AMD64)
1630 #if defined(__default_codegen__)
1631 /* This should be exactly 13 bytes long */
1634 if (acfg->llvm_separate) {
1635 emit_unset_mode (acfg);
1636 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1637 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1639 /* mov <OFFSET>(%rip), %r10 */
1640 emit_byte (acfg, '\x4d');
1641 emit_byte (acfg, '\x8b');
1642 emit_byte (acfg, '\x15');
1643 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1645 /* jmp *<offset>(%rip) */
1646 emit_byte (acfg, '\xff');
1647 emit_byte (acfg, '\x25');
1648 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1650 #elif defined(__native_client_codegen__)
1652 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1653 guint8 *code = buf_aligned;
1655 /* mov <OFFSET>(%rip), %r10d */
1656 emit_byte (acfg, '\x45');
1657 emit_byte (acfg, '\x8b');
1658 emit_byte (acfg, '\x15');
1659 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1661 /* mov <OFFSET>(%rip), %r11d */
1662 emit_byte (acfg, '\x45');
1663 emit_byte (acfg, '\x8b');
1664 emit_byte (acfg, '\x1d');
1665 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1668 amd64_jump_reg (code, AMD64_R11);
1669 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1671 emit_alignment (acfg, kNaClAlignment);
1672 *tramp_size = kNaClAlignment;
1673 #endif /*__native_client_codegen__*/
1675 #elif defined(TARGET_ARM)
1679 /* This should be exactly 24 bytes long */
1682 /* Load rgctx value */
1683 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1684 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1685 /* Load branch addr + branch */
1686 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1687 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1689 g_assert (code - buf == 16);
1692 emit_bytes (acfg, buf, code - buf);
1693 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1694 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1695 #elif defined(TARGET_ARM64)
1696 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1697 #elif defined(TARGET_POWERPC)
1704 g_assert (!acfg->use_bin_writer);
1707 * PPC has no ip relative addressing, so we need to compute the address
1708 * of the mscorlib got. That is slow and complex, so instead, we store it
1709 * in the second got slot of every aot image. The caller already computed
1710 * the address of its got and placed it into r30.
1712 emit_unset_mode (acfg);
1713 /* Load mscorlib got address */
1714 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1716 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1717 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1718 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1719 /* Load target address */
1720 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1721 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1722 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1723 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1724 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1725 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1727 fprintf (acfg->fp, "mtctr 11\n");
1728 /* Branch to the target address */
1729 fprintf (acfg->fp, "bctr\n");
1731 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1732 *tramp_size = 11 * 4;
1734 *tramp_size = 9 * 4;
1737 #elif defined(TARGET_X86)
1741 /* Similar to the PPC code above */
1743 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1746 /* Load mscorlib got address */
1747 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1749 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1750 /* Branch to the target address */
1751 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1753 #ifdef __native_client_codegen__
1755 /* emit nops to next 32 byte alignment */
1756 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1757 while (code < (buf + a)) x86_nop(code);
1761 emit_bytes (acfg, buf, code - buf);
1763 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1764 g_assert (code - buf == *tramp_size);
1766 g_assert_not_reached ();
1771 * arch_emit_imt_thunk:
1773 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1774 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1775 * key is the IMT key, and ptr holds the address of a memory location holding
1776 * the address to branch to if the IMT arg matches the key. The array is
1777 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1779 * TRAMP_SIZE is set to the size of the emitted trampoline.
1782 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1784 #if defined(TARGET_AMD64)
1786 #if defined(__native_client_codegen__)
1789 guint8 *labels [16];
1791 guint8 *mov_buf_ptr = mov_buf;
1793 const int kSizeOfMove = 7;
1794 #if defined(__default_codegen__)
1795 code = buf = g_malloc (256);
1796 #elif defined(__native_client_codegen__)
1797 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1798 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1799 /* The RIP relative move below is emitted first */
1804 /* FIXME: Optimize this, i.e. use binary search etc. */
1805 /* Maybe move the body into a separate function (slower, but much smaller) */
1807 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1809 if (acfg->llvm_separate) {
1810 emit_unset_mode (acfg);
1811 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1815 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1817 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1820 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1822 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1825 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1826 amd64_jump_code (code, labels [0]);
1829 mono_amd64_patch (labels [2], code);
1830 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1831 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1834 mono_amd64_patch (labels [1], code);
1835 /* Load fail tramp */
1836 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1837 /* Check if there is a fail tramp */
1838 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1840 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1841 /* Jump to fail tramp */
1842 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1845 mono_amd64_patch (labels [3], code);
1846 x86_breakpoint (code);
1848 if (!acfg->llvm_separate) {
1849 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1850 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1851 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1852 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1853 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1854 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1856 emit_bytes (acfg, buf, code - buf);
1858 *tramp_size = code - buf + kSizeOfMove;
1859 #if defined(__native_client_codegen__)
1860 /* The tramp will be padded to the next kNaClAlignment bundle. */
1861 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1864 #if defined(__default_codegen__)
1866 #elif defined(__native_client_codegen__)
1870 #elif defined(TARGET_X86)
1872 #ifdef __native_client_codegen__
1875 guint8 *labels [16];
1877 #if defined(__default_codegen__)
1878 code = buf = g_malloc (256);
1879 #elif defined(__native_client_codegen__)
1880 buf_alloc = g_malloc (256 + kNaClAlignment);
1881 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1884 /* Allocate a temporary stack slot */
1885 x86_push_reg (code, X86_EAX);
1887 x86_push_reg (code, X86_EAX);
1889 /* Load mscorlib got address */
1890 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1892 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1895 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1897 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1900 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1902 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1905 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1906 x86_jump_code (code, labels [0]);
1909 mono_x86_patch (labels [2], code);
1910 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1911 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1912 /* Save the target address to the temporary stack location */
1913 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1915 x86_pop_reg (code, X86_EAX);
1916 /* Jump to the target address */
1920 mono_x86_patch (labels [1], code);
1921 /* Load fail tramp */
1922 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1923 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1925 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1926 /* Jump to fail tramp */
1927 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1928 x86_pop_reg (code, X86_EAX);
1932 mono_x86_patch (labels [3], code);
1933 x86_breakpoint (code);
1935 #ifdef __native_client_codegen__
1937 /* emit nops to next 32 byte alignment */
1938 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1939 while (code < (buf + a)) x86_nop(code);
1942 emit_bytes (acfg, buf, code - buf);
1944 *tramp_size = code - buf;
1946 #if defined(__default_codegen__)
1948 #elif defined(__native_client_codegen__)
1952 #elif defined(TARGET_ARM)
1954 guint8 *code, *code2, *labels [16];
1958 /* The IMT method is in v5 */
1960 /* Need at least two free registers, plus a slot for storing the pc */
1961 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1963 /* Load the parameter from the GOT */
1964 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1965 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1968 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1969 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1971 ARM_B_COND (code, ARMCOND_EQ, 0);
1973 /* End-of-loop check */
1974 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1976 ARM_B_COND (code, ARMCOND_EQ, 0);
1979 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1982 arm_patch (labels [4], labels [1]);
1985 arm_patch (labels [2], code);
1986 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1987 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1988 /* Save it to the third stack slot */
1989 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1990 /* Restore the registers and branch */
1991 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1994 arm_patch (labels [3], code);
1995 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1996 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1997 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2001 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2003 emit_bytes (acfg, buf, code - buf);
2004 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2006 *tramp_size = code - buf + 4;
2007 #elif defined(TARGET_ARM64)
2008 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2009 #elif defined(TARGET_POWERPC)
2011 guint8 *code, *labels [16];
2015 /* Load the mscorlib got address */
2016 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2017 /* Load the parameter from the GOT */
2018 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2019 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2021 /* Load and check key */
2023 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2024 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2026 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2028 /* End-of-loop check */
2029 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2031 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2034 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2037 mono_ppc_patch (labels [4], labels [1]);
2040 mono_ppc_patch (labels [2], code);
2041 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2042 /* r12 now contains the value of the vtable slot */
2043 /* this is not a function descriptor on ppc64 */
2044 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2045 ppc_mtctr (code, ppc_r12);
2046 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2049 mono_ppc_patch (labels [3], code);
2053 *tramp_size = code - buf;
2055 emit_bytes (acfg, buf, code - buf);
2057 g_assert_not_reached ();
2062 * arch_emit_gsharedvt_arg_trampoline:
2064 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2065 * two GOT slots which contain the argument, and the code to jump to.
2066 * TRAMP_SIZE is set to the size of the emitted trampoline.
2067 * These kinds of trampolines cannot be enumerated statically, since there could
2068 * be one trampoline per method instantiation, so we emit the same code for all
2069 * trampolines, and parameterize them using two GOT slots.
2072 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2074 #if defined(TARGET_X86)
2078 /* Similar to the PPC code above */
2080 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2083 /* Load mscorlib got address */
2084 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2086 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2087 /* Branch to the target address */
2088 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2090 #ifdef __native_client_codegen__
2092 /* emit nops to next 32 byte alignment */
2093 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2094 while (code < (buf + a)) x86_nop(code);
2098 emit_bytes (acfg, buf, code - buf);
2100 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2101 g_assert (code - buf == *tramp_size);
2102 #elif defined(TARGET_ARM)
2106 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2107 /* Similar to arch_emit_specific_trampoline () */
2110 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2111 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2112 /* Load the arg value from the GOT */
2113 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2114 /* Load the addr from the GOT */
2115 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2117 ARM_BX (code, ARMREG_R1);
2119 g_assert (code - buf == 20);
2122 emit_bytes (acfg, buf, code - buf);
2123 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2124 #elif defined(TARGET_ARM64)
2125 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2127 g_assert_not_reached ();
2132 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2134 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2135 /* Based on code generated by gcc */
2136 emit_unset_mode (acfg);
2139 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2140 ".section .ctors,\"aw\",@progbits\n"
2144 ".section .opd,\"aw\"\n"
2147 ".long .%s,.TOC.@tocbase32\n"
2150 ".type .%s,@function\n"
2152 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2154 ".section .ctors,\"aw\",@progbits\n"
2158 ".section .opd,\"aw\"\n"
2161 ".long .%1$s,.TOC.@tocbase32\n"
2162 ".size %1$s,.-%1$s\n"
2164 ".type .%1$s,@function\n"
2166 ".%1$s:\n", symbol);
2177 "lis 3, .Lglobals@h\n"
2178 "ori 3, 3, .Lglobals@l\n"
2179 "bl .mono_aot_register_module\n"
2187 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2189 ".size .%s,.-.%s\n", symbol, symbol);
2192 ".size .%1$s,.-.%1$s\n", symbol);
2198 /* END OF ARCH SPECIFIC CODE */
2201 mono_get_field_token (MonoClassField *field)
2203 MonoClass *klass = field->parent;
2206 for (i = 0; i < klass->field.count; ++i) {
2207 if (field == &klass->fields [i])
2208 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2211 g_assert_not_reached ();
2216 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2220 //printf ("ENCODE: %d 0x%x.\n", value, value);
2223 * Same encoding as the one used in the metadata, extended to handle values
2224 * greater than 0x1fffffff.
2226 if ((value >= 0) && (value <= 127))
2228 else if ((value >= 0) && (value <= 16383)) {
2229 p [0] = 0x80 | (value >> 8);
2230 p [1] = value & 0xff;
2232 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2233 p [0] = (value >> 24) | 0xc0;
2234 p [1] = (value >> 16) & 0xff;
2235 p [2] = (value >> 8) & 0xff;
2236 p [3] = value & 0xff;
2241 p [1] = (value >> 24) & 0xff;
2242 p [2] = (value >> 16) & 0xff;
2243 p [3] = (value >> 8) & 0xff;
2244 p [4] = value & 0xff;
2252 stream_init (MonoDynamicStream *sh)
2255 sh->alloc_size = 4096;
2256 sh->data = g_malloc (4096);
2258 /* So offsets are > 0 */
2264 make_room_in_stream (MonoDynamicStream *stream, int size)
2266 if (size <= stream->alloc_size)
2269 while (stream->alloc_size <= size) {
2270 if (stream->alloc_size < 4096)
2271 stream->alloc_size = 4096;
2273 stream->alloc_size *= 2;
2276 stream->data = g_realloc (stream->data, stream->alloc_size);
2280 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2284 make_room_in_stream (stream, stream->index + len);
2285 memcpy (stream->data + stream->index, data, len);
2286 idx = stream->index;
2287 stream->index += len;
2294 * Add data to the binary blob inside the aot image. Returns the offset inside the
2295 * blob where the data was stored.
2298 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2300 if (acfg->blob.alloc_size == 0)
2301 stream_init (&acfg->blob);
2303 return add_stream_data (&acfg->blob, (char*)data, data_len);
2307 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2312 if (acfg->blob.alloc_size == 0)
2313 stream_init (&acfg->blob);
2315 count = acfg->blob.index % align;
2317 /* we assume the stream data will be aligned */
2319 add_stream_data (&acfg->blob, buf, 4 - count);
2321 return add_stream_data (&acfg->blob, (char*)data, data_len);
2325 * emit_offset_table:
2327 * Emit a table of increasing offsets in a compact form using differential encoding.
2328 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2329 * group size, the more compact the table becomes, but the slower it becomes to compute
2330 * a given entry. Returns the size of the table.
2333 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2335 gint32 current_offset;
2336 int i, buf_size, ngroups, index_entry_size;
2338 guint32 *index_offsets;
2340 ngroups = (noffsets + (group_size - 1)) / group_size;
2342 index_offsets = g_new0 (guint32, ngroups);
2344 buf_size = noffsets * 4;
2345 p = buf = g_malloc0 (buf_size);
2348 for (i = 0; i < noffsets; ++i) {
2349 //printf ("D: %d -> %d\n", i, offsets [i]);
2350 if ((i % group_size) == 0) {
2351 index_offsets [i / group_size] = p - buf;
2352 /* Emit the full value for these entries */
2353 encode_value (offsets [i], p, &p);
2355 /* The offsets are allowed to be non-increasing */
2356 //g_assert (offsets [i] >= current_offset);
2357 encode_value (offsets [i] - current_offset, p, &p);
2359 current_offset = offsets [i];
2362 if (ngroups && index_offsets [ngroups - 1] < 65000)
2363 index_entry_size = 2;
2365 index_entry_size = 4;
2367 /* Emit the header */
2368 emit_int32 (acfg, noffsets);
2369 emit_int32 (acfg, group_size);
2370 emit_int32 (acfg, ngroups);
2371 emit_int32 (acfg, index_entry_size);
2373 /* Emit the index */
2374 for (i = 0; i < ngroups; ++i) {
2375 if (index_entry_size == 2)
2376 emit_int16 (acfg, index_offsets [i]);
2378 emit_int32 (acfg, index_offsets [i]);
2382 emit_bytes (acfg, buf, p - buf);
2384 return (int)(p - buf) + (ngroups * 4);
2388 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2392 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2396 index = g_hash_table_size (cfg->image_hash);
2397 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2398 g_ptr_array_add (cfg->image_table, image);
2404 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2407 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2409 /* FIXME: Search referenced images as well */
2410 if (!acfg->typespec_classes) {
2411 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2412 for (i = 0; i < len; ++i) {
2414 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2415 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2418 for (i = 0; i < len; ++i) {
2419 if (acfg->typespec_classes [i] == klass)
2424 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2430 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2433 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2436 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2439 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2442 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2447 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2451 if (klass->generic_class) {
2453 g_assert (klass->type_token);
2455 /* Find a typespec for a class if possible */
2456 token = find_typespec_for_class (acfg, klass);
2458 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2459 encode_value (token, p, &p);
2461 MonoClass *gclass = klass->generic_class->container_class;
2462 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2463 static int count = 0;
2466 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2467 encode_klass_ref (acfg, gclass, p, &p);
2468 encode_ginst (acfg, inst, p, &p);
2472 } else if (klass->type_token) {
2473 int iindex = get_image_index (acfg, klass->image);
2475 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2477 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2478 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2480 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2481 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2482 encode_value (get_image_index (acfg, klass->image), p, &p);
2484 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2485 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2486 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2488 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2489 encode_value (klass->byval_arg.type, p, &p);
2490 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2492 encode_value (container ? 1 : 0, p, &p);
2494 encode_value (container->is_method, p, &p);
2495 g_assert (par->serial == 0);
2496 if (container->is_method)
2497 encode_method_ref (acfg, container->owner.method, p, &p);
2499 encode_klass_ref (acfg, container->owner.klass, p, &p);
2501 encode_value (par->serial, p, &p);
2503 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2504 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2505 encode_type (acfg, &klass->byval_arg, p, &p);
2508 g_assert (klass->rank > 0);
2509 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2510 encode_value (klass->rank, p, &p);
2511 encode_klass_ref (acfg, klass->element_class, p, &p);
2519 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2520 * standard metadata encoding.
2523 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2525 gboolean shared = FALSE;
2528 * The encoding of generic instances is large so emit them only once.
2530 if (klass->generic_class) {
2532 g_assert (klass->type_token);
2534 /* Find a typespec for a class if possible */
2535 token = find_typespec_for_class (acfg, klass);
2538 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2543 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2547 buf2 = g_malloc (1024);
2550 encode_klass_ref_inner (acfg, klass, p, &p);
2551 g_assert (p - buf2 < 1024);
2553 offset = add_to_blob (acfg, buf2, p - buf2);
2556 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2562 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2563 encode_value (offset, p, &p);
2568 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2572 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2574 guint32 token = mono_get_field_token (field);
2577 encode_klass_ref (cfg, field->parent, p, &p);
2578 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2579 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2584 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2589 encode_value (inst->type_argc, p, &p);
2590 for (i = 0; i < inst->type_argc; ++i)
2591 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2596 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2599 MonoGenericInst *inst;
2601 inst = context->class_inst;
2603 g_assert (inst->type_argc);
2604 encode_ginst (acfg, inst, p, &p);
2606 encode_value (0, p, &p);
2608 inst = context->method_inst;
2610 g_assert (inst->type_argc);
2611 encode_ginst (acfg, inst, p, &p);
2613 encode_value (0, p, &p);
2619 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2623 g_assert (t->num_mods == 0);
2624 /* t->attrs can be ignored */
2625 //g_assert (t->attrs == 0);
2628 *p = MONO_TYPE_PINNED;
2632 *p = MONO_TYPE_BYREF;
2640 case MONO_TYPE_VOID:
2641 case MONO_TYPE_BOOLEAN:
2642 case MONO_TYPE_CHAR:
2655 case MONO_TYPE_STRING:
2656 case MONO_TYPE_OBJECT:
2657 case MONO_TYPE_TYPEDBYREF:
2659 case MONO_TYPE_VALUETYPE:
2660 case MONO_TYPE_CLASS:
2661 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2663 case MONO_TYPE_SZARRAY:
2664 encode_klass_ref (acfg, t->data.klass, p, &p);
2667 encode_type (acfg, t->data.type, p, &p);
2669 case MONO_TYPE_GENERICINST: {
2670 MonoClass *gclass = t->data.generic_class->container_class;
2671 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2673 encode_klass_ref (acfg, gclass, p, &p);
2674 encode_ginst (acfg, inst, p, &p);
2677 case MONO_TYPE_ARRAY: {
2678 MonoArrayType *array = t->data.array;
2681 encode_klass_ref (acfg, array->eklass, p, &p);
2682 encode_value (array->rank, p, &p);
2683 encode_value (array->numsizes, p, &p);
2684 for (i = 0; i < array->numsizes; ++i)
2685 encode_value (array->sizes [i], p, &p);
2686 encode_value (array->numlobounds, p, &p);
2687 for (i = 0; i < array->numlobounds; ++i)
2688 encode_value (array->lobounds [i], p, &p);
2692 case MONO_TYPE_MVAR:
2693 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2696 g_assert_not_reached ();
2703 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2709 /* Similar to the metadata encoding */
2710 if (sig->generic_param_count)
2714 if (sig->explicit_this)
2716 flags |= (sig->call_convention & 0x0F);
2720 if (sig->generic_param_count)
2721 encode_value (sig->generic_param_count, p, &p);
2722 encode_value (sig->param_count, p, &p);
2724 encode_type (acfg, sig->ret, p, &p);
2725 for (i = 0; i < sig->param_count; ++i) {
2726 if (sig->sentinelpos == i) {
2727 *p = MONO_TYPE_SENTINEL;
2730 encode_type (acfg, sig->params [i], p, &p);
2736 #define MAX_IMAGE_INDEX 250
2739 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2741 guint32 image_index = get_image_index (acfg, method->klass->image);
2742 guint32 token = method->token;
2743 MonoJumpInfoToken *ji;
2747 * The encoding for most methods is as follows:
2748 * - image index encoded as a leb128
2749 * - token index encoded as a leb128
2750 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2751 * types of method encodings.
2754 /* Mark methods which can't use aot trampolines because they need the further
2755 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2757 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2758 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2759 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2761 if (method->wrapper_type) {
2762 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2764 encode_value (method->wrapper_type, p, &p);
2766 switch (method->wrapper_type) {
2767 case MONO_WRAPPER_REMOTING_INVOKE:
2768 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2769 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2772 m = mono_marshal_method_from_wrapper (method);
2774 encode_method_ref (acfg, m, p, &p);
2777 case MONO_WRAPPER_PROXY_ISINST:
2778 case MONO_WRAPPER_LDFLD:
2779 case MONO_WRAPPER_LDFLDA:
2780 case MONO_WRAPPER_STFLD:
2781 case MONO_WRAPPER_ISINST: {
2782 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2785 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2788 case MONO_WRAPPER_LDFLD_REMOTE:
2789 case MONO_WRAPPER_STFLD_REMOTE:
2791 case MONO_WRAPPER_ALLOC: {
2792 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2794 /* The GC name is saved once in MonoAotFileInfo */
2795 g_assert (info->alloc_type != -1);
2796 encode_value (info->alloc_type, p, &p);
2799 case MONO_WRAPPER_WRITE_BARRIER:
2801 case MONO_WRAPPER_STELEMREF: {
2802 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2805 encode_value (info->subtype, p, &p);
2806 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2807 encode_value (info->d.virtual_stelemref.kind, p, &p);
2810 case MONO_WRAPPER_UNKNOWN: {
2811 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2814 encode_value (info->subtype, p, &p);
2815 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2816 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2817 encode_klass_ref (acfg, method->klass, p, &p);
2818 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2819 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2820 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2821 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2824 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2825 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2828 encode_value (info->subtype, p, &p);
2829 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2830 strcpy ((char*)p, method->name);
2831 p += strlen (method->name) + 1;
2832 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2833 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2835 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2836 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2840 case MONO_WRAPPER_SYNCHRONIZED: {
2843 m = mono_marshal_method_from_wrapper (method);
2845 g_assert (m != method);
2846 encode_method_ref (acfg, m, p, &p);
2849 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2850 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2853 encode_value (info->subtype, p, &p);
2855 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2856 encode_value (info->d.element_addr.rank, p, &p);
2857 encode_value (info->d.element_addr.elem_size, p, &p);
2858 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2859 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2861 g_assert_not_reached ();
2865 case MONO_WRAPPER_CASTCLASS: {
2866 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2869 encode_value (info->subtype, p, &p);
2872 case MONO_WRAPPER_RUNTIME_INVOKE: {
2873 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2876 encode_value (info->subtype, p, &p);
2877 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2878 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2879 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2880 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2883 case MONO_WRAPPER_DELEGATE_INVOKE:
2884 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2885 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2886 if (method->is_inflated) {
2887 /* These wrappers are identified by their class */
2888 encode_value (1, p, &p);
2889 encode_klass_ref (acfg, method->klass, p, &p);
2891 MonoMethodSignature *sig = mono_method_signature (method);
2892 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2894 encode_value (0, p, &p);
2895 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2896 encode_value (info ? info->subtype : 0, p, &p);
2897 encode_signature (acfg, sig, p, &p);
2901 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2902 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2905 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2906 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2910 g_assert_not_reached ();
2912 } else if (mono_method_signature (method)->is_inflated) {
2914 * This is a generic method, find the original token which referenced it and
2916 * Obtain the token from information recorded by the JIT.
2918 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2920 image_index = get_image_index (acfg, ji->image);
2921 g_assert (image_index < MAX_IMAGE_INDEX);
2924 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2925 encode_value (image_index, p, &p);
2926 encode_value (token, p, &p);
2928 MonoMethod *declaring;
2929 MonoGenericContext *context = mono_method_get_context (method);
2931 g_assert (method->is_inflated);
2932 declaring = ((MonoMethodInflated*)method)->declaring;
2935 * This might be a non-generic method of a generic instance, which
2936 * doesn't have a token since the reference is generated by the JIT
2937 * like Nullable:Box/Unbox, or by generic sharing.
2939 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2940 /* Encode the klass */
2941 encode_klass_ref (acfg, method->klass, p, &p);
2942 /* Encode the method */
2943 image_index = get_image_index (acfg, method->klass->image);
2944 g_assert (image_index < MAX_IMAGE_INDEX);
2945 g_assert (declaring->token);
2946 token = declaring->token;
2947 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2948 encode_value (image_index, p, &p);
2949 encode_value (token, p, &p);
2950 encode_generic_context (acfg, context, p, &p);
2952 } else if (token == 0) {
2953 /* This might be a method of a constructed type like int[,].Set */
2954 /* Obtain the token from information recorded by the JIT */
2955 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2957 image_index = get_image_index (acfg, ji->image);
2958 g_assert (image_index < MAX_IMAGE_INDEX);
2961 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2962 encode_value (image_index, p, &p);
2963 encode_value (token, p, &p);
2966 g_assert (method->klass->rank);
2968 /* Encode directly */
2969 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2970 encode_klass_ref (acfg, method->klass, p, &p);
2971 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2972 encode_value (0, p, &p);
2973 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2974 encode_value (1, p, &p);
2975 else if (!strcmp (method->name, "Get"))
2976 encode_value (2, p, &p);
2977 else if (!strcmp (method->name, "Address"))
2978 encode_value (3, p, &p);
2979 else if (!strcmp (method->name, "Set"))
2980 encode_value (4, p, &p);
2982 g_assert_not_reached ();
2985 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2987 if (image_index >= MONO_AOT_METHODREF_MIN) {
2988 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2989 encode_value (image_index, p, &p);
2990 encode_value (mono_metadata_token_index (token), p, &p);
2992 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2999 compare_patches (gconstpointer a, gconstpointer b)
3003 i = (*(MonoJumpInfo**)a)->ip.i;
3004 j = (*(MonoJumpInfo**)b)->ip.i;
3015 static G_GNUC_UNUSED char*
3016 patch_to_string (MonoJumpInfo *patch_info)
3020 str = g_string_new ("");
3022 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3024 switch (patch_info->type) {
3025 case MONO_PATCH_INFO_VTABLE:
3026 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3031 g_string_append_printf (str, ")");
3032 return g_string_free (str, FALSE);
3038 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3041 static inline gboolean
3042 is_plt_patch (MonoJumpInfo *patch_info)
3044 switch (patch_info->type) {
3045 case MONO_PATCH_INFO_METHOD:
3046 case MONO_PATCH_INFO_INTERNAL_METHOD:
3047 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3048 case MONO_PATCH_INFO_ICALL_ADDR:
3049 case MONO_PATCH_INFO_CLASS_INIT:
3050 case MONO_PATCH_INFO_RGCTX_FETCH:
3051 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3052 case MONO_PATCH_INFO_MONITOR_ENTER:
3053 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3054 case MONO_PATCH_INFO_MONITOR_EXIT:
3055 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3065 * Return the symbol identifying the plt entry PLT_OFFSET.
3068 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3072 * The Apple linker reorganizes object files, so it doesn't like branches to local
3073 * labels, since those have no relocations.
3075 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3077 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3084 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3086 static MonoPltEntry*
3087 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3091 if (!is_plt_patch (patch_info))
3094 if (!acfg->patch_to_plt_entry [patch_info->type])
3095 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3096 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3098 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3100 * Allocate a separate PLT slot for each such patch, since some plt
3101 * entries will refer to the method itself, and some will refer to the
3108 MonoJumpInfo *new_ji;
3110 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3112 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3113 res->plt_offset = acfg->plt_offset;
3115 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3116 if (acfg->aot_opts.write_symbols)
3117 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3119 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3121 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3123 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3125 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3127 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3128 //mono_print_ji (patch_info); printf ("\n");
3129 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3131 acfg->plt_offset ++;
3140 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3141 * JI could be found if it exists, otherwise allocates a new one.
3144 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3147 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3149 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3151 return got_offset - 1;
3154 got_offset = acfg->llvm_got_offset;
3155 acfg->llvm_got_offset ++;
3157 got_offset = acfg->got_offset;
3158 acfg->got_offset ++;
3161 acfg->stats.got_slots ++;
3162 acfg->stats.got_slot_types [ji->type] ++;
3164 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3165 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3166 g_ptr_array_add (info->got_patches, ji);
3171 /* Add a method to the list of methods which need to be emitted */
3173 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3176 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3177 g_ptr_array_add (acfg->methods, method);
3178 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3179 acfg->nmethods = acfg->methods->len + 1;
3182 if (method->wrapper_type || extra)
3183 g_ptr_array_add (acfg->extra_methods, method);
3187 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3189 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3197 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3201 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3205 index = acfg->method_index;
3206 add_method_with_index (acfg, method, index, extra);
3208 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3210 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3212 acfg->method_index ++;
3218 add_method (MonoAotCompile *acfg, MonoMethod *method)
3220 return add_method_full (acfg, method, FALSE, 0);
3224 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3226 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3227 method = mini_get_shared_method (method);
3229 if (acfg->aot_opts.log_generics)
3230 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3232 add_method_full (acfg, method, TRUE, depth);
3236 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3238 add_extra_method_with_depth (acfg, method, 0);
3242 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3244 MonoAotCompile *acfg = user_data;
3245 MonoJitICallInfo *callinfo = value;
3246 MonoMethod *wrapper;
3252 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3253 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3256 add_method (acfg, wrapper);
3260 get_runtime_invoke_sig (MonoMethodSignature *sig)
3262 MonoMethodBuilder *mb;
3265 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3266 m = mono_mb_create_method (mb, sig, 16);
3267 return mono_marshal_get_runtime_invoke (m, FALSE);
3271 can_marshal_struct (MonoClass *klass)
3273 MonoClassField *field;
3274 gboolean can_marshal = TRUE;
3275 gpointer iter = NULL;
3276 MonoMarshalType *info;
3279 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3282 info = mono_marshal_load_type_info (klass);
3284 /* Only allow a few field types to avoid asserts in the marshalling code */
3285 while ((field = mono_class_get_fields (klass, &iter))) {
3286 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3289 switch (field->type->type) {
3294 case MONO_TYPE_BOOLEAN:
3297 case MONO_TYPE_CHAR:
3305 case MONO_TYPE_STRING:
3307 case MONO_TYPE_VALUETYPE:
3308 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3309 can_marshal = FALSE;
3311 case MONO_TYPE_SZARRAY: {
3312 gboolean has_mspec = FALSE;
3315 for (i = 0; i < info->num_fields; ++i) {
3316 if (info->fields [i].field == field && info->fields [i].mspec)
3321 can_marshal = FALSE;
3325 can_marshal = FALSE;
3331 /* Its hard to compute whenever these can be marshalled or not */
3332 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3339 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3341 /* Create a vtype instantiation */
3342 MonoGenericContext shared_context;
3344 MonoGenericInst *inst;
3345 MonoGenericContainer *container;
3346 MonoClass **constraints;
3349 memset (ctx, 0, sizeof (MonoGenericContext));
3351 if (method->klass->generic_container) {
3352 shared_context = method->klass->generic_container->context;
3353 inst = shared_context.class_inst;
3355 args = g_new0 (MonoType*, inst->type_argc);
3356 for (i = 0; i < inst->type_argc; ++i) {
3357 args [i] = &mono_defaults.int_class->byval_arg;
3359 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3361 if (method->is_generic) {
3362 container = mono_method_get_generic_container (method);
3363 shared_context = container->context;
3364 inst = shared_context.method_inst;
3366 args = g_new0 (MonoType*, inst->type_argc);
3367 for (i = 0; i < container->type_argc; ++i) {
3368 MonoGenericParamInfo *info = &container->type_params [i].info;
3369 gboolean ref_only = FALSE;
3371 if (info && info->constraints) {
3372 constraints = info->constraints;
3374 while (*constraints) {
3375 MonoClass *cklass = *constraints;
3376 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3377 /* Inflaring the method with our vtype would not be valid */
3384 args [i] = &mono_defaults.object_class->byval_arg;
3386 args [i] = &mono_defaults.int_class->byval_arg;
3388 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3393 add_wrappers (MonoAotCompile *acfg)
3395 MonoMethod *method, *m;
3397 MonoMethodSignature *sig, *csig;
3401 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3402 * so there is only one wrapper of a given type, or inlining their contents into their
3405 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3407 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3408 gboolean skip = FALSE;
3410 method = mono_get_method (acfg->image, token, NULL);
3412 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3413 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3414 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3417 /* Skip methods which can not be handled by get_runtime_invoke () */
3418 sig = mono_method_signature (method);
3421 if ((sig->ret->type == MONO_TYPE_PTR) ||
3422 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3424 if (mono_class_is_open_constructed_type (sig->ret))
3427 for (j = 0; j < sig->param_count; j++) {
3428 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3430 if (mono_class_is_open_constructed_type (sig->params [j]))
3434 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3435 if (!mono_class_is_contextbound (method->klass)) {
3436 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3437 gboolean has_nullable = FALSE;
3439 for (j = 0; j < sig->param_count; j++) {
3440 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3441 has_nullable = TRUE;
3444 if (info && !has_nullable) {
3445 /* Supported by the dynamic runtime-invoke wrapper */
3449 mono_arch_dyn_call_free (info);
3454 //printf ("%s\n", mono_method_full_name (method, TRUE));
3455 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3459 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3462 /* Runtime invoke wrappers */
3464 /* void runtime-invoke () [.cctor] */
3465 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3466 csig->ret = &mono_defaults.void_class->byval_arg;
3467 add_method (acfg, get_runtime_invoke_sig (csig));
3469 /* void runtime-invoke () [Finalize] */
3470 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3472 csig->ret = &mono_defaults.void_class->byval_arg;
3473 add_method (acfg, get_runtime_invoke_sig (csig));
3475 /* void runtime-invoke (string) [exception ctor] */
3476 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3478 csig->ret = &mono_defaults.void_class->byval_arg;
3479 csig->params [0] = &mono_defaults.string_class->byval_arg;
3480 add_method (acfg, get_runtime_invoke_sig (csig));
3482 /* void runtime-invoke (string, string) [exception ctor] */
3483 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3485 csig->ret = &mono_defaults.void_class->byval_arg;
3486 csig->params [0] = &mono_defaults.string_class->byval_arg;
3487 csig->params [1] = &mono_defaults.string_class->byval_arg;
3488 add_method (acfg, get_runtime_invoke_sig (csig));
3490 /* string runtime-invoke () [Exception.ToString ()] */
3491 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3493 csig->ret = &mono_defaults.string_class->byval_arg;
3494 add_method (acfg, get_runtime_invoke_sig (csig));
3496 /* void runtime-invoke (string, Exception) [exception ctor] */
3497 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3499 csig->ret = &mono_defaults.void_class->byval_arg;
3500 csig->params [0] = &mono_defaults.string_class->byval_arg;
3501 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3502 add_method (acfg, get_runtime_invoke_sig (csig));
3504 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3505 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3507 csig->ret = &(mono_class_from_name (
3508 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3509 csig->params [0] = &mono_defaults.string_class->byval_arg;
3510 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3511 add_method (acfg, get_runtime_invoke_sig (csig));
3513 /* runtime-invoke used by finalizers */
3514 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3516 /* This is used by mono_runtime_capture_context () */
3517 method = mono_get_context_capture_method ();
3519 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3521 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3522 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3526 add_method (acfg, mono_marshal_get_stelemref ());
3528 if (MONO_ARCH_HAVE_TLS_GET) {
3529 /* Managed Allocators */
3530 nallocators = mono_gc_get_managed_allocator_types ();
3531 for (i = 0; i < nallocators; ++i) {
3532 m = mono_gc_get_managed_allocator_by_type (i);
3534 add_method (acfg, m);
3538 /* Stelemref wrappers */
3540 MonoMethod **wrappers;
3543 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3544 for (i = 0; i < nwrappers; ++i)
3545 add_method (acfg, wrappers [i]);
3549 /* castclass_with_check wrapper */
3550 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3551 /* isinst_with_check wrapper */
3552 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3554 /* JIT icall wrappers */
3555 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3556 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3560 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3561 * we use the original method instead at runtime.
3562 * Since full-aot doesn't support remoting, this is not a problem.
3565 /* remoting-invoke wrappers */
3566 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3567 MonoMethodSignature *sig;
3569 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3570 method = mono_get_method (acfg->image, token, NULL);
3572 sig = mono_method_signature (method);
3574 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3575 m = mono_marshal_get_remoting_invoke_with_check (method);
3577 add_method (acfg, m);
3582 /* delegate-invoke wrappers */
3583 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3586 MonoCustomAttrInfo *cattr;
3588 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3589 klass = mono_class_get_checked (acfg->image, token, &error);
3592 mono_error_cleanup (&error);
3596 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3599 if (!klass->generic_container) {
3600 method = mono_get_delegate_invoke (klass);
3602 m = mono_marshal_get_delegate_invoke (method, NULL);
3604 add_method (acfg, m);
3606 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3608 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3610 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3612 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3614 cattr = mono_custom_attrs_from_class (klass);
3619 for (j = 0; j < cattr->num_attrs; ++j)
3620 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3622 if (j < cattr->num_attrs)
3623 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3625 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3627 MonoGenericContext ctx;
3628 MonoMethod *inst, *gshared;
3631 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3634 method = mono_get_delegate_invoke (klass);
3635 create_gsharedvt_inst (acfg, method, &ctx);
3637 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3638 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3640 m = mono_marshal_get_delegate_invoke (inst, NULL);
3641 g_assert (m->is_inflated);
3643 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3644 add_extra_method (acfg, gshared);
3647 method = mono_get_delegate_begin_invoke (klass);
3648 create_gsharedvt_inst (acfg, method, &ctx);
3650 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3651 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3653 m = mono_marshal_get_delegate_begin_invoke (inst);
3654 g_assert (m->is_inflated);
3656 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3657 add_extra_method (acfg, gshared);
3660 method = mono_get_delegate_end_invoke (klass);
3661 create_gsharedvt_inst (acfg, method, &ctx);
3663 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3664 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3666 m = mono_marshal_get_delegate_end_invoke (inst);
3667 g_assert (m->is_inflated);
3669 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3670 add_extra_method (acfg, gshared);
3675 /* array access wrappers */
3676 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3680 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3681 klass = mono_class_get_checked (acfg->image, token, &error);
3684 mono_error_cleanup (&error);
3688 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3689 MonoMethod *m, *wrapper;
3691 /* Add runtime-invoke wrappers too */
3693 m = mono_class_get_method_from_name (klass, "Get", -1);
3695 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3696 add_extra_method (acfg, wrapper);
3697 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3699 m = mono_class_get_method_from_name (klass, "Set", -1);
3701 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3702 add_extra_method (acfg, wrapper);
3703 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3707 /* Synchronized wrappers */
3708 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3709 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3710 method = mono_get_method (acfg->image, token, NULL);
3712 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3713 if (method->is_generic) {
3715 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3717 MonoGenericContext ctx;
3718 MonoMethod *inst, *gshared, *m;
3721 * Create a generic wrapper for a generic instance, and AOT that.
3723 create_gsharedvt_inst (acfg, method, &ctx);
3724 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3725 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3726 m = mono_marshal_get_synchronized_wrapper (inst);
3727 g_assert (m->is_inflated);
3728 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3729 add_method (acfg, gshared);
3731 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3736 /* pinvoke wrappers */
3737 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3739 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3741 method = mono_get_method (acfg->image, token, NULL);
3743 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3744 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3745 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3749 /* native-to-managed wrappers */
3750 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3752 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3753 MonoCustomAttrInfo *cattr;
3756 method = mono_get_method (acfg->image, token, NULL);
3759 * Only generate native-to-managed wrappers for methods which have an
3760 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3761 * name to avoid defining a new assembly to contain it.
3763 cattr = mono_custom_attrs_from_method (method);
3766 for (j = 0; j < cattr->num_attrs; ++j)
3767 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3769 if (j < cattr->num_attrs) {
3770 MonoCustomAttrEntry *e = &cattr->attrs [j];
3771 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3772 const char *p = (const char*)e->data;
3774 int slen, num_named, named_type, data_type;
3778 char *export_name = NULL;
3779 MonoMethod *wrapper;
3781 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3782 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3783 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3784 mono_method_full_name (method, TRUE));
3788 g_assert (sig->param_count == 1);
3789 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3792 * Decode the cattr manually since we can't create objects
3793 * during aot compilation.
3799 /* From load_cattr_value () in reflection.c */
3800 slen = mono_metadata_decode_value (p, &p);
3801 n = g_memdup (p, slen + 1);
3803 t = mono_reflection_type_from_name (n, acfg->image);
3807 klass = mono_class_from_mono_type (t);
3808 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3812 num_named = read16 (p);
3815 g_assert (num_named < 2);
3816 if (num_named == 1) {
3819 MonoType *prop_type;
3821 /* parse ExportSymbol attribute */
3823 named_type = *named;
3828 name_len = mono_metadata_decode_blob_size (named, &named);
3829 name = g_malloc (name_len + 1);
3830 memcpy (name, named, name_len);
3831 name [name_len] = 0;
3834 g_assert (named_type == 0x54);
3835 g_assert (!strcmp (name, "ExportSymbol"));
3837 prop_type = &mono_defaults.string_class->byval_arg;
3839 /* load_cattr_value (), string case */
3840 g_assert (*named != (char)0xff);
3841 slen = mono_metadata_decode_value (named, &named);
3842 export_name = g_malloc (slen + 1);
3843 memcpy (export_name, named, slen);
3844 export_name [slen] = 0;
3848 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3849 add_method (acfg, wrapper);
3851 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3855 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3856 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3857 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3861 /* StructureToPtr/PtrToStructure wrappers */
3862 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3866 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3867 klass = mono_class_get_checked (acfg->image, token, &error);
3870 mono_error_cleanup (&error);
3874 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3875 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3876 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3877 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3883 has_type_vars (MonoClass *klass)
3885 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3888 return has_type_vars (klass->element_class);
3889 if (klass->generic_class) {
3890 MonoGenericContext *context = &klass->generic_class->context;
3891 if (context->class_inst) {
3894 for (i = 0; i < context->class_inst->type_argc; ++i)
3895 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3899 if (klass->generic_container)
3905 is_vt_inst (MonoGenericInst *inst)
3909 for (i = 0; i < inst->type_argc; ++i) {
3910 MonoType *t = inst->type_argv [i];
3911 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3918 method_has_type_vars (MonoMethod *method)
3920 if (has_type_vars (method->klass))
3923 if (method->is_inflated) {
3924 MonoGenericContext *context = mono_method_get_context (method);
3925 if (context->method_inst) {
3928 for (i = 0; i < context->method_inst->type_argc; ++i)
3929 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3936 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3939 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3941 /* This might lead to a huge code blowup so only do it if neccesary */
3942 if (!acfg->aot_opts.full_aot && !force)
3945 add_generic_class_with_depth (acfg, klass, 0, ref);
3949 check_type_depth (MonoType *t, int depth)
3957 case MONO_TYPE_GENERICINST: {
3958 MonoGenericClass *gklass = t->data.generic_class;
3959 MonoGenericInst *ginst = gklass->context.class_inst;
3962 for (i = 0; i < ginst->type_argc; ++i) {
3963 if (check_type_depth (ginst->type_argv [i], depth + 1))
3977 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3980 * add_generic_class:
3982 * Add all methods of a generic class.
3985 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3988 MonoClassField *field;
3990 gboolean use_gsharedvt = FALSE;
3992 if (!acfg->ginst_hash)
3993 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3995 mono_class_init (klass);
3997 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4000 if (has_type_vars (klass))
4003 if (!klass->generic_class && !klass->rank)
4006 if (klass->exception_type)
4009 if (!acfg->ginst_hash)
4010 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4012 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4015 if (check_type_depth (&klass->byval_arg, 0))
4018 if (acfg->aot_opts.log_generics)
4019 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4021 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4024 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4025 * Enable this only for some classes since gsharedvt might not support all methods.
4027 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) &&
4028 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4029 use_gsharedvt = TRUE;
4032 while ((method = mono_class_get_methods (klass, &iter))) {
4033 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4035 * This is partial sharing, and we can't handle it yet
4040 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4042 add_types_from_method_header (acfg, method);
4046 if (method->is_generic)
4051 * FIXME: Instances which are referenced by these methods are not added,
4052 * for example Array.Resize<int> for List<int>.Add ().
4054 add_extra_method_with_depth (acfg, method, depth + 1);
4058 while ((field = mono_class_get_fields (klass, &iter))) {
4059 if (field->type->type == MONO_TYPE_GENERICINST)
4060 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4063 if (klass->delegate) {
4064 method = mono_get_delegate_invoke (klass);
4066 method = mono_marshal_get_delegate_invoke (method, NULL);
4068 if (acfg->aot_opts.log_generics)
4069 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4071 add_method (acfg, method);
4074 /* Add superclasses */
4076 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4079 * For ICollection<T>, add instances of the helper methods
4080 * in Array, since a T[] could be cast to ICollection<T>.
4082 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4083 (!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"))) {
4084 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4085 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4089 if (!strcmp (klass->name, "IEnumerator`1"))
4090 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4092 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4094 /* Add the T[]/InternalEnumerator class */
4095 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4099 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4100 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4104 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4105 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4109 while ((method = mono_class_get_methods (array_class, &iter))) {
4110 if (strstr (method->name, name_prefix)) {
4111 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4113 add_extra_method_with_depth (acfg, m, depth);
4117 g_free (name_prefix);
4120 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4121 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4122 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4123 MonoClass *icomparable, *gcomparer;
4124 MonoGenericContext ctx;
4125 MonoType *args [16];
4127 memset (&ctx, 0, sizeof (ctx));
4129 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4130 g_assert (icomparable);
4131 args [0] = &tclass->byval_arg;
4132 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4134 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4135 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4136 g_assert (gcomparer);
4137 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4141 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4142 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4143 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4144 MonoClass *iface, *gcomparer;
4145 MonoGenericContext ctx;
4146 MonoType *args [16];
4148 memset (&ctx, 0, sizeof (ctx));
4150 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4152 args [0] = &tclass->byval_arg;
4153 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4155 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4156 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4157 g_assert (gcomparer);
4158 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4164 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4167 MonoGenericContext ctx;
4168 MonoType *args [16];
4170 if (acfg->aot_opts.no_instances)
4173 memset (&ctx, 0, sizeof (ctx));
4175 for (i = 0; i < ninsts; ++i) {
4176 args [0] = insts [i];
4177 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4178 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4183 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4185 MonoMethodHeader *header;
4186 MonoMethodSignature *sig;
4189 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4191 sig = mono_method_signature (method);
4194 for (j = 0; j < sig->param_count; ++j)
4195 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4196 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4199 header = mono_method_get_header (method);
4202 for (j = 0; j < header->num_locals; ++j)
4203 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4204 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4206 mono_loader_clear_error ();
4211 * add_generic_instances:
4213 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4216 add_generic_instances (MonoAotCompile *acfg)
4221 MonoGenericContext *context;
4223 if (acfg->aot_opts.no_instances)
4226 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4227 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4228 method = mono_get_method (acfg->image, token, NULL);
4233 if (method->klass->image != acfg->image)
4236 context = mono_method_get_context (method);
4238 if (context && ((context->class_inst && context->class_inst->is_open)))
4242 * For open methods, create an instantiation which can be passed to the JIT.
4243 * FIXME: Handle class_inst as well.
4245 if (context && context->method_inst && context->method_inst->is_open) {
4247 MonoGenericContext shared_context;
4248 MonoGenericInst *inst;
4249 MonoType **type_argv;
4251 MonoMethod *declaring_method;
4252 gboolean supported = TRUE;
4254 /* Check that the context doesn't contain open constructed types */
4255 if (context->class_inst) {
4256 inst = context->class_inst;
4257 for (i = 0; i < inst->type_argc; ++i) {
4258 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)
4260 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4264 if (context->method_inst) {
4265 inst = context->method_inst;
4266 for (i = 0; i < inst->type_argc; ++i) {
4267 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)
4269 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4277 memset (&shared_context, 0, sizeof (MonoGenericContext));
4279 inst = context->class_inst;
4281 type_argv = g_new0 (MonoType*, inst->type_argc);
4282 for (i = 0; i < inst->type_argc; ++i) {
4283 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)
4284 type_argv [i] = &mono_defaults.object_class->byval_arg;
4286 type_argv [i] = inst->type_argv [i];
4289 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4293 inst = context->method_inst;
4295 type_argv = g_new0 (MonoType*, inst->type_argc);
4296 for (i = 0; i < inst->type_argc; ++i) {
4297 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)
4298 type_argv [i] = &mono_defaults.object_class->byval_arg;
4300 type_argv [i] = inst->type_argv [i];
4303 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4307 if (method->is_generic || method->klass->generic_container)
4308 declaring_method = method;
4310 declaring_method = mono_method_get_declaring_generic_method (method);
4312 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4313 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4317 * If the method is fully sharable, it was already added in place of its
4318 * generic definition.
4320 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4324 * FIXME: Partially shared methods are not shared here, so we end up with
4325 * many identical methods.
4327 add_extra_method (acfg, method);
4330 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4334 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4336 klass = mono_class_get_checked (acfg->image, token, &error);
4337 if (!klass || klass->rank) {
4338 mono_error_cleanup (&error);
4342 add_generic_class (acfg, klass, FALSE, "typespec");
4345 /* Add types of args/locals */
4346 for (i = 0; i < acfg->methods->len; ++i) {
4347 method = g_ptr_array_index (acfg->methods, i);
4348 add_types_from_method_header (acfg, method);
4351 if (acfg->image == mono_defaults.corlib) {
4353 MonoType *insts [256];
4356 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4357 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4358 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4359 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4360 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4361 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4362 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4363 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4364 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4365 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4366 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4367 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4369 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4370 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4372 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4373 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4375 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4377 /* Add instances of the array generic interfaces for primitive types */
4378 /* This will add instances of the InternalArray_ helper methods in Array too */
4379 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4381 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4382 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4384 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4385 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4387 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4390 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4391 * used for all instances of GetGenericValueImpl by the AOT runtime.
4394 MonoGenericContext ctx;
4395 MonoType *args [16];
4396 MonoMethod *get_method;
4397 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4399 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4403 memset (&ctx, 0, sizeof (ctx));
4404 args [0] = &mono_defaults.object_class->byval_arg;
4405 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4406 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4407 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4411 /* Same for CompareExchange<T>/Exchange<T> */
4413 MonoGenericContext ctx;
4414 MonoType *args [16];
4416 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4417 gpointer iter = NULL;
4419 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4420 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4422 memset (&ctx, 0, sizeof (ctx));
4423 args [0] = &mono_defaults.object_class->byval_arg;
4424 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4425 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4426 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4431 /* Same for Volatile.Read/Write<T> */
4433 MonoGenericContext ctx;
4434 MonoType *args [16];
4436 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4437 gpointer iter = NULL;
4439 if (volatile_klass) {
4440 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4441 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4443 memset (&ctx, 0, sizeof (ctx));
4444 args [0] = &mono_defaults.object_class->byval_arg;
4445 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4446 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4447 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4456 * is_direct_callable:
4458 * Return whenever the method identified by JI is directly callable without
4459 * going through the PLT.
4462 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4464 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4465 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4467 gboolean direct_callable = TRUE;
4469 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4470 direct_callable = FALSE;
4471 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4472 // FIXME: Maybe call the wrapper directly ?
4473 direct_callable = FALSE;
4475 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4476 /* Disable this so all calls go through load_method (), see the
4477 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4478 * mono_debugger_agent_init ().
4480 direct_callable = FALSE;
4483 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4484 /* sgen does some initialization when the allocator method is created */
4485 direct_callable = FALSE;
4487 if (direct_callable)
4490 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4491 if (acfg->aot_opts.direct_pinvoke)
4493 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4494 if (acfg->aot_opts.direct_icalls)
4502 #ifdef MONO_ARCH_AOT_SUPPORTED
4504 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4506 MonoImage *image = method->klass->image;
4507 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4508 MonoTableInfo *tables = image->tables;
4509 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4510 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4511 guint32 im_cols [MONO_IMPLMAP_SIZE];
4514 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4518 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4521 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4523 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4526 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4528 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4535 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4537 if (a->native_offset == b->native_offset)
4538 return a->il_offset - b->il_offset;
4540 return a->native_offset - b->native_offset;
4544 * compute_line_numbers:
4546 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4549 static MonoDebugSourceLocation**
4550 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4552 MonoDebugMethodInfo *minfo;
4553 MonoDebugLineNumberEntry *ln_array;
4554 MonoDebugSourceLocation *loc;
4555 int i, prev_line, prev_il_offset;
4556 int *native_to_il_offset = NULL;
4557 MonoDebugSourceLocation **res;
4560 minfo = mono_debug_lookup_method (method);
4563 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4564 if (debug_info->code_size != code_size)
4567 g_assert (code_size);
4569 /* Compute the native->IL offset mapping */
4571 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4572 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4574 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4576 native_to_il_offset = g_new0 (int, code_size + 1);
4578 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4580 MonoDebugLineNumberEntry *lne = &ln_array [i];
4583 for (j = 0; j < lne->native_offset; ++j)
4584 native_to_il_offset [j] = -1;
4587 if (i < debug_info->num_line_numbers - 1) {
4588 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4590 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4591 native_to_il_offset [j] = lne->il_offset;
4593 for (j = lne->native_offset; j < code_size; ++j)
4594 native_to_il_offset [j] = lne->il_offset;
4599 /* Compute the native->line number mapping */
4600 res = g_new0 (MonoDebugSourceLocation*, code_size);
4601 prev_il_offset = -1;
4604 for (i = 0; i < code_size; ++i) {
4605 int il_offset = native_to_il_offset [i];
4607 if (il_offset == -1 || il_offset == prev_il_offset)
4609 prev_il_offset = il_offset;
4610 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4611 if (!(loc && loc->source_file))
4613 if (loc->row == prev_line) {
4614 mono_debug_symfile_free_location (loc);
4617 prev_line = loc->row;
4618 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4620 /* This will cover the prolog too */
4630 get_file_index (MonoAotCompile *acfg, const char *source_file)
4634 // FIXME: Free these
4635 if (!acfg->dwarf_ln_filenames)
4636 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4637 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4639 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4640 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4641 emit_unset_mode (acfg);
4642 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4654 * emit_and_reloc_code:
4656 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4657 * is true, calls are made through the GOT too. This is used for emitting trampolines
4658 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4659 * since trampolines are needed to make PTL work.
4662 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4664 int i, pindex, start_index, method_index;
4666 MonoJumpInfo *patch_info;
4667 MonoMethodHeader *header;
4668 MonoDebugSourceLocation **locs = NULL;
4670 #ifdef MONO_ARCH_AOT_SUPPORTED
4671 gboolean direct_call, external_call;
4673 const char *direct_call_target = 0;
4674 const char *direct_pinvoke;
4678 header = mono_method_get_header (method);
4680 method_index = get_method_index (acfg, method);
4683 if (acfg->gas_line_numbers && method && debug_info) {
4684 locs = compute_line_numbers (method, code_len, debug_info);
4686 int findex = get_file_index (acfg, "<unknown>");
4687 emit_unset_mode (acfg);
4688 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4692 /* Collect and sort relocations */
4693 patches = g_ptr_array_new ();
4694 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4695 g_ptr_array_add (patches, patch_info);
4696 g_ptr_array_sort (patches, compare_patches);
4699 for (i = 0; i < code_len; i += INST_LEN) {
4701 for (pindex = start_index; pindex < patches->len; ++pindex) {
4702 patch_info = g_ptr_array_index (patches, pindex);
4703 if (patch_info->ip.i >= i)
4707 if (locs && locs [i]) {
4708 MonoDebugSourceLocation *loc = locs [i];
4711 findex = get_file_index (acfg, loc->source_file);
4712 emit_unset_mode (acfg);
4713 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4714 mono_debug_symfile_free_location (loc);
4718 #ifdef MONO_ARCH_AOT_SUPPORTED
4719 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4720 start_index = pindex;
4722 switch (patch_info->type) {
4723 case MONO_PATCH_INFO_NONE:
4725 case MONO_PATCH_INFO_GOT_OFFSET: {
4728 arch_emit_got_offset (acfg, code + i, &code_size);
4729 i += code_size - INST_LEN;
4731 patch_info->type = MONO_PATCH_INFO_NONE;
4734 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4735 int code_size, index;
4736 char *selector = (void*)patch_info->data.target;
4738 if (!acfg->objc_selector_to_index)
4739 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4740 if (!acfg->objc_selectors)
4741 acfg->objc_selectors = g_ptr_array_new ();
4742 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4746 index = acfg->objc_selector_index;
4747 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4748 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4749 acfg->objc_selector_index ++;
4752 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4753 i += code_size - INST_LEN;
4755 patch_info->type = MONO_PATCH_INFO_NONE;
4760 * If this patch is a call, try emitting a direct call instead of
4761 * through a PLT entry. This is possible if the called method is in
4762 * the same assembly and requires no initialization.
4764 direct_call = FALSE;
4765 external_call = FALSE;
4766 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4767 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4768 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4769 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4771 direct_call_target = callee_cfg->asm_symbol;
4772 patch_info->type = MONO_PATCH_INFO_NONE;
4773 acfg->stats.direct_calls ++;
4776 acfg->stats.all_calls ++;
4777 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4778 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4779 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4780 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4782 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4783 if (direct_pinvoke) {
4785 g_assert (strlen (direct_pinvoke) < 1000);
4786 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4789 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4790 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4791 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4792 /* Call to a C function implementing a jit icall */
4794 external_call = TRUE;
4795 g_assert (strlen (sym) < 1000);
4796 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4798 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4799 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4800 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4801 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4802 /* Call to a jit icall without a wrapper */
4804 external_call = TRUE;
4805 g_assert (strlen (sym) < 1000);
4806 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4811 patch_info->type = MONO_PATCH_INFO_NONE;
4812 acfg->stats.direct_calls ++;
4815 if (!got_only && !direct_call) {
4816 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4818 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4820 direct_call_target = plt_entry->symbol;
4822 /* Nullify the patch */
4823 patch_info->type = MONO_PATCH_INFO_NONE;
4824 plt_entry->jit_used = TRUE;
4831 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4832 i += call_size - INST_LEN;
4836 got_slot = get_got_offset (acfg, FALSE, patch_info);
4838 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4839 i += code_size - INST_LEN;
4845 #endif /* MONO_ARCH_AOT_SUPPORTED */
4848 /* Find next patch */
4850 for (pindex = start_index; pindex < patches->len; ++pindex) {
4851 patch_info = g_ptr_array_index (patches, pindex);
4852 if (patch_info->ip.i >= i)
4856 /* Try to emit multiple bytes at once */
4857 if (pindex < patches->len && patch_info->ip.i > i) {
4860 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4861 if (locs && locs [limit])
4865 emit_code_bytes (acfg, code + i, limit - i);
4866 i = limit - INST_LEN;
4868 emit_code_bytes (acfg, code + i, INST_LEN);
4879 * Return a modified version of S which only includes characters permissible in symbols.
4882 sanitize_symbol (MonoAotCompile *acfg, char *s)
4884 gboolean process = FALSE;
4893 for (i = 0; i < len; ++i)
4894 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4899 gs = g_string_sized_new (len);
4900 for (i = 0; i < len; ++i) {
4902 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4903 g_string_append_c (gs, c);
4904 } else if (c > 0x7f) {
4905 /* multi-byte utf8 */
4906 g_string_append_printf (gs, "_0x%x", c);
4909 while (c >> 6 == 0x2) {
4910 g_string_append_printf (gs, "%x", c);
4914 g_string_append_printf (gs, "_");
4917 g_string_append_c (gs, '_');
4921 res = mono_mempool_strdup (acfg->mempool, gs->str);
4922 g_string_free (gs, TRUE);
4927 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4929 char *name1, *name2, *cached;
4930 int i, j, len, count;
4931 MonoMethod *cached_method;
4933 name1 = mono_method_full_name (method, TRUE);
4936 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4937 if ((!prefix || !*prefix) && name1 [0] == 'L')
4941 len = strlen (name1);
4942 name2 = malloc (strlen (prefix) + len + 16);
4943 memcpy (name2, prefix, strlen (prefix));
4944 j = strlen (prefix);
4945 for (i = 0; i < len; ++i) {
4946 if (isalnum (name1 [i])) {
4947 name2 [j ++] = name1 [i];
4948 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4950 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4953 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4963 cached_method = g_hash_table_lookup (cache, name2);
4964 if (!(cached_method && cached_method != method))
4966 sprintf (name2 + j, "_%d", count);
4970 cached = g_strdup (name2);
4971 g_hash_table_insert (cache, cached, method);
4977 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4982 char *debug_sym = NULL;
4983 char *symbol = NULL;
4984 int func_alignment = AOT_FUNC_ALIGNMENT;
4985 MonoMethodHeader *header;
4988 method = cfg->orig_method;
4989 code = cfg->native_code;
4990 header = cfg->header;
4992 method_index = get_method_index (acfg, method);
4993 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4995 /* Make the labels local */
4996 emit_section_change (acfg, ".text", 0);
4997 emit_alignment_code (acfg, func_alignment);
4999 if (acfg->global_symbols && acfg->need_no_dead_strip)
5000 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5002 emit_label (acfg, cfg->asm_symbol);
5004 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm_separate) {
5006 * Write a C style symbol for every method, this has two uses:
5007 * - it works on platforms where the dwarf debugging info is not
5009 * - it allows the setting of breakpoints of aot-ed methods.
5011 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5013 if (acfg->need_no_dead_strip)
5014 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5015 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5016 emit_label (acfg, debug_sym);
5019 export_name = g_hash_table_lookup (acfg->export_names, method);
5021 /* Emit a global symbol for the method */
5022 emit_global_inner (acfg, export_name, TRUE);
5023 emit_label (acfg, export_name);
5026 if (cfg->verbose_level > 0)
5027 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5029 acfg->stats.code_size += cfg->code_len;
5031 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5033 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 ()));
5037 if (acfg->aot_opts.write_symbols) {
5038 emit_symbol_size (acfg, debug_sym, ".");
5042 emit_label (acfg, symbol);
5049 * Encode PATCH_INFO into its disk representation.
5052 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5056 switch (patch_info->type) {
5057 case MONO_PATCH_INFO_NONE:
5059 case MONO_PATCH_INFO_IMAGE:
5060 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5062 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5063 case MONO_PATCH_INFO_JIT_TLS_ID:
5064 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5066 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5067 encode_value (patch_info->data.index, p, &p);
5069 case MONO_PATCH_INFO_METHOD_REL:
5070 encode_value ((gint)patch_info->data.offset, p, &p);
5072 case MONO_PATCH_INFO_SWITCH: {
5073 gpointer *table = (gpointer *)patch_info->data.table->table;
5076 encode_value (patch_info->data.table->table_size, p, &p);
5077 for (k = 0; k < patch_info->data.table->table_size; k++)
5078 encode_value ((int)(gssize)table [k], p, &p);
5081 case MONO_PATCH_INFO_METHODCONST:
5082 case MONO_PATCH_INFO_METHOD:
5083 case MONO_PATCH_INFO_METHOD_JUMP:
5084 case MONO_PATCH_INFO_ICALL_ADDR:
5085 case MONO_PATCH_INFO_METHOD_RGCTX:
5086 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5087 encode_method_ref (acfg, patch_info->data.method, p, &p);
5089 case MONO_PATCH_INFO_INTERNAL_METHOD:
5090 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5091 guint32 len = strlen (patch_info->data.name);
5093 encode_value (len, p, &p);
5095 memcpy (p, patch_info->data.name, len);
5100 case MONO_PATCH_INFO_LDSTR: {
5101 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5102 guint32 token = patch_info->data.token->token;
5103 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5104 encode_value (image_index, p, &p);
5105 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5108 case MONO_PATCH_INFO_RVA:
5109 case MONO_PATCH_INFO_DECLSEC:
5110 case MONO_PATCH_INFO_LDTOKEN:
5111 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5112 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5113 encode_value (patch_info->data.token->token, p, &p);
5114 encode_value (patch_info->data.token->has_context, p, &p);
5115 if (patch_info->data.token->has_context)
5116 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5118 case MONO_PATCH_INFO_EXC_NAME: {
5119 MonoClass *ex_class;
5122 mono_class_from_name (mono_defaults.exception_class->image,
5123 "System", patch_info->data.target);
5124 g_assert (ex_class);
5125 encode_klass_ref (acfg, ex_class, p, &p);
5128 case MONO_PATCH_INFO_R4:
5129 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5131 case MONO_PATCH_INFO_R8:
5132 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5133 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5135 case MONO_PATCH_INFO_VTABLE:
5136 case MONO_PATCH_INFO_CLASS:
5137 case MONO_PATCH_INFO_IID:
5138 case MONO_PATCH_INFO_ADJUSTED_IID:
5139 case MONO_PATCH_INFO_CLASS_INIT:
5140 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5142 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5143 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5144 if (patch_info->data.del_tramp->method) {
5145 encode_value (1, p, &p);
5146 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5148 encode_value (0, p, &p);
5150 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5152 case MONO_PATCH_INFO_FIELD:
5153 case MONO_PATCH_INFO_SFLDA:
5154 encode_field_info (acfg, patch_info->data.field, p, &p);
5156 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5158 case MONO_PATCH_INFO_RGCTX_FETCH: {
5159 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5164 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5165 * reference the same method, so encode the method only once.
5167 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5169 buf2 = g_malloc (1024);
5172 encode_method_ref (acfg, entry->method, p2, &p2);
5173 g_assert (p2 - buf2 < 1024);
5175 offset = add_to_blob (acfg, buf2, p2 - buf2);
5178 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5183 encode_value (offset, p, &p);
5184 g_assert ((int)entry->info_type < 256);
5185 g_assert (entry->data->type < 256);
5186 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5187 encode_patch (acfg, entry->data, p, &p);
5190 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5191 case MONO_PATCH_INFO_MONITOR_ENTER:
5192 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5193 case MONO_PATCH_INFO_MONITOR_EXIT:
5194 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5196 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5197 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5198 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5200 case MONO_PATCH_INFO_SIGNATURE:
5201 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5203 case MONO_PATCH_INFO_TLS_OFFSET:
5204 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5206 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5207 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5208 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5210 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5211 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5214 encode_method_ref (acfg, info->method, p, &p);
5215 encode_value (info->num_entries, p, &p);
5216 for (i = 0; i < info->num_entries; ++i) {
5217 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5219 encode_value (template->info_type, p, &p);
5220 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5221 case MONO_PATCH_INFO_CLASS:
5222 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5224 case MONO_PATCH_INFO_FIELD:
5225 encode_field_info (acfg, template->data, p, &p);
5228 g_assert_not_reached ();
5234 case MONO_PATCH_INFO_LDSTR_LIT: {
5235 const char *s = patch_info->data.target;
5237 encode_value (strlen (s), p, &p);
5238 memcpy (p, s, strlen (s) + 1);
5242 g_warning ("unable to handle jump info %d", patch_info->type);
5243 g_assert_not_reached ();
5250 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5253 guint32 pindex, offset;
5254 MonoJumpInfo *patch_info;
5256 encode_value (n_patches, p, &p);
5258 for (pindex = 0; pindex < patches->len; ++pindex) {
5259 patch_info = g_ptr_array_index (patches, pindex);
5261 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5265 offset = get_got_offset (acfg, llvm, patch_info);
5266 encode_value (offset, p, &p);
5273 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5277 int pindex, buf_size, n_patches;
5279 MonoJumpInfo *patch_info;
5280 MonoMethodHeader *header;
5281 guint32 method_index;
5283 guint32 first_got_offset;
5285 method = cfg->orig_method;
5286 header = mono_method_get_header (method);
5288 method_index = get_method_index (acfg, method);
5290 /* Sort relocations */
5291 patches = g_ptr_array_new ();
5292 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5293 g_ptr_array_add (patches, patch_info);
5294 g_ptr_array_sort (patches, compare_patches);
5296 first_got_offset = acfg->cfgs [method_index]->got_offset;
5298 /**********************/
5299 /* Encode method info */
5300 /**********************/
5302 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5303 p = buf = g_malloc (buf_size);
5305 if (mono_class_get_cctor (method->klass))
5306 encode_klass_ref (acfg, method->klass, p, &p);
5308 /* Not needed when loading the method */
5309 encode_value (0, p, &p);
5312 if (cfg->opt & MONO_OPT_SHARED) {
5313 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5314 for (l = cfg->ldstr_list; l; l = l->next) {
5315 encode_value ((long)l->data, p, &p);
5319 /* Used only in shared mode */
5320 g_assert (!cfg->ldstr_list);
5323 for (pindex = 0; pindex < patches->len; ++pindex) {
5324 patch_info = g_ptr_array_index (patches, pindex);
5326 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5327 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5328 patch_info->type = MONO_PATCH_INFO_NONE;
5333 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5334 /* Stored in a GOT slot initialized at module load time */
5335 patch_info->type = MONO_PATCH_INFO_NONE;
5339 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5340 /* Stored in a GOT slot initialized at module load time */
5341 patch_info->type = MONO_PATCH_INFO_NONE;
5345 if (is_plt_patch (patch_info)) {
5346 /* Calls are made through the PLT */
5347 patch_info->type = MONO_PATCH_INFO_NONE;
5355 g_assert (cfg->has_got_slots);
5357 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5359 acfg->stats.info_size += p - buf;
5361 g_assert (p - buf < buf_size);
5363 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5368 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5370 guint32 cache_index;
5373 /* Reuse the unwind module to canonize and store unwind info entries */
5374 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5376 /* Use +/- 1 to distinguish 0s from missing entries */
5377 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5385 * It would be easier to use assembler symbols, but the caller needs an
5388 offset = acfg->unwind_info_offset;
5389 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5390 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5393 encode_value (encoded_len, p, &p);
5395 acfg->unwind_info_offset += encoded_len + (p - buf);
5401 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5404 int i, k, buf_size, method_index;
5405 guint32 debug_info_size, seq_points_size;
5407 MonoMethodHeader *header;
5408 guint8 *p, *buf, *debug_info;
5409 MonoJitInfo *jinfo = cfg->jit_info;
5411 gboolean use_unwind_ops = FALSE;
5412 MonoSeqPointInfo *seq_points;
5414 method = cfg->orig_method;
5415 code = cfg->native_code;
5416 header = cfg->header;
5418 method_index = get_method_index (acfg, method);
5420 if (!acfg->aot_opts.nodebug) {
5421 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5424 debug_info_size = 0;
5427 seq_points = cfg->seq_point_info;
5429 seq_points_size = (cfg->gen_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5431 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5432 p = buf = g_malloc (buf_size);
5434 use_unwind_ops = cfg->unwind_ops != NULL;
5436 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);
5438 encode_value (flags, p, &p);
5440 if (use_unwind_ops) {
5441 guint32 encoded_len;
5443 guint32 unwind_desc;
5445 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5447 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5448 encode_value (unwind_desc, p, &p);
5450 encode_value (jinfo->unwind_info, p, &p);
5453 /*Encode the number of holes before the number of clauses to make decoding easier*/
5454 if (jinfo->has_try_block_holes) {
5455 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5456 encode_value (table->num_holes, p, &p);
5459 if (jinfo->has_arch_eh_info) {
5461 * In AOT mode, the code length is calculated from the address of the previous method,
5462 * which could include alignment padding, so calculating the start of the epilog as
5463 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5465 encode_value (jinfo->code_size, p, &p);
5468 /* Exception table */
5469 if (cfg->compile_llvm) {
5471 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5472 * since the information is only available to llc. Instead, we let llc save the data
5473 * into the LSDA, and read it from there at runtime.
5475 /* The assembly might be CIL stripped so emit the data ourselves */
5476 if (header->num_clauses)
5477 encode_value (header->num_clauses, p, &p);
5479 for (k = 0; k < header->num_clauses; ++k) {
5480 MonoExceptionClause *clause;
5482 clause = &header->clauses [k];
5484 encode_value (clause->flags, p, &p);
5485 if (clause->data.catch_class) {
5486 encode_value (1, p, &p);
5487 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5489 encode_value (0, p, &p);
5492 /* Emit a list of nesting clauses */
5493 for (i = 0; i < header->num_clauses; ++i) {
5495 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5497 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5499 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5500 encode_value (i, p, &p);
5502 encode_value (-1, p, &p);
5505 if (jinfo->num_clauses)
5506 encode_value (jinfo->num_clauses, p, &p);
5508 for (k = 0; k < jinfo->num_clauses; ++k) {
5509 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5511 encode_value (ei->flags, p, &p);
5512 encode_value (ei->exvar_offset, p, &p);
5514 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5515 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5517 if (ei->data.catch_class) {
5521 buf2 = g_malloc (4096);
5523 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5525 g_assert (len < 4096);
5526 encode_value (len, p, &p);
5527 memcpy (p, buf2, len);
5531 encode_value (0, p, &p);
5535 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5536 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5537 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5541 if (jinfo->has_try_block_holes) {
5542 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5543 for (i = 0; i < table->num_holes; ++i) {
5544 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5545 encode_value (hole->clause, p, &p);
5546 encode_value (hole->length, p, &p);
5547 encode_value (hole->offset, p, &p);
5551 if (jinfo->has_arch_eh_info) {
5552 MonoArchEHJitInfo *eh_info;
5554 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5555 encode_value (eh_info->stack_size, p, &p);
5556 encode_value (eh_info->epilog_size, p, &p);
5559 if (jinfo->has_generic_jit_info) {
5560 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5561 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5567 encode_value (gi->nlocs, p, &p);
5569 for (i = 0; i < gi->nlocs; ++i) {
5570 MonoDwarfLocListEntry *entry = &gi->locations [i];
5572 encode_value (entry->is_reg ? 1 : 0, p, &p);
5573 encode_value (entry->reg, p, &p);
5575 encode_value (entry->offset, p, &p);
5577 g_assert (entry->from == 0);
5579 encode_value (entry->from, p, &p);
5580 encode_value (entry->to, p, &p);
5583 if (!cfg->compile_llvm) {
5584 encode_value (gi->has_this ? 1 : 0, p, &p);
5585 encode_value (gi->this_reg, p, &p);
5586 encode_value (gi->this_offset, p, &p);
5591 * Need to encode jinfo->method too, since it is not equal to 'method'
5592 * when using generic sharing.
5594 buf2 = g_malloc (4096);
5596 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5598 g_assert (len < 4096);
5599 encode_value (len, p, &p);
5600 memcpy (p, buf2, len);
5604 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5605 MonoMethodInflated *inflated;
5606 MonoGenericContext *context;
5607 MonoGenericInst *inst;
5609 g_assert (jinfo->d.method->is_inflated);
5610 inflated = (MonoMethodInflated*)jinfo->d.method;
5611 context = &inflated->context;
5613 encode_value (1, p, &p);
5614 if (context->class_inst) {
5615 inst = context->class_inst;
5617 encode_value (inst->type_argc, p, &p);
5618 for (i = 0; i < inst->type_argc; ++i)
5619 encode_value (gsctx->var_is_vt [i], p, &p);
5621 encode_value (0, p, &p);
5623 if (context->method_inst) {
5624 inst = context->method_inst;
5626 encode_value (inst->type_argc, p, &p);
5627 for (i = 0; i < inst->type_argc; ++i)
5628 encode_value (gsctx->mvar_is_vt [i], p, &p);
5630 encode_value (0, p, &p);
5633 encode_value (0, p, &p);
5638 p += seq_point_info_write (seq_points, p);
5640 g_assert (debug_info_size < buf_size);
5642 encode_value (debug_info_size, p, &p);
5643 if (debug_info_size) {
5644 memcpy (p, debug_info, debug_info_size);
5645 p += debug_info_size;
5646 g_free (debug_info);
5651 encode_value (cfg->gc_map_size, p, &p);
5652 /* The GC map requires 4 bytes of alignment */
5653 while ((gsize)p % 4)
5655 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5656 p += cfg->gc_map_size;
5659 acfg->stats.ex_info_size += p - buf;
5661 g_assert (p - buf < buf_size);
5664 /* The GC Map requires 4 byte alignment */
5665 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5670 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5673 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5675 int i, buf_size, res;
5676 gboolean no_special_static, cant_encode;
5677 gpointer iter = NULL;
5680 mono_error_cleanup (&error);
5684 p = buf = g_malloc (buf_size);
5686 /* Mark as unusable */
5687 encode_value (-1, p, &p);
5689 res = add_to_blob (acfg, buf, p - buf);
5695 buf_size = 10240 + (klass->vtable_size * 16);
5696 p = buf = g_malloc (buf_size);
5700 mono_class_init (klass);
5702 mono_class_get_nested_types (klass, &iter);
5703 g_assert (klass->nested_classes_inited);
5705 mono_class_setup_vtable (klass);
5708 * Emit all the information which is required for creating vtables so
5709 * the runtime does not need to create the MonoMethod structures which
5710 * take up a lot of space.
5713 no_special_static = !mono_class_has_special_static_fields (klass);
5715 /* Check whenever we have enough info to encode the vtable */
5716 cant_encode = FALSE;
5717 for (i = 0; i < klass->vtable_size; ++i) {
5718 MonoMethod *cm = klass->vtable [i];
5720 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5724 mono_class_has_finalizer (klass);
5726 if (klass->generic_container || cant_encode) {
5727 encode_value (-1, p, &p);
5729 encode_value (klass->vtable_size, p, &p);
5730 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);
5731 if (klass->has_cctor)
5732 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5733 if (klass->has_finalize)
5734 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5736 encode_value (klass->instance_size, p, &p);
5737 encode_value (mono_class_data_size (klass), p, &p);
5738 encode_value (klass->packing_size, p, &p);
5739 encode_value (klass->min_align, p, &p);
5741 for (i = 0; i < klass->vtable_size; ++i) {
5742 MonoMethod *cm = klass->vtable [i];
5745 encode_method_ref (acfg, cm, p, &p);
5747 encode_value (0, p, &p);
5751 acfg->stats.class_info_size += p - buf;
5753 g_assert (p - buf < buf_size);
5754 res = add_to_blob (acfg, buf, p - buf);
5761 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5763 char *debug_sym = NULL;
5767 if (acfg->llvm_separate && llvm_acfg->aot_opts.static_link) {
5768 /* Need to add a prefix to create unique symbols */
5769 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5771 prefix = g_strdup ("plt_");
5775 case MONO_PATCH_INFO_METHOD:
5776 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5778 case MONO_PATCH_INFO_INTERNAL_METHOD:
5779 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5781 case MONO_PATCH_INFO_CLASS_INIT:
5782 s = mono_type_get_name (&ji->data.klass->byval_arg);
5783 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5786 case MONO_PATCH_INFO_RGCTX_FETCH:
5787 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5789 case MONO_PATCH_INFO_ICALL_ADDR: {
5790 char *s = get_debug_sym (ji->data.method, "", cache);
5792 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5796 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5797 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5799 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5800 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5808 return sanitize_symbol (acfg, debug_sym);
5812 * Calls made from AOTed code are routed through a table of jumps similar to the
5813 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5814 * control to the AOT runtime through a trampoline.
5817 emit_plt (MonoAotCompile *acfg)
5823 sprintf (symbol, "plt");
5825 emit_section_change (acfg, ".text", 0);
5826 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5827 emit_label (acfg, symbol);
5828 emit_label (acfg, acfg->plt_symbol);
5830 for (i = 0; i < acfg->plt_offset; ++i) {
5831 char *debug_sym = NULL;
5832 MonoPltEntry *plt_entry = NULL;
5837 * The first plt entry is unused.
5841 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5844 debug_sym = plt_entry->debug_sym;
5846 if (acfg->thumb_mixed && !plt_entry->jit_used)
5847 /* Emit only a thumb version */
5850 /* Skip plt entries not actually called */
5851 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5854 if (acfg->llvm && !acfg->thumb_mixed) {
5855 emit_label (acfg, plt_entry->llvm_symbol);
5856 if (acfg->llvm_separate) {
5857 emit_global (acfg, plt_entry->llvm_symbol, TRUE);
5858 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5863 if (acfg->need_no_dead_strip) {
5864 emit_unset_mode (acfg);
5865 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5867 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5868 emit_label (acfg, debug_sym);
5871 emit_label (acfg, plt_entry->symbol);
5873 arch_emit_plt_entry (acfg, i);
5876 emit_symbol_size (acfg, debug_sym, ".");
5879 if (acfg->thumb_mixed) {
5880 /* Make sure the ARM symbols don't alias the thumb ones */
5881 emit_zero_bytes (acfg, 16);
5884 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5887 for (i = 0; i < acfg->plt_offset; ++i) {
5888 char *debug_sym = NULL;
5889 MonoPltEntry *plt_entry = NULL;
5895 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5898 /* Skip plt entries not actually called by LLVM code */
5899 if (!plt_entry->llvm_used)
5902 if (acfg->aot_opts.write_symbols) {
5903 if (plt_entry->debug_sym)
5904 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5908 #if defined(TARGET_MACH)
5909 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5910 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5912 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5913 emit_label (acfg, debug_sym);
5915 fprintf (acfg->fp, "\n.thumb_func\n");
5917 emit_label (acfg, plt_entry->llvm_symbol);
5919 arch_emit_llvm_plt_entry (acfg, i);
5922 emit_symbol_size (acfg, debug_sym, ".");
5928 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5930 sprintf (symbol, "plt_end");
5931 emit_label (acfg, symbol);
5935 * emit_trampoline_full:
5937 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5938 * create_jit_info_for_trampoline ().
5940 static G_GNUC_UNUSED void
5941 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5943 char start_symbol [256];
5944 char end_symbol [256];
5946 guint32 buf_size, info_offset;
5947 MonoJumpInfo *patch_info;
5960 code_size = info->code_size;
5962 unwind_ops = info->unwind_ops;
5964 #ifdef __native_client_codegen__
5965 mono_nacl_fix_patches (code, ji);
5970 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5972 emit_section_change (acfg, ".text", 0);
5973 emit_global (acfg, start_symbol, TRUE);
5974 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
5975 emit_label (acfg, start_symbol);
5977 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5978 emit_label (acfg, symbol);
5981 * The code should access everything through the GOT, so we pass
5984 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5986 emit_symbol_size (acfg, start_symbol, ".");
5989 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5990 emit_label (acfg, end_symbol);
5995 /* Sort relocations */
5996 patches = g_ptr_array_new ();
5997 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5998 if (patch_info->type != MONO_PATCH_INFO_NONE)
5999 g_ptr_array_add (patches, patch_info);
6000 g_ptr_array_sort (patches, compare_patches);
6002 buf_size = patches->len * 128 + 128;
6003 buf = g_malloc (buf_size);
6006 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6007 g_assert (p - buf < buf_size);
6009 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6011 info_offset = add_to_blob (acfg, buf, p - buf);
6013 emit_section_change (acfg, RODATA_SECT, 0);
6014 emit_global (acfg, symbol, FALSE);
6015 emit_label (acfg, symbol);
6017 emit_int32 (acfg, info_offset);
6021 guint32 encoded_len;
6025 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6027 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6028 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6031 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6032 emit_int32 (acfg, uw_offset);
6035 /* Emit debug info */
6039 sprintf (symbol, "%s", name);
6040 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6043 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6047 static G_GNUC_UNUSED void
6048 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6050 emit_trampoline_full (acfg, got_offset, info, FALSE);
6054 emit_trampolines (MonoAotCompile *acfg)
6057 char end_symbol [256];
6058 int i, tramp_got_offset;
6059 MonoAotTrampoline ntype;
6060 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6064 if (!acfg->aot_opts.full_aot)
6067 g_assert (acfg->image->assembly);
6069 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6070 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6071 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6072 MonoTrampInfo *info;
6075 * Emit the generic trampolines.
6077 * We could save some code by treating the generic trampolines as a wrapper
6078 * method, but that approach has its own complexities, so we choose the simpler
6081 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6082 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6083 #ifdef DISABLE_REMOTING
6084 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6087 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6088 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6091 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6092 emit_trampoline (acfg, acfg->got_offset, info);
6095 mono_arch_get_nullified_class_init_trampoline (&info);
6096 emit_trampoline (acfg, acfg->got_offset, info);
6097 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6098 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6099 emit_trampoline (acfg, acfg->got_offset, info);
6100 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6101 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6102 emit_trampoline (acfg, acfg->got_offset, info);
6104 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6105 emit_trampoline (acfg, acfg->got_offset, info);
6108 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6109 emit_trampoline (acfg, acfg->got_offset, info);
6111 /* Emit the exception related code pieces */
6112 mono_arch_get_restore_context (&info, TRUE);
6113 emit_trampoline (acfg, acfg->got_offset, info);
6114 mono_arch_get_call_filter (&info, TRUE);
6115 emit_trampoline (acfg, acfg->got_offset, info);
6116 mono_arch_get_throw_exception (&info, TRUE);
6117 emit_trampoline (acfg, acfg->got_offset, info);
6118 mono_arch_get_rethrow_exception (&info, TRUE);
6119 emit_trampoline (acfg, acfg->got_offset, info);
6120 mono_arch_get_throw_corlib_exception (&info, TRUE);
6121 emit_trampoline (acfg, acfg->got_offset, info);
6123 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6124 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6126 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6128 /* Create a separate out trampoline for more information in stack traces */
6129 info->name = g_strdup ("gsharedvt_out_trampoline");
6130 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6134 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6136 GSList *l = mono_arch_get_trampolines (TRUE);
6139 MonoTrampInfo *info = l->data;
6141 emit_trampoline (acfg, acfg->got_offset, info);
6147 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6150 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6151 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6152 emit_trampoline (acfg, acfg->got_offset, info);
6154 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6155 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6156 emit_trampoline (acfg, acfg->got_offset, info);
6159 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6160 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6161 emit_trampoline (acfg, acfg->got_offset, info);
6167 /* delegate_invoke_impl trampolines */
6168 l = mono_arch_get_delegate_invoke_impls ();
6170 MonoTrampInfo *info = l->data;
6172 emit_trampoline (acfg, acfg->got_offset, info);
6177 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6179 /* Emit trampolines which are numerous */
6182 * These include the following:
6183 * - specific trampolines
6184 * - static rgctx invoke trampolines
6186 * These trampolines have the same code, they are parameterized by GOT
6188 * They are defined in this file, in the arch_... routines instead of
6189 * in tramp-<ARCH>.c, since it is easier to do it this way.
6193 * When running in aot-only mode, we can't create specific trampolines at
6194 * runtime, so we create a few, and save them in the AOT file.
6195 * Normal trampolines embed their argument as a literal inside the
6196 * trampoline code, we can't do that here, so instead we embed an offset
6197 * which needs to be added to the trampoline address to get the address of
6198 * the GOT slot which contains the argument value.
6199 * The generated trampolines jump to the generic trampolines using another
6200 * GOT slot, which will be setup by the AOT loader to point to the
6201 * generic trampoline code of the given type.
6205 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6209 emit_section_change (acfg, ".text", 0);
6211 tramp_got_offset = acfg->got_offset;
6213 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6215 case MONO_AOT_TRAMP_SPECIFIC:
6216 sprintf (symbol, "specific_trampolines");
6218 case MONO_AOT_TRAMP_STATIC_RGCTX:
6219 sprintf (symbol, "static_rgctx_trampolines");
6221 case MONO_AOT_TRAMP_IMT_THUNK:
6222 sprintf (symbol, "imt_thunks");
6224 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6225 sprintf (symbol, "gsharedvt_arg_trampolines");
6228 g_assert_not_reached ();
6231 sprintf (end_symbol, "%s_e", symbol);
6233 if (acfg->aot_opts.write_symbols)
6234 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6236 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6237 emit_label (acfg, symbol);
6239 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6241 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6245 case MONO_AOT_TRAMP_SPECIFIC:
6246 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6247 tramp_got_offset += 2;
6249 case MONO_AOT_TRAMP_STATIC_RGCTX:
6250 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6251 tramp_got_offset += 2;
6253 case MONO_AOT_TRAMP_IMT_THUNK:
6254 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6255 tramp_got_offset += 1;
6257 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6258 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6259 tramp_got_offset += 2;
6262 g_assert_not_reached ();
6264 #ifdef __native_client_codegen__
6265 /* align to avoid 32-byte boundary crossings */
6266 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6269 if (!acfg->trampoline_size [ntype]) {
6270 g_assert (tramp_size);
6271 acfg->trampoline_size [ntype] = tramp_size;
6275 emit_label (acfg, end_symbol);
6276 emit_int32 (acfg, 0);
6279 arch_emit_specific_trampoline_pages (acfg);
6281 /* Reserve some entries at the end of the GOT for our use */
6282 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6285 acfg->got_offset += acfg->num_trampoline_got_entries;
6289 str_begins_with (const char *str1, const char *str2)
6291 int len = strlen (str2);
6292 return strncmp (str1, str2, len) == 0;
6296 mono_aot_readonly_field_override (MonoClassField *field)
6299 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6300 char *p = rdv->name;
6302 len = strlen (field->parent->name_space);
6303 if (strncmp (p, field->parent->name_space, len))
6308 len = strlen (field->parent->name);
6309 if (strncmp (p, field->parent->name, len))
6314 if (strcmp (p, field->name))
6316 switch (rdv->type) {
6318 return &rdv->value.i1;
6320 return &rdv->value.i2;
6322 return &rdv->value.i4;
6331 add_readonly_value (MonoAotOptions *opts, const char *val)
6336 /* the format of val is:
6337 * namespace.typename.fieldname=type/value
6338 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6340 fval = strrchr (val, '/');
6342 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6345 tval = strrchr (val, '=');
6347 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6350 rdv = g_new0 (ReadOnlyValue, 1);
6351 rdv->name = g_malloc0 (tval - val + 1);
6352 memcpy (rdv->name, val, tval - val);
6355 if (strncmp (tval, "i1", 2) == 0) {
6356 rdv->value.i1 = atoi (fval);
6357 rdv->type = MONO_TYPE_I1;
6358 } else if (strncmp (tval, "i2", 2) == 0) {
6359 rdv->value.i2 = atoi (fval);
6360 rdv->type = MONO_TYPE_I2;
6361 } else if (strncmp (tval, "i4", 2) == 0) {
6362 rdv->value.i4 = atoi (fval);
6363 rdv->type = MONO_TYPE_I4;
6365 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6368 rdv->next = readonly_values;
6369 readonly_values = rdv;
6373 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6375 gchar **args, **ptr;
6377 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6378 for (ptr = args; ptr && *ptr; ptr ++) {
6379 const char *arg = *ptr;
6381 if (str_begins_with (arg, "outfile=")) {
6382 opts->outfile = g_strdup (arg + strlen ("outfile="));
6383 } else if (str_begins_with (arg, "llvm-outfile=")) {
6384 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6385 } else if (str_begins_with (arg, "save-temps")) {
6386 opts->save_temps = TRUE;
6387 } else if (str_begins_with (arg, "keep-temps")) {
6388 opts->save_temps = TRUE;
6389 } else if (str_begins_with (arg, "write-symbols")) {
6390 opts->write_symbols = TRUE;
6391 } else if (str_begins_with (arg, "no-write-symbols")) {
6392 opts->write_symbols = FALSE;
6393 } else if (str_begins_with (arg, "metadata-only")) {
6394 opts->metadata_only = TRUE;
6395 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6396 opts->bind_to_runtime_version = TRUE;
6397 } else if (str_begins_with (arg, "full")) {
6398 opts->full_aot = TRUE;
6399 } else if (str_begins_with (arg, "threads=")) {
6400 opts->nthreads = atoi (arg + strlen ("threads="));
6401 } else if (str_begins_with (arg, "static")) {
6402 opts->static_link = TRUE;
6403 opts->no_dlsym = TRUE;
6404 } else if (str_begins_with (arg, "asmonly")) {
6405 opts->asm_only = TRUE;
6406 } else if (str_begins_with (arg, "asmwriter")) {
6407 opts->asm_writer = TRUE;
6408 } else if (str_begins_with (arg, "nodebug")) {
6409 opts->nodebug = TRUE;
6410 } else if (str_begins_with (arg, "dwarfdebug")) {
6411 opts->dwarf_debug = TRUE;
6412 } else if (str_begins_with (arg, "nopagetrampolines")) {
6413 opts->use_trampolines_page = FALSE;
6414 } else if (str_begins_with (arg, "ntrampolines=")) {
6415 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6416 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6417 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6418 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6419 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6420 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6421 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6422 } else if (str_begins_with (arg, "autoreg")) {
6423 opts->autoreg = TRUE;
6424 } else if (str_begins_with (arg, "tool-prefix=")) {
6425 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6426 } else if (str_begins_with (arg, "soft-debug")) {
6427 opts->soft_debug = TRUE;
6428 } else if (str_begins_with (arg, "direct-pinvoke")) {
6429 opts->direct_pinvoke = TRUE;
6430 } else if (str_begins_with (arg, "direct-icalls")) {
6431 opts->direct_icalls = TRUE;
6432 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6433 } else if (str_begins_with (arg, "iphone-abi")) {
6434 // older full-aot users did depend on this.
6436 } else if (str_begins_with (arg, "no-direct-calls")) {
6437 opts->no_direct_calls = TRUE;
6438 } else if (str_begins_with (arg, "print-skipped")) {
6439 opts->print_skipped_methods = TRUE;
6440 } else if (str_begins_with (arg, "stats")) {
6442 } else if (str_begins_with (arg, "no-instances")) {
6443 opts->no_instances = TRUE;
6444 } else if (str_begins_with (arg, "log-generics")) {
6445 opts->log_generics = TRUE;
6446 } else if (str_begins_with (arg, "log-instances=")) {
6447 opts->log_instances = TRUE;
6448 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6449 } else if (str_begins_with (arg, "log-instances")) {
6450 opts->log_instances = TRUE;
6451 } else if (str_begins_with (arg, "internal-logfile=")) {
6452 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6453 } else if (str_begins_with (arg, "mtriple=")) {
6454 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6455 } else if (str_begins_with (arg, "llvm-path=")) {
6456 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6457 } else if (!strcmp (arg, "llvm")) {
6459 } else if (str_begins_with (arg, "readonly-value=")) {
6460 add_readonly_value (opts, arg + strlen ("readonly-value="));
6461 } else if (str_begins_with (arg, "info")) {
6462 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6464 } else if (str_begins_with (arg, "gc-maps")) {
6465 mini_gc_enable_gc_maps_for_aot ();
6466 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6467 printf ("Supported options for --aot:\n");
6468 printf (" outfile=\n");
6469 printf (" llvm-outfile=\n");
6470 printf (" save-temps\n");
6471 printf (" keep-temps\n");
6472 printf (" write-symbols\n");
6473 printf (" metadata-only\n");
6474 printf (" bind-to-runtime-version\n");
6476 printf (" threads=\n");
6477 printf (" static\n");
6478 printf (" asmonly\n");
6479 printf (" asmwriter\n");
6480 printf (" nodebug\n");
6481 printf (" dwarfdebug\n");
6482 printf (" ntrampolines=\n");
6483 printf (" nrgctx-trampolines=\n");
6484 printf (" nimt-trampolines=\n");
6485 printf (" ngsharedvt-trampolines=\n");
6486 printf (" autoreg\n");
6487 printf (" tool-prefix=\n");
6488 printf (" readonly-value=\n");
6489 printf (" soft-debug\n");
6490 printf (" gc-maps\n");
6491 printf (" print-skipped\n");
6492 printf (" no-instances\n");
6493 printf (" stats\n");
6495 printf (" help/?\n");
6498 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6503 if (opts->use_trampolines_page) {
6504 opts->ntrampolines = 0;
6505 opts->nrgctx_trampolines = 0;
6506 opts->nimt_trampolines = 0;
6507 opts->ngsharedvt_arg_trampolines = 0;
6513 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6515 MonoMethod *method = (MonoMethod*)key;
6516 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6517 MonoAotCompile *acfg = user_data;
6518 MonoJumpInfoToken *new_ji;
6520 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6521 new_ji->image = ji->image;
6522 new_ji->token = ji->token;
6523 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6527 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6529 if (klass->type_token)
6531 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6534 return can_encode_class (acfg, klass->element_class);
6539 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6541 if (method->wrapper_type) {
6542 switch (method->wrapper_type) {
6543 case MONO_WRAPPER_NONE:
6544 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6545 case MONO_WRAPPER_XDOMAIN_INVOKE:
6546 case MONO_WRAPPER_STFLD:
6547 case MONO_WRAPPER_LDFLD:
6548 case MONO_WRAPPER_LDFLDA:
6549 case MONO_WRAPPER_LDFLD_REMOTE:
6550 case MONO_WRAPPER_STFLD_REMOTE:
6551 case MONO_WRAPPER_STELEMREF:
6552 case MONO_WRAPPER_ISINST:
6553 case MONO_WRAPPER_PROXY_ISINST:
6554 case MONO_WRAPPER_ALLOC:
6555 case MONO_WRAPPER_REMOTING_INVOKE:
6556 case MONO_WRAPPER_UNKNOWN:
6557 case MONO_WRAPPER_WRITE_BARRIER:
6558 case MONO_WRAPPER_DELEGATE_INVOKE:
6559 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6560 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6561 case MONO_WRAPPER_SYNCHRONIZED:
6563 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6564 case MONO_WRAPPER_CASTCLASS: {
6565 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6574 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6578 if (!method->token) {
6579 /* The method is part of a constructed type like Int[,].Set (). */
6580 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6581 if (method->klass->rank)
6591 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6593 switch (patch_info->type) {
6594 case MONO_PATCH_INFO_METHOD:
6595 case MONO_PATCH_INFO_METHODCONST:
6596 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6597 MonoMethod *method = patch_info->data.method;
6599 return can_encode_method (acfg, method);
6601 case MONO_PATCH_INFO_VTABLE:
6602 case MONO_PATCH_INFO_CLASS_INIT:
6603 case MONO_PATCH_INFO_CLASS:
6604 case MONO_PATCH_INFO_IID:
6605 case MONO_PATCH_INFO_ADJUSTED_IID:
6606 if (!can_encode_class (acfg, patch_info->data.klass)) {
6607 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6611 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6612 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6613 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6618 case MONO_PATCH_INFO_RGCTX_FETCH: {
6619 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6621 if (!can_encode_method (acfg, entry->method))
6623 if (!can_encode_patch (acfg, entry->data))
6637 * AOT compile a given method.
6638 * This function might be called by multiple threads, so it must be thread-safe.
6641 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6644 MonoJumpInfo *patch_info;
6647 MonoMethod *wrapped;
6650 if (acfg->aot_opts.metadata_only)
6653 mono_acfg_lock (acfg);
6654 index = get_method_index (acfg, method);
6655 mono_acfg_unlock (acfg);
6657 /* fixme: maybe we can also precompile wrapper methods */
6658 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6659 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6660 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6661 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6665 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6668 wrapped = mono_marshal_method_from_wrapper (method);
6669 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6670 // FIXME: The wrapper should be generic too, but it is not
6673 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6676 InterlockedIncrement (&acfg->stats.mcount);
6679 if (method->is_generic || method->klass->generic_container) {
6680 InterlockedIncrement (&acfg->stats.genericcount);
6685 //acfg->aot_opts.print_skipped_methods = TRUE;
6688 * Since these methods are the only ones which are compiled with
6689 * AOT support, and they are not used by runtime startup/shutdown code,
6690 * the runtime will not see AOT methods during AOT compilation,so it
6691 * does not need to support them by creating a fake GOT etc.
6693 flags = JIT_FLAG_AOT;
6694 if (acfg->aot_opts.full_aot)
6695 flags |= JIT_FLAG_FULL_AOT;
6697 flags |= JIT_FLAG_LLVM;
6698 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6699 mono_loader_clear_error ();
6701 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6702 if (acfg->aot_opts.print_skipped_methods)
6703 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6704 InterlockedIncrement (&acfg->stats.genericcount);
6707 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6708 if (acfg->aot_opts.print_skipped_methods)
6709 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6710 /* Let the exception happen at runtime */
6714 if (cfg->disable_aot) {
6715 if (acfg->aot_opts.print_skipped_methods)
6716 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6717 InterlockedIncrement (&acfg->stats.ocount);
6718 mono_destroy_compile (cfg);
6721 cfg->method_index = index;
6723 /* Nullify patches which need no aot processing */
6724 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6725 switch (patch_info->type) {
6726 case MONO_PATCH_INFO_LABEL:
6727 case MONO_PATCH_INFO_BB:
6728 patch_info->type = MONO_PATCH_INFO_NONE;
6735 /* Collect method->token associations from the cfg */
6736 mono_acfg_lock (acfg);
6737 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6738 mono_acfg_unlock (acfg);
6739 g_hash_table_destroy (cfg->token_info_hash);
6740 cfg->token_info_hash = NULL;
6743 * Check for absolute addresses.
6746 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6747 switch (patch_info->type) {
6748 case MONO_PATCH_INFO_ABS:
6749 /* unable to handle this */
6758 if (acfg->aot_opts.print_skipped_methods)
6759 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6760 InterlockedIncrement (&acfg->stats.abscount);
6761 mono_destroy_compile (cfg);
6765 /* Lock for the rest of the code */
6766 mono_acfg_lock (acfg);
6769 * Check for methods/klasses we can't encode.
6772 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6773 if (!can_encode_patch (acfg, patch_info))
6778 if (acfg->aot_opts.print_skipped_methods)
6779 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6780 acfg->stats.ocount++;
6781 mono_destroy_compile (cfg);
6782 mono_acfg_unlock (acfg);
6786 if (method->is_inflated && acfg->aot_opts.log_instances) {
6787 if (acfg->instances_logfile)
6788 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6790 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6793 /* Adds generic instances referenced by this method */
6795 * The depth is used to avoid infinite loops when generic virtual recursion is
6798 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6799 if (!acfg->aot_opts.no_instances && depth < 32) {
6800 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6801 switch (patch_info->type) {
6802 case MONO_PATCH_INFO_METHOD: {
6803 MonoMethod *m = patch_info->data.method;
6804 if (m->is_inflated) {
6805 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6806 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6807 !method_has_type_vars (m)) {
6808 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6809 if (acfg->aot_opts.full_aot)
6810 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6812 add_extra_method_with_depth (acfg, m, depth + 1);
6813 add_types_from_method_header (acfg, m);
6816 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6818 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6819 add_extra_method_with_depth (acfg, m, depth + 1);
6822 case MONO_PATCH_INFO_VTABLE: {
6823 MonoClass *klass = patch_info->data.klass;
6825 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6826 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6829 case MONO_PATCH_INFO_SFLDA: {
6830 MonoClass *klass = patch_info->data.field->parent;
6832 /* The .cctor needs to run at runtime. */
6833 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6834 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6843 /* Determine whenever the method has GOT slots */
6844 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6845 switch (patch_info->type) {
6846 case MONO_PATCH_INFO_GOT_OFFSET:
6847 case MONO_PATCH_INFO_NONE:
6848 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6850 case MONO_PATCH_INFO_IMAGE:
6851 /* The assembly is stored in GOT slot 0 */
6852 if (patch_info->data.image != acfg->image)
6853 cfg->has_got_slots = TRUE;
6856 if (!is_plt_patch (patch_info))
6857 cfg->has_got_slots = TRUE;
6862 if (!cfg->has_got_slots)
6863 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6866 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6868 /* Make a copy of the patch info which is in the mempool */
6870 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6872 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6873 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6876 patches = new_patch_info;
6878 patches_end->next = new_patch_info;
6879 patches_end = new_patch_info;
6881 cfg->patch_info = patches;
6883 /* Make a copy of the unwind info */
6885 GSList *l, *unwind_ops;
6889 for (l = cfg->unwind_ops; l; l = l->next) {
6890 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6891 memcpy (op, l->data, sizeof (MonoUnwindOp));
6892 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6894 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6896 /* Make a copy of the argument/local info */
6898 MonoInst **args, **locals;
6899 MonoMethodSignature *sig;
6900 MonoMethodHeader *header;
6903 sig = mono_method_signature (method);
6904 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6905 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6906 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6907 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6911 header = mono_method_get_header (method);
6912 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6913 for (i = 0; i < header->num_locals; ++i) {
6914 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6915 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6917 cfg->locals = locals;
6920 /* Free some fields used by cfg to conserve memory */
6921 mono_mempool_destroy (cfg->mempool);
6922 cfg->mempool = NULL;
6923 g_free (cfg->varinfo);
6924 cfg->varinfo = NULL;
6928 mono_regstate_free (cfg->rs);
6932 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6934 while (index >= acfg->cfgs_size) {
6935 MonoCompile **new_cfgs;
6938 new_size = acfg->cfgs_size * 2;
6939 new_cfgs = g_new0 (MonoCompile*, new_size);
6940 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6941 g_free (acfg->cfgs);
6942 acfg->cfgs = new_cfgs;
6943 acfg->cfgs_size = new_size;
6945 acfg->cfgs [index] = cfg;
6947 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6950 if (cfg->orig_method->wrapper_type)
6951 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6954 mono_acfg_unlock (acfg);
6956 InterlockedIncrement (&acfg->stats.ccount);
6960 compile_thread_main (gpointer *user_data)
6962 MonoDomain *domain = user_data [0];
6963 MonoAotCompile *acfg = user_data [1];
6964 GPtrArray *methods = user_data [2];
6967 mono_thread_attach (domain);
6969 for (i = 0; i < methods->len; ++i)
6970 compile_method (acfg, g_ptr_array_index (methods, i));
6974 load_profile_files (MonoAotCompile *acfg)
6978 int file_index, res, method_index, i;
6981 GList *unordered, *l;
6986 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6988 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6993 infile = fopen (tmp, "r");
6996 printf ("Using profile data file '%s'\n", tmp);
7001 res = fscanf (infile, "%32s\n", ver);
7002 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7003 printf ("Profile file has wrong version or invalid.\n");
7010 MonoMethodDesc *desc;
7013 if (fgets (name, 1023, infile) == NULL)
7016 /* Kill the newline */
7017 if (strlen (name) > 0)
7018 name [strlen (name) - 1] = '\0';
7020 desc = mono_method_desc_new (name, TRUE);
7022 method = mono_method_desc_search_in_image (desc, acfg->image);
7024 if (method && mono_method_get_token (method)) {
7025 token = mono_method_get_token (method);
7026 method_index = mono_metadata_token_index (token) - 1;
7029 for (i = 0; i < acfg->method_order->len; ++i) {
7030 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7036 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7038 //printf ("No method found matching '%s'.\n", name);
7044 /* Add missing methods */
7046 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7048 for (i = 0; i < acfg->method_order->len; ++i) {
7049 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7055 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7057 unordered = g_list_reverse (unordered);
7058 for (l = unordered; l; l = l->next)
7059 g_ptr_array_add (acfg->method_order, l->data);
7062 /* Used by the LLVM backend */
7064 mono_aot_get_got_offset (MonoJumpInfo *ji)
7066 return get_got_offset (llvm_acfg, TRUE, ji);
7070 mono_aot_get_method_name (MonoCompile *cfg)
7072 if (llvm_acfg->aot_opts.static_link)
7073 /* Include the assembly name too to avoid duplicate symbol errors */
7074 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7076 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7080 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7082 return is_direct_callable (llvm_acfg, NULL, patch_info);
7086 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7088 MonoPltEntry *plt_entry;
7090 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7091 plt_entry->llvm_used = FALSE;
7095 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7097 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7098 MonoPltEntry *plt_entry;
7101 ji->data.target = data;
7103 if (!can_encode_patch (llvm_acfg, ji))
7106 plt_entry = get_plt_entry (llvm_acfg, ji);
7107 plt_entry->llvm_used = TRUE;
7109 #if defined(TARGET_MACH)
7110 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7112 return g_strdup_printf (plt_entry->llvm_symbol);
7117 mono_aot_get_method_index (MonoMethod *method)
7119 g_assert (llvm_acfg);
7120 return get_method_index (llvm_acfg, method);
7124 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7128 mono_acfg_lock (llvm_acfg);
7129 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7130 mono_acfg_unlock (llvm_acfg);
7140 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7144 emit_llvm_file (MonoAotCompile *acfg)
7146 char *command, *opts, *tempbc, *output_fname;
7148 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7149 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7153 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7154 * a lot of time, and doesn't seem to save much space.
7155 * The following optimizations cannot be enabled:
7157 * - 'jump-threading' changes our blockaddress references to int constants.
7158 * - 'basiccg' fails because it contains:
7159 * if (CS && !isa<IntrinsicInst>(II)) {
7160 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7161 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7162 * The opt list below was produced by taking the output of:
7163 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7164 * then removing tailcallelim + the global opts.
7165 * strip-dead-prototypes deletes unused intrinsics definitions.
7167 opts = g_strdup ("-instcombine -simplifycfg");
7168 //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");
7169 /* The dse pass is disabled because of #13734 and #17616 */
7171 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7172 * // If we have no DataLayout information around, then the size of the store
7173 * // is inferrable from the pointee type. If they are the same type, then
7174 * // we know that the store is safe.
7175 * if (AA.getDataLayout() == 0 &&
7176 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7177 * return OverwriteComplete;
7178 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7180 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");
7182 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7183 aot_printf (acfg, "Executing opt: %s\n", command);
7184 if (system (command) != 0)
7189 if (!acfg->llc_args)
7190 acfg->llc_args = g_string_new ("");
7192 /* Verbose asm slows down llc greatly */
7193 g_string_append (acfg->llc_args, " -asm-verbose=false");
7195 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7197 if (acfg->aot_opts.mtriple)
7198 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7200 if (acfg->llvm_separate)
7201 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7203 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7204 /* ios requires PIC code now */
7205 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7207 if (llvm_acfg->aot_opts.static_link)
7208 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7210 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7212 unlink (acfg->tmpfname);
7214 if (acfg->llvm_separate) {
7215 if (acfg->llvm_owriter) {
7216 /* Emit an object file directly */
7217 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7218 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7220 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7223 output_fname = g_strdup (acfg->tmpfname);
7225 command = g_strdup_printf ("%sllc %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7227 aot_printf (acfg, "Executing llc: %s\n", command);
7229 if (system (command) != 0)
7236 emit_code (MonoAotCompile *acfg)
7238 int oindex, i, prev_index;
7241 #if defined(TARGET_POWERPC64)
7242 sprintf (symbol, ".Lgot_addr");
7243 emit_section_change (acfg, ".text", 0);
7244 emit_alignment (acfg, 8);
7245 emit_label (acfg, symbol);
7246 emit_pointer (acfg, acfg->got_symbol);
7250 * This global symbol is used to compute the address of each method using the
7251 * code_offsets array. It is also used to compute the memory ranges occupied by
7252 * AOT code, so it must be equal to the address of the first emitted method.
7254 emit_section_change (acfg, ".text", 0);
7255 emit_alignment_code (acfg, 8);
7257 for (i = 0; i < acfg->nmethods; ++i) {
7258 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7259 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7264 if (!acfg->methods_symbol) {
7265 sprintf (symbol, "methods");
7266 emit_label (acfg, symbol);
7267 acfg->methods_symbol = g_strdup (symbol);
7269 emit_label (acfg, "jit_code_start");
7272 * Emit some padding so the local symbol for the first method doesn't have the
7273 * same address as 'methods'.
7275 #if defined(__default_codegen__)
7276 emit_padding (acfg, 16);
7277 #elif defined(__native_client_codegen__)
7279 const int kPaddingSize = 16;
7280 guint8 pad_buffer[kPaddingSize];
7281 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7282 emit_bytes (acfg, pad_buffer, kPaddingSize);
7286 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7290 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7292 cfg = acfg->cfgs [i];
7297 method = cfg->orig_method;
7299 /* Emit unbox trampoline */
7300 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7301 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7303 emit_section_change (acfg, ".text", 0);
7304 #ifdef __native_client_codegen__
7305 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7308 if (acfg->thumb_mixed && cfg->compile_llvm) {
7309 emit_set_thumb_mode (acfg);
7310 fprintf (acfg->fp, "\n.thumb_func\n");
7313 emit_label (acfg, symbol);
7315 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7317 if (acfg->thumb_mixed && cfg->compile_llvm)
7318 emit_set_arm_mode (acfg);
7321 if (cfg->compile_llvm)
7322 acfg->stats.llvm_count ++;
7324 emit_method_code (acfg, cfg);
7327 sprintf (symbol, "methods_end");
7328 emit_section_change (acfg, ".text", 0);
7329 emit_alignment_code (acfg, 8);
7330 emit_label (acfg, symbol);
7332 emit_label (acfg, "jit_code_end");
7334 /* To distinguish it from the next symbol */
7335 emit_padding (acfg, 4);
7338 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7339 * from optimizing them away, since it doesn't see that code_offsets references them.
7340 * JITted methods don't need this since they are referenced using assembler local
7342 * FIXME: This is why write-symbols doesn't work on OSX ?
7344 if (acfg->llvm && acfg->need_no_dead_strip) {
7345 fprintf (acfg->fp, "\n");
7346 for (i = 0; i < acfg->nmethods; ++i) {
7347 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7348 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7353 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7354 * This is PIE code, and the linker can update it if needed.
7356 sprintf (symbol, "method_addresses");
7357 emit_section_change (acfg, ".text", 1);
7358 emit_alignment_code (acfg, 8);
7359 emit_label (acfg, symbol);
7360 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7361 emit_unset_mode (acfg);
7362 if (acfg->need_no_dead_strip)
7363 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7365 for (i = 0; i < acfg->nmethods; ++i) {
7366 #ifdef MONO_ARCH_AOT_SUPPORTED
7370 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7372 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7376 sprintf (symbol, "method_addresses_end");
7377 emit_label (acfg, symbol);
7380 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7381 sprintf (symbol, "unbox_trampolines");
7382 emit_section_change (acfg, RODATA_SECT, 0);
7383 emit_alignment (acfg, 8);
7384 emit_label (acfg, symbol);
7387 for (i = 0; i < acfg->nmethods; ++i) {
7392 cfg = acfg->cfgs [i];
7396 method = cfg->orig_method;
7398 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7399 index = get_method_index (acfg, method);
7401 emit_int32 (acfg, index);
7402 /* Make sure the table is sorted by index */
7403 g_assert (index > prev_index);
7407 sprintf (symbol, "unbox_trampolines_end");
7408 emit_label (acfg, symbol);
7409 emit_int32 (acfg, 0);
7411 /* Emit a separate table with the trampoline addresses/offsets */
7412 sprintf (symbol, "unbox_trampoline_addresses");
7413 emit_section_change (acfg, ".text", 0);
7414 emit_alignment_code (acfg, 8);
7415 emit_label (acfg, symbol);
7417 for (i = 0; i < acfg->nmethods; ++i) {
7422 cfg = acfg->cfgs [i];
7426 method = cfg->orig_method;
7428 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7429 #ifdef MONO_ARCH_AOT_SUPPORTED
7432 index = get_method_index (acfg, method);
7433 sprintf (symbol, "ut_%d", index);
7435 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7442 emit_info (MonoAotCompile *acfg)
7448 offsets = g_new0 (gint32, acfg->nmethods);
7450 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7451 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7453 if (acfg->cfgs [i]) {
7454 emit_method_info (acfg, acfg->cfgs [i]);
7455 offsets [i] = acfg->cfgs [i]->method_info_offset;
7461 sprintf (symbol, "method_info_offsets");
7462 emit_section_change (acfg, RODATA_SECT, 1);
7463 emit_alignment (acfg, 8);
7464 emit_label (acfg, symbol);
7466 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7471 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7473 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7474 #define mix(a,b,c) { \
7475 a -= c; a ^= rot(c, 4); c += b; \
7476 b -= a; b ^= rot(a, 6); a += c; \
7477 c -= b; c ^= rot(b, 8); b += a; \
7478 a -= c; a ^= rot(c,16); c += b; \
7479 b -= a; b ^= rot(a,19); a += c; \
7480 c -= b; c ^= rot(b, 4); b += a; \
7482 #define final(a,b,c) { \
7483 c ^= b; c -= rot(b,14); \
7484 a ^= c; a -= rot(c,11); \
7485 b ^= a; b -= rot(a,25); \
7486 c ^= b; c -= rot(b,16); \
7487 a ^= c; a -= rot(c,4); \
7488 b ^= a; b -= rot(a,14); \
7489 c ^= b; c -= rot(b,24); \
7493 mono_aot_type_hash (MonoType *t1)
7495 guint hash = t1->type;
7497 hash |= t1->byref << 6; /* do not collide with t1->type values */
7499 case MONO_TYPE_VALUETYPE:
7500 case MONO_TYPE_CLASS:
7501 case MONO_TYPE_SZARRAY:
7502 /* check if the distribution is good enough */
7503 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7505 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7506 case MONO_TYPE_ARRAY:
7507 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7508 case MONO_TYPE_GENERICINST:
7509 return ((hash << 5) - hash) ^ 0;
7516 * mono_aot_method_hash:
7518 * Return a hash code for methods which only depends on metadata.
7521 mono_aot_method_hash (MonoMethod *method)
7523 MonoMethodSignature *sig;
7527 guint32 *hashes_start, *hashes;
7529 MonoGenericInst *ginst = NULL;
7531 /* Similar to the hash in mono_method_get_imt_slot () */
7533 sig = mono_method_signature (method);
7535 if (method->is_inflated)
7536 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7538 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7539 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7540 hashes = hashes_start;
7542 /* Some wrappers are assigned to random classes */
7543 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7544 klass = method->klass;
7546 klass = mono_defaults.object_class;
7548 if (!method->wrapper_type) {
7549 char *full_name = mono_type_full_name (&klass->byval_arg);
7551 hashes [0] = mono_metadata_str_hash (full_name);
7555 hashes [0] = mono_metadata_str_hash (klass->name);
7556 hashes [1] = mono_metadata_str_hash (klass->name_space);
7558 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7559 /* The method name includes a stringified pointer */
7562 hashes [2] = mono_metadata_str_hash (method->name);
7563 hashes [3] = method->wrapper_type;
7564 hashes [4] = mono_aot_type_hash (sig->ret);
7566 for (i = 0; i < sig->param_count; i++) {
7567 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7570 for (i = 0; i < ginst->type_argc; ++i)
7571 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7573 g_assert (hindex == hashes_count);
7575 /* Setup internal state */
7576 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7578 /* Handle most of the hashes */
7579 while (hashes_count > 3) {
7588 /* Handle the last 3 hashes (all the case statements fall through) */
7589 switch (hashes_count) {
7590 case 3 : c += hashes [2];
7591 case 2 : b += hashes [1];
7592 case 1 : a += hashes [0];
7594 case 0: /* nothing left to add */
7598 free (hashes_start);
7607 * mono_aot_get_array_helper_from_wrapper;
7609 * Get the helper method in Array called by an array wrapper method.
7612 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7616 MonoGenericContext ctx;
7617 MonoType *args [16];
7618 char *mname, *iname, *s, *s2, *helper_name = NULL;
7620 prefix = "System.Collections.Generic";
7621 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7622 s2 = strstr (s, "`1.");
7628 //printf ("X: %s %s\n", iname, mname);
7630 if (!strcmp (iname, "IList"))
7631 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7633 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7634 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7636 g_free (helper_name);
7639 if (m->is_generic) {
7641 memset (&ctx, 0, sizeof (ctx));
7642 args [0] = &method->klass->element_class->byval_arg;
7643 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7644 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7645 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7651 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7653 typedef struct HashEntry {
7654 guint32 key, value, index;
7655 struct HashEntry *next;
7659 * emit_extra_methods:
7661 * Emit methods which are not in the METHOD table, like wrappers.
7664 emit_extra_methods (MonoAotCompile *acfg)
7666 int i, table_size, buf_size;
7669 guint32 *info_offsets;
7672 HashEntry *entry, *new_entry;
7673 int nmethods, max_chain_length;
7676 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7678 /* Emit method info */
7680 for (i = 0; i < acfg->extra_methods->len; ++i) {
7681 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7682 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7688 p = buf = g_malloc (buf_size);
7692 method = cfg->method_to_register;
7694 encode_method_ref (acfg, method, p, &p);
7696 g_assert ((p - buf) < buf_size);
7698 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7703 * Construct a chained hash table for mapping indexes in extra_method_info to
7706 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7707 table = g_ptr_array_sized_new (table_size);
7708 for (i = 0; i < table_size; ++i)
7709 g_ptr_array_add (table, NULL);
7710 chain_lengths = g_new0 (int, table_size);
7711 max_chain_length = 0;
7712 for (i = 0; i < acfg->extra_methods->len; ++i) {
7713 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7714 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7720 key = info_offsets [i];
7721 value = get_method_index (acfg, method);
7723 hash = mono_aot_method_hash (method) % table_size;
7724 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7726 chain_lengths [hash] ++;
7727 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7729 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7730 new_entry->key = key;
7731 new_entry->value = value;
7733 entry = g_ptr_array_index (table, hash);
7734 if (entry == NULL) {
7735 new_entry->index = hash;
7736 g_ptr_array_index (table, hash) = new_entry;
7739 entry = entry->next;
7741 entry->next = new_entry;
7742 new_entry->index = table->len;
7743 g_ptr_array_add (table, new_entry);
7747 //printf ("MAX: %d\n", max_chain_length);
7749 /* Emit the table */
7750 sprintf (symbol, "extra_method_table");
7751 emit_section_change (acfg, RODATA_SECT, 0);
7752 emit_alignment (acfg, 8);
7753 emit_label (acfg, symbol);
7755 emit_int32 (acfg, table_size);
7756 for (i = 0; i < table->len; ++i) {
7757 HashEntry *entry = g_ptr_array_index (table, i);
7759 if (entry == NULL) {
7760 emit_int32 (acfg, 0);
7761 emit_int32 (acfg, 0);
7762 emit_int32 (acfg, 0);
7764 //g_assert (entry->key > 0);
7765 emit_int32 (acfg, entry->key);
7766 emit_int32 (acfg, entry->value);
7768 emit_int32 (acfg, entry->next->index);
7770 emit_int32 (acfg, 0);
7775 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7776 * This is used by mono_aot_find_jit_info ().
7778 sprintf (symbol, "extra_method_info_offsets");
7779 emit_section_change (acfg, RODATA_SECT, 0);
7780 emit_alignment (acfg, 8);
7781 emit_label (acfg, symbol);
7783 emit_int32 (acfg, acfg->extra_methods->len);
7784 for (i = 0; i < acfg->extra_methods->len; ++i) {
7785 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7787 emit_int32 (acfg, get_method_index (acfg, method));
7788 emit_int32 (acfg, info_offsets [i]);
7793 emit_exception_info (MonoAotCompile *acfg)
7799 offsets = g_new0 (gint32, acfg->nmethods);
7800 for (i = 0; i < acfg->nmethods; ++i) {
7801 if (acfg->cfgs [i]) {
7802 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7803 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7809 sprintf (symbol, "ex_info_offsets");
7810 emit_section_change (acfg, RODATA_SECT, 1);
7811 emit_alignment (acfg, 8);
7812 emit_label (acfg, symbol);
7814 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7819 emit_unwind_info (MonoAotCompile *acfg)
7825 * The unwind info contains a lot of duplicates so we emit each unique
7826 * entry once, and only store the offset from the start of the table in the
7830 sprintf (symbol, "unwind_info");
7831 emit_section_change (acfg, RODATA_SECT, 1);
7832 emit_alignment (acfg, 8);
7833 emit_label (acfg, symbol);
7835 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7836 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7837 guint8 *unwind_info;
7838 guint32 unwind_info_len;
7842 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7845 encode_value (unwind_info_len, p, &p);
7846 emit_bytes (acfg, buf, p - buf);
7847 emit_bytes (acfg, unwind_info, unwind_info_len);
7849 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7854 emit_class_info (MonoAotCompile *acfg)
7860 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7861 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7862 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7864 sprintf (symbol, "class_info_offsets");
7865 emit_section_change (acfg, RODATA_SECT, 1);
7866 emit_alignment (acfg, 8);
7867 emit_label (acfg, symbol);
7869 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7873 typedef struct ClassNameTableEntry {
7874 guint32 token, index;
7875 struct ClassNameTableEntry *next;
7876 } ClassNameTableEntry;
7879 emit_class_name_table (MonoAotCompile *acfg)
7882 guint32 token, hash;
7887 ClassNameTableEntry *entry, *new_entry;
7890 * Construct a chained hash table for mapping class names to typedef tokens.
7892 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7893 table = g_ptr_array_sized_new (table_size);
7894 for (i = 0; i < table_size; ++i)
7895 g_ptr_array_add (table, NULL);
7896 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7898 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7899 klass = mono_class_get_checked (acfg->image, token, &error);
7901 mono_error_cleanup (&error);
7904 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7905 hash = mono_metadata_str_hash (full_name) % table_size;
7908 /* FIXME: Allocate from the mempool */
7909 new_entry = g_new0 (ClassNameTableEntry, 1);
7910 new_entry->token = token;
7912 entry = g_ptr_array_index (table, hash);
7913 if (entry == NULL) {
7914 new_entry->index = hash;
7915 g_ptr_array_index (table, hash) = new_entry;
7918 entry = entry->next;
7920 entry->next = new_entry;
7921 new_entry->index = table->len;
7922 g_ptr_array_add (table, new_entry);
7926 /* Emit the table */
7927 sprintf (symbol, "class_name_table");
7928 emit_section_change (acfg, RODATA_SECT, 0);
7929 emit_alignment (acfg, 8);
7930 emit_label (acfg, symbol);
7932 /* FIXME: Optimize memory usage */
7933 g_assert (table_size < 65000);
7934 emit_int16 (acfg, table_size);
7935 g_assert (table->len < 65000);
7936 for (i = 0; i < table->len; ++i) {
7937 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7939 if (entry == NULL) {
7940 emit_int16 (acfg, 0);
7941 emit_int16 (acfg, 0);
7943 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7945 emit_int16 (acfg, entry->next->index);
7947 emit_int16 (acfg, 0);
7953 emit_image_table (MonoAotCompile *acfg)
7959 * The image table is small but referenced in a lot of places.
7960 * So we emit it at once, and reference its elements by an index.
7963 sprintf (symbol, "image_table");
7964 emit_section_change (acfg, RODATA_SECT, 1);
7965 emit_alignment (acfg, 8);
7966 emit_label (acfg, symbol);
7968 emit_int32 (acfg, acfg->image_table->len);
7969 for (i = 0; i < acfg->image_table->len; i++) {
7970 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7971 MonoAssemblyName *aname = &image->assembly->aname;
7973 /* FIXME: Support multi-module assemblies */
7974 g_assert (image->assembly->image == image);
7976 emit_string (acfg, image->assembly_name);
7977 emit_string (acfg, image->guid);
7978 emit_string (acfg, aname->culture ? aname->culture : "");
7979 emit_string (acfg, (const char*)aname->public_key_token);
7981 emit_alignment (acfg, 8);
7982 emit_int32 (acfg, aname->flags);
7983 emit_int32 (acfg, aname->major);
7984 emit_int32 (acfg, aname->minor);
7985 emit_int32 (acfg, aname->build);
7986 emit_int32 (acfg, aname->revision);
7991 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
7994 int i, first_plt_got_patch = 0, buf_size;
7996 guint32 *got_info_offsets;
7997 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
7999 /* Add the patches needed by the PLT to the GOT */
8001 acfg->plt_got_offset_base = acfg->got_offset;
8002 first_plt_got_patch = info->got_patches->len;
8003 for (i = 1; i < acfg->plt_offset; ++i) {
8004 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8006 g_ptr_array_add (info->got_patches, plt_entry->ji);
8008 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8011 acfg->got_offset += acfg->plt_offset;
8016 * - optimize offsets table.
8017 * - reduce number of exported symbols.
8018 * - emit info for a klass only once.
8019 * - determine when a method uses a GOT slot which is guaranteed to be already
8021 * - clean up and document the code.
8022 * - use String.Empty in class libs.
8025 /* Encode info required to decode shared GOT entries */
8026 buf_size = info->got_patches->len * 128;
8027 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8028 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8030 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8032 if (acfg->plt_offset)
8033 acfg->plt_got_info_offsets [0] = 0;
8035 for (i = 0; i < info->got_patches->len; ++i) {
8036 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8041 encode_value (ji->type, p, &p);
8043 encode_patch (acfg, ji, p, &p);
8044 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8045 g_assert (p - buf <= buf_size);
8046 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8048 if (!llvm && i >= first_plt_got_patch)
8049 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8050 acfg->stats.got_info_size += p - buf;
8053 /* Emit got_info_offsets table */
8055 sprintf (symbol, "llvm_got_info_offsets");
8057 sprintf (symbol, "got_info_offsets");
8058 emit_section_change (acfg, RODATA_SECT, 1);
8059 emit_alignment (acfg, 8);
8060 emit_label (acfg, symbol);
8062 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8063 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8067 emit_got (MonoAotCompile *acfg)
8071 /* Don't make GOT global so accesses to it don't need relocations */
8072 sprintf (symbol, "%s", acfg->got_symbol);
8073 emit_section_change (acfg, ".bss", 0);
8074 emit_alignment (acfg, 8);
8075 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8076 emit_label (acfg, symbol);
8077 if (acfg->got_offset > 0)
8078 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8080 sprintf (symbol, "got_end");
8081 emit_label (acfg, symbol);
8084 typedef struct GlobalsTableEntry {
8085 guint32 value, index;
8086 struct GlobalsTableEntry *next;
8087 } GlobalsTableEntry;
8090 emit_globals (MonoAotCompile *acfg)
8096 GlobalsTableEntry *entry, *new_entry;
8098 if (!acfg->aot_opts.static_link)
8102 * When static linking, we emit a table containing our globals.
8106 * Construct a chained hash table for mapping global names to their index in
8107 * the globals table.
8109 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8110 table = g_ptr_array_sized_new (table_size);
8111 for (i = 0; i < table_size; ++i)
8112 g_ptr_array_add (table, NULL);
8113 for (i = 0; i < acfg->globals->len; ++i) {
8114 char *name = g_ptr_array_index (acfg->globals, i);
8116 hash = mono_metadata_str_hash (name) % table_size;
8118 /* FIXME: Allocate from the mempool */
8119 new_entry = g_new0 (GlobalsTableEntry, 1);
8120 new_entry->value = i;
8122 entry = g_ptr_array_index (table, hash);
8123 if (entry == NULL) {
8124 new_entry->index = hash;
8125 g_ptr_array_index (table, hash) = new_entry;
8128 entry = entry->next;
8130 entry->next = new_entry;
8131 new_entry->index = table->len;
8132 g_ptr_array_add (table, new_entry);
8136 /* Emit the table */
8137 sprintf (symbol, ".Lglobals_hash");
8138 emit_section_change (acfg, RODATA_SECT, 0);
8139 emit_alignment (acfg, 8);
8140 emit_label (acfg, symbol);
8142 /* FIXME: Optimize memory usage */
8143 g_assert (table_size < 65000);
8144 emit_int16 (acfg, table_size);
8145 for (i = 0; i < table->len; ++i) {
8146 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8148 if (entry == NULL) {
8149 emit_int16 (acfg, 0);
8150 emit_int16 (acfg, 0);
8152 emit_int16 (acfg, entry->value + 1);
8154 emit_int16 (acfg, entry->next->index);
8156 emit_int16 (acfg, 0);
8160 /* Emit the names */
8161 for (i = 0; i < acfg->globals->len; ++i) {
8162 char *name = g_ptr_array_index (acfg->globals, i);
8164 sprintf (symbol, "name_%d", i);
8165 emit_section_change (acfg, RODATA_SECT, 1);
8167 emit_alignment (acfg, 4);
8169 emit_label (acfg, symbol);
8170 emit_string (acfg, name);
8173 /* Emit the globals table */
8174 sprintf (symbol, "globals");
8175 emit_section_change (acfg, ".data", 0);
8176 /* This is not a global, since it is accessed by the init function */
8177 emit_alignment (acfg, 8);
8178 emit_label (acfg, symbol);
8180 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8181 emit_pointer (acfg, symbol);
8183 for (i = 0; i < acfg->globals->len; ++i) {
8184 char *name = g_ptr_array_index (acfg->globals, i);
8186 sprintf (symbol, "name_%d", i);
8187 emit_pointer (acfg, symbol);
8189 g_assert (strlen (name) < sizeof (symbol));
8190 sprintf (symbol, "%s", name);
8191 emit_pointer (acfg, symbol);
8193 /* Null terminate the table */
8194 emit_int32 (acfg, 0);
8195 emit_int32 (acfg, 0);
8199 emit_autoreg (MonoAotCompile *acfg)
8204 * Emit a function into the .ctor section which will be called by the ELF
8205 * loader to register this module with the runtime.
8207 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8210 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8212 arch_emit_autoreg (acfg, symbol);
8218 emit_mem_end (MonoAotCompile *acfg)
8222 sprintf (symbol, "mem_end");
8223 emit_section_change (acfg, ".text", 1);
8224 emit_alignment_code (acfg, 8);
8225 emit_label (acfg, symbol);
8229 * Emit a structure containing all the information not stored elsewhere.
8232 emit_file_info (MonoAotCompile *acfg)
8237 const char *gc_name;
8240 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8242 if (acfg->aot_opts.bind_to_runtime_version) {
8243 build_info = mono_get_runtime_build_info ();
8244 emit_string_symbol (acfg, "runtime_version", build_info);
8245 g_free (build_info);
8247 emit_string_symbol (acfg, "runtime_version", "");
8250 /* Emit a string holding the assembly name */
8251 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8254 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8257 gc_name = mono_gc_get_gc_name ();
8258 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8260 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8261 emit_section_change (acfg, ".data", 0);
8262 emit_alignment (acfg, 8);
8263 emit_label (acfg, symbol);
8264 if (!acfg->aot_opts.static_link)
8265 emit_global (acfg, symbol, FALSE);
8267 /* The data emitted here must match MonoAotFileInfo. */
8269 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8270 emit_int32 (acfg, 0);
8273 * We emit pointers to our data structures instead of emitting global symbols which
8274 * point to them, to reduce the number of globals, and because using globals leads to
8275 * various problems (i.e. arm/thumb).
8277 emit_pointer (acfg, acfg->got_symbol);
8279 emit_pointer (acfg, acfg->llvm_got_symbol);
8281 emit_pointer (acfg, NULL);
8282 emit_pointer (acfg, acfg->methods_symbol);
8283 emit_pointer (acfg, "jit_code_start");
8284 emit_pointer (acfg, "jit_code_end");
8287 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8289 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8291 emit_pointer (acfg, NULL);
8293 emit_pointer (acfg, "blob");
8294 emit_pointer (acfg, "class_name_table");
8295 emit_pointer (acfg, "class_info_offsets");
8296 emit_pointer (acfg, "method_info_offsets");
8297 emit_pointer (acfg, "ex_info_offsets");
8298 emit_pointer (acfg, "method_addresses");
8299 emit_pointer (acfg, "extra_method_info_offsets");
8300 emit_pointer (acfg, "extra_method_table");
8301 emit_pointer (acfg, "got_info_offsets");
8303 emit_pointer (acfg, "llvm_got_info_offsets");
8305 emit_pointer (acfg, NULL);
8306 emit_pointer (acfg, "methods_end");
8307 emit_pointer (acfg, "unwind_info");
8308 emit_pointer (acfg, "mem_end");
8309 emit_pointer (acfg, "image_table");
8310 emit_pointer (acfg, "plt");
8311 emit_pointer (acfg, "plt_end");
8312 emit_pointer (acfg, "assembly_guid");
8313 emit_pointer (acfg, "runtime_version");
8314 if (acfg->num_trampoline_got_entries) {
8315 emit_pointer (acfg, "specific_trampolines");
8316 emit_pointer (acfg, "static_rgctx_trampolines");
8317 emit_pointer (acfg, "imt_thunks");
8318 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8320 emit_pointer (acfg, NULL);
8321 emit_pointer (acfg, NULL);
8322 emit_pointer (acfg, NULL);
8323 emit_pointer (acfg, NULL);
8325 if (acfg->thumb_mixed) {
8326 emit_pointer (acfg, "thumb_end");
8328 emit_pointer (acfg, NULL);
8330 if (acfg->aot_opts.static_link) {
8331 emit_pointer (acfg, "globals");
8333 emit_pointer (acfg, NULL);
8335 emit_pointer (acfg, "assembly_name");
8336 emit_pointer (acfg, "unbox_trampolines");
8337 emit_pointer (acfg, "unbox_trampolines_end");
8338 emit_pointer (acfg, "unbox_trampoline_addresses");
8340 emit_int32 (acfg, acfg->plt_got_offset_base);
8341 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8342 emit_int32 (acfg, acfg->plt_offset);
8343 emit_int32 (acfg, acfg->nmethods);
8344 emit_int32 (acfg, acfg->flags);
8345 emit_int32 (acfg, acfg->opts);
8346 emit_int32 (acfg, acfg->simd_opts);
8347 emit_int32 (acfg, gc_name_offset);
8349 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8350 emit_int32 (acfg, acfg->num_trampolines [i]);
8351 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8352 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8353 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8354 emit_int32 (acfg, acfg->trampoline_size [i]);
8355 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8357 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8362 memset (&t, 0, sizeof (MonoType));
8363 t.type = MONO_TYPE_R8;
8364 mono_type_size (&t, &align);
8365 emit_int32 (acfg, align);
8367 memset (&t, 0, sizeof (MonoType));
8368 t.type = MONO_TYPE_I8;
8369 mono_type_size (&t, &align);
8371 emit_int32 (acfg, align);
8374 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8375 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8377 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8378 emit_int32 (acfg, acfg->tramp_page_size);
8379 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8380 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8382 if (acfg->aot_opts.static_link) {
8386 * Emit a global symbol which can be passed by an embedding app to
8387 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8390 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8392 /* Get rid of characters which cannot occur in symbols */
8394 for (p = symbol; *p; ++p) {
8395 if (!(isalnum (*p) || *p == '_'))
8398 acfg->static_linking_symbol = g_strdup (symbol);
8399 emit_global_inner (acfg, symbol, FALSE);
8400 emit_alignment (acfg, sizeof (gpointer));
8401 emit_label (acfg, symbol);
8402 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8407 emit_blob (MonoAotCompile *acfg)
8411 sprintf (symbol, "blob");
8412 emit_section_change (acfg, RODATA_SECT, 1);
8413 emit_alignment (acfg, 8);
8414 emit_label (acfg, symbol);
8416 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8420 emit_objc_selectors (MonoAotCompile *acfg)
8424 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8429 * cat > foo.m << EOF
8432 * return @selector(print:);
8437 img_writer_emit_unset_mode (acfg->w);
8438 g_assert (acfg->fp);
8439 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8440 fprintf (acfg->fp, ".align 3\n");
8441 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8442 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8443 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8445 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8446 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8447 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8448 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8451 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8452 fprintf (acfg->fp, ".align 3\n");
8453 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8454 fprintf (acfg->fp, ".long 0\n");
8455 fprintf (acfg->fp, ".long 16\n");
8459 emit_dwarf_info (MonoAotCompile *acfg)
8461 #ifdef EMIT_DWARF_INFO
8465 /* DIEs for methods */
8466 for (i = 0; i < acfg->nmethods; ++i) {
8467 MonoCompile *cfg = acfg->cfgs [i];
8472 // FIXME: LLVM doesn't define .Lme_...
8473 if (cfg->compile_llvm)
8476 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8478 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 ()));
8484 collect_methods (MonoAotCompile *acfg)
8487 MonoImage *image = acfg->image;
8489 /* Collect methods */
8490 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8492 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8494 method = mono_get_method (acfg->image, token, NULL);
8497 aot_printerrf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8498 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8502 /* Load all methods eagerly to skip the slower lazy loading code */
8503 mono_class_setup_methods (method->klass);
8505 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8506 /* Compile the wrapper instead */
8507 /* We do this here instead of add_wrappers () because it is easy to do it here */
8508 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8512 /* FIXME: Some mscorlib methods don't have debug info */
8514 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8515 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8516 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8517 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8518 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8519 if (!mono_debug_lookup_method (method)) {
8520 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8527 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8528 add_method_with_index (acfg, method, i, FALSE);
8529 acfg->method_index ++;
8532 /* gsharedvt methods */
8533 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8535 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8537 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8540 method = mono_get_method (acfg->image, token, NULL);
8544 if (strcmp (method->name, "gshared2"))
8548 if (!strstr (method->klass->image->name, "mini"))
8551 if (method->is_generic || method->klass->generic_container) {
8552 MonoMethod *gshared;
8554 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8555 add_extra_method (acfg, gshared);
8559 add_generic_instances (acfg);
8561 if (acfg->aot_opts.full_aot)
8562 add_wrappers (acfg);
8567 compile_methods (MonoAotCompile *acfg)
8571 if (acfg->aot_opts.nthreads > 0) {
8576 gpointer *user_data;
8577 MonoMethod **methods;
8579 methods_len = acfg->methods->len;
8581 len = acfg->methods->len / acfg->aot_opts.nthreads;
8584 * Partition the list of methods into fragments, and hand it to threads to
8587 threads = g_ptr_array_new ();
8588 /* Make a copy since acfg->methods is modified by compile_method () */
8589 methods = g_new0 (MonoMethod*, methods_len);
8590 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8591 for (i = 0; i < methods_len; ++i)
8592 methods [i] = g_ptr_array_index (acfg->methods, i);
8594 while (i < methods_len) {
8595 frag = g_ptr_array_new ();
8596 for (j = 0; j < len; ++j) {
8597 if (i < methods_len) {
8598 g_ptr_array_add (frag, methods [i]);
8603 user_data = g_new0 (gpointer, 3);
8604 user_data [0] = mono_domain_get ();
8605 user_data [1] = acfg;
8606 user_data [2] = frag;
8608 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8609 g_ptr_array_add (threads, handle);
8613 for (i = 0; i < threads->len; ++i) {
8614 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8620 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8621 for (i = methods_len; i < acfg->methods->len; ++i) {
8622 /* This can new methods to acfg->methods */
8623 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8628 compile_asm (MonoAotCompile *acfg)
8630 char *command, *objfile;
8631 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8632 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8634 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8635 #define AS_OPTIONS "--64"
8636 #elif defined(TARGET_POWERPC64)
8637 #define AS_OPTIONS "-a64 -mppc64"
8638 #define LD_OPTIONS "-m elf64ppc"
8639 #elif defined(sparc) && SIZEOF_VOID_P == 8
8640 #define AS_OPTIONS "-xarch=v9"
8641 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8642 #define AS_OPTIONS "-arch i386"
8644 #define AS_OPTIONS ""
8647 #ifdef __native_client_codegen__
8648 #if defined(TARGET_AMD64)
8649 #define AS_NAME "nacl64-as"
8651 #define AS_NAME "nacl-as"
8653 #elif defined(TARGET_OSX)
8654 #define AS_NAME "clang -c -x assembler"
8656 #define AS_NAME "as"
8660 #define LD_OPTIONS ""
8664 #define LD_NAME "ld -shared -G"
8665 #elif defined(__ppc__) && defined(TARGET_MACH)
8666 #define LD_NAME "gcc -dynamiclib"
8667 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8668 #define LD_NAME "clang --shared"
8669 #elif defined(HOST_WIN32)
8670 #define LD_NAME "gcc -shared --dll"
8671 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8672 #define LD_NAME "clang -m32 -dynamiclib"
8675 if (acfg->aot_opts.asm_only) {
8676 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8677 if (acfg->aot_opts.static_link)
8678 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8679 if (acfg->llvm_separate)
8680 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8684 if (acfg->aot_opts.static_link) {
8685 if (acfg->aot_opts.outfile)
8686 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8688 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8690 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8692 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);
8693 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8694 if (system (command) != 0) {
8700 if (acfg->llvm_separate && !acfg->llvm_owriter) {
8701 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
8702 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8703 if (system (command) != 0) {
8712 if (acfg->aot_opts.static_link) {
8713 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8714 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8719 if (acfg->aot_opts.outfile)
8720 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8722 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8724 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8726 if (acfg->llvm_separate) {
8727 llvm_ofile = g_strdup (acfg->llvm_ofile);
8729 llvm_ofile = g_strdup ("");
8733 command = g_strdup_printf ("%s -o %s %s %s.o", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8735 command = g_strdup_printf ("%sld %s -shared -o %s %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile, acfg->tmpfname);
8737 aot_printf (acfg, "Executing the native linker: %s\n", command);
8738 if (system (command) != 0) {
8739 g_free (tmp_outfile_name);
8740 g_free (outfile_name);
8748 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8749 printf ("Stripping the binary: %s\n", com);
8753 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8755 * gas generates 'mapping symbols' each time code and data is mixed, which
8756 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8758 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8759 aot_printf (acfg, "Stripping the binary: %s\n", command);
8760 if (system (command) != 0) {
8761 g_free (tmp_outfile_name);
8762 g_free (outfile_name);
8769 rename (tmp_outfile_name, outfile_name);
8771 #if defined(TARGET_MACH)
8772 command = g_strdup_printf ("dsymutil %s", outfile_name);
8773 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8774 if (system (command) != 0) {
8779 if (!acfg->aot_opts.save_temps)
8782 g_free (tmp_outfile_name);
8783 g_free (outfile_name);
8786 if (acfg->aot_opts.save_temps)
8787 aot_printf (acfg, "Retained input file.\n");
8789 unlink (acfg->tmpfname);
8794 static void init_got_info (GotInfo *info)
8798 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8799 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8800 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8801 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8802 info->got_patches = g_ptr_array_new ();
8805 static MonoAotCompile*
8806 acfg_create (MonoAssembly *ass, guint32 opts)
8808 MonoImage *image = ass->image;
8809 MonoAotCompile *acfg;
8811 acfg = g_new0 (MonoAotCompile, 1);
8812 acfg->methods = g_ptr_array_new ();
8813 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8814 acfg->method_depth = g_hash_table_new (NULL, NULL);
8815 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8816 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8817 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8818 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8819 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8820 acfg->image_hash = g_hash_table_new (NULL, NULL);
8821 acfg->image_table = g_ptr_array_new ();
8822 acfg->globals = g_ptr_array_new ();
8823 acfg->image = image;
8825 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8826 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8827 acfg->mempool = mono_mempool_new ();
8828 acfg->extra_methods = g_ptr_array_new ();
8829 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8830 acfg->unwind_ops = g_ptr_array_new ();
8831 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8832 acfg->method_order = g_ptr_array_new ();
8833 acfg->export_names = g_hash_table_new (NULL, NULL);
8834 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8835 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8836 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8837 mono_mutex_init_recursive (&acfg->mutex);
8839 init_got_info (&acfg->got_info);
8840 init_got_info (&acfg->llvm_got_info);
8846 got_info_free (GotInfo *info)
8850 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8851 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8852 g_free (info->patch_to_got_offset_by_type);
8853 g_hash_table_destroy (info->patch_to_got_offset);
8854 g_ptr_array_free (info->got_patches, TRUE);
8858 acfg_free (MonoAotCompile *acfg)
8862 img_writer_destroy (acfg->w);
8863 for (i = 0; i < acfg->nmethods; ++i)
8865 g_free (acfg->cfgs [i]);
8866 g_free (acfg->cfgs);
8867 g_free (acfg->static_linking_symbol);
8868 g_free (acfg->got_symbol);
8869 g_free (acfg->plt_symbol);
8870 g_ptr_array_free (acfg->methods, TRUE);
8871 g_ptr_array_free (acfg->image_table, TRUE);
8872 g_ptr_array_free (acfg->globals, TRUE);
8873 g_ptr_array_free (acfg->unwind_ops, TRUE);
8874 g_hash_table_destroy (acfg->method_indexes);
8875 g_hash_table_destroy (acfg->method_depth);
8876 g_hash_table_destroy (acfg->plt_offset_to_entry);
8877 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8878 if (acfg->patch_to_plt_entry [i])
8879 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8881 g_free (acfg->patch_to_plt_entry);
8882 g_hash_table_destroy (acfg->method_to_cfg);
8883 g_hash_table_destroy (acfg->token_info_hash);
8884 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8885 g_hash_table_destroy (acfg->image_hash);
8886 g_hash_table_destroy (acfg->unwind_info_offsets);
8887 g_hash_table_destroy (acfg->method_label_hash);
8888 g_hash_table_destroy (acfg->export_names);
8889 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8890 g_hash_table_destroy (acfg->klass_blob_hash);
8891 g_hash_table_destroy (acfg->method_blob_hash);
8892 got_info_free (&acfg->got_info);
8893 got_info_free (&acfg->llvm_got_info);
8894 mono_mempool_destroy (acfg->mempool);
8899 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8901 MonoImage *image = ass->image;
8902 int i, res, all_sizes;
8903 MonoAotCompile *acfg;
8904 char *outfile_name, *tmp_outfile_name, *p;
8905 char llvm_stats_msg [256];
8909 acfg = acfg_create (ass, opts);
8911 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8912 acfg->aot_opts.write_symbols = TRUE;
8913 acfg->aot_opts.ntrampolines = 1024;
8914 acfg->aot_opts.nrgctx_trampolines = 1024;
8915 acfg->aot_opts.nimt_trampolines = 128;
8916 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8917 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8918 acfg->aot_opts.llvm_path = g_strdup ("");
8920 acfg->aot_opts.use_trampolines_page = TRUE;
8923 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8925 if (acfg->aot_opts.logfile) {
8926 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
8929 if (acfg->aot_opts.static_link)
8930 acfg->aot_opts.autoreg = TRUE;
8932 //acfg->aot_opts.print_skipped_methods = TRUE;
8934 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8935 if (opts & MONO_OPT_GSHAREDVT) {
8936 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
8941 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8943 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8944 if (acfg->aot_opts.full_aot) {
8945 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
8950 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8951 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8955 if (acfg->aot_opts.static_link)
8956 acfg->aot_opts.asm_writer = TRUE;
8958 if (acfg->aot_opts.soft_debug) {
8959 MonoDebugOptions *opt = mini_get_debug_options ();
8961 opt->mdb_optimizations = TRUE;
8962 opt->gen_seq_points_debug_data = TRUE;
8964 if (!mono_debug_enabled ()) {
8965 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
8968 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8971 if (mono_use_llvm || acfg->aot_opts.llvm) {
8973 acfg->aot_opts.asm_writer = TRUE;
8974 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8976 if (acfg->aot_opts.soft_debug) {
8977 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8983 if (!acfg->aot_opts.asm_only || acfg->aot_opts.llvm_outfile) {
8985 * Emit all LLVM code into a separate assembly/object file and link with it
8988 #if LLVM_API_VERSION >= 3
8989 acfg->llvm_separate = TRUE;
8990 if (!acfg->aot_opts.asm_only)
8991 acfg->llvm_owriter = TRUE;
8994 if (acfg->aot_opts.llvm_outfile && !acfg->llvm_separate) {
8995 aot_printerrf (acfg, "The llvm-outputfile= option is not supported on this platform.\n");
9000 if (acfg->aot_opts.full_aot)
9001 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9003 if (acfg->aot_opts.instances_logfile_path) {
9004 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9005 if (!acfg->instances_logfile) {
9006 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9011 load_profile_files (acfg);
9013 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9014 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9015 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9017 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9018 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9019 if (acfg->opts & MONO_OPT_GSHAREDVT)
9020 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9023 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9027 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9028 /* Get rid of characters which cannot occur in symbols */
9029 for (p = acfg->assembly_name_sym; *p; ++p) {
9030 if (!(isalnum (*p) || *p == '_'))
9034 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9035 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9036 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9038 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9040 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9041 if (acfg->llvm_separate)
9042 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9044 acfg->llvm_eh_frame_symbol = g_strdup ("mono_eh_frame");
9047 acfg->method_index = 1;
9051 if (acfg->aot_opts.full_aot)
9052 mono_set_partial_sharing_supported (TRUE);
9055 res = collect_methods (acfg);
9059 acfg->cfgs_size = acfg->methods->len + 32;
9060 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9062 /* PLT offset 0 is reserved for the PLT trampoline */
9063 acfg->plt_offset = 1;
9068 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, acfg->llvm_separate, acfg->llvm_separate);
9072 /* GOT offset 0 is reserved for the address of the current assembly */
9076 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9077 ji->type = MONO_PATCH_INFO_IMAGE;
9078 ji->data.image = acfg->image;
9080 get_got_offset (acfg, FALSE, ji);
9081 get_got_offset (acfg, TRUE, ji);
9083 /* Slot 1 is reserved for the mscorlib got addr */
9084 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9085 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9086 get_got_offset (acfg, FALSE, ji);
9087 get_got_offset (acfg, TRUE, ji);
9089 /* This is very common */
9090 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9091 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9092 get_got_offset (acfg, FALSE, ji);
9093 get_got_offset (acfg, TRUE, ji);
9095 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9096 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9097 get_got_offset (acfg, FALSE, ji);
9098 get_got_offset (acfg, TRUE, ji);
9103 compile_methods (acfg);
9107 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9115 if (acfg->aot_opts.asm_only) {
9116 if (acfg->aot_opts.outfile) {
9117 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9118 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9120 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9121 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9123 if (acfg->llvm_separate) {
9124 g_assert (acfg->aot_opts.llvm_outfile);
9125 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9128 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9129 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9130 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9131 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9134 res = emit_llvm_file (acfg);
9140 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9141 if (acfg->aot_opts.outfile)
9142 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9144 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9147 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9148 * it might be in another file system so the rename () won't work.
9150 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9152 acfg->fp = fopen (tmp_outfile_name, "w");
9154 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9158 acfg->w = img_writer_create (acfg->fp, TRUE);
9159 acfg->use_bin_writer = TRUE;
9161 if (acfg->llvm && !acfg->llvm_separate) {
9162 /* Append to the .s file created by llvm */
9163 /* FIXME: Use multiple files instead */
9164 acfg->fp = fopen (acfg->tmpfname, "a+");
9166 if (acfg->aot_opts.asm_only) {
9167 if (acfg->aot_opts.outfile)
9168 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9170 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9171 acfg->fp = fopen (acfg->tmpfname, "w+");
9173 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9174 acfg->fp = fdopen (i, "w+");
9177 if (acfg->fp == 0) {
9178 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9181 acfg->w = img_writer_create (acfg->fp, FALSE);
9183 tmp_outfile_name = NULL;
9184 outfile_name = NULL;
9187 /* Compute symbols for methods */
9188 for (i = 0; i < acfg->nmethods; ++i) {
9189 if (acfg->cfgs [i]) {
9190 MonoCompile *cfg = acfg->cfgs [i];
9191 int method_index = get_method_index (acfg, cfg->orig_method);
9193 if (COMPILE_LLVM (cfg))
9194 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9195 else if (acfg->global_symbols || acfg->llvm_separate)
9196 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9198 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9202 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9204 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9205 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9208 //acfg->gas_line_numbers = TRUE;
9211 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9212 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9213 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9216 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9219 img_writer_emit_start (acfg->w);
9222 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9224 if (acfg->thumb_mixed) {
9227 * This global symbol marks the end of THUMB code, and the beginning of ARM
9228 * code generated by our JIT.
9230 sprintf (symbol, "thumb_end");
9231 emit_section_change (acfg, ".text", 0);
9232 emit_alignment_code (acfg, 8);
9233 emit_label (acfg, symbol);
9234 emit_zero_bytes (acfg, 16);
9236 fprintf (acfg->fp, ".arm\n");
9243 emit_extra_methods (acfg);
9245 emit_trampolines (acfg);
9247 emit_class_name_table (acfg);
9249 emit_got_info (acfg, FALSE);
9251 emit_got_info (acfg, TRUE);
9253 emit_exception_info (acfg);
9255 emit_unwind_info (acfg);
9257 emit_class_info (acfg);
9261 emit_image_table (acfg);
9265 emit_file_info (acfg);
9269 emit_objc_selectors (acfg);
9271 emit_globals (acfg);
9273 emit_autoreg (acfg);
9276 emit_dwarf_info (acfg);
9277 mono_dwarf_writer_close (acfg->dwarf);
9280 emit_mem_end (acfg);
9282 if (acfg->need_pt_gnu_stack) {
9283 /* This is required so the .so doesn't have an executable stack */
9284 /* The bin writer already emits this */
9285 if (!acfg->use_bin_writer)
9286 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9291 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9294 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9296 strcpy (llvm_stats_msg, "");
9298 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;
9300 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",
9301 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9302 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9303 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9304 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9305 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9306 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9307 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9308 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9309 (int)(acfg->got_offset * sizeof (gpointer)));
9310 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9311 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9313 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9314 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9315 if (acfg->stats.genericcount)
9316 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9317 if (acfg->stats.abscount)
9318 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9319 if (acfg->stats.lmfcount)
9320 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9321 if (acfg->stats.ocount)
9322 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9325 res = img_writer_emit_writeout (acfg->w);
9330 if (acfg->use_bin_writer) {
9331 int err = rename (tmp_outfile_name, outfile_name);
9334 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9338 res = compile_asm (acfg);
9345 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9347 if (acfg->aot_opts.stats) {
9350 aot_printf (acfg, "GOT slot distribution:\n");
9351 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9352 if (acfg->stats.got_slot_types [i])
9353 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]);
9356 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);
9368 mono_aot_readonly_field_override (MonoClassField *field)
9374 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)