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-internals.h>
45 #include <mono/metadata/mempool-internals.h>
46 #include <mono/metadata/mono-endian.h>
47 #include <mono/metadata/threads-types.h>
48 #include <mono/utils/mono-logger-internals.h>
49 #include <mono/utils/mono-compiler.h>
50 #include <mono/utils/mono-time.h>
51 #include <mono/utils/mono-mmap.h>
52 #include <mono/utils/json.h>
54 #include "aot-compiler.h"
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
59 #include "mini-llvm.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
100 gboolean write_symbols;
101 gboolean metadata_only;
102 gboolean bind_to_runtime_version;
105 gboolean static_link;
109 gboolean dwarf_debug;
111 gboolean log_generics;
112 gboolean log_instances;
113 gboolean gen_seq_points_file;
114 gboolean direct_pinvoke;
115 gboolean direct_icalls;
116 gboolean no_direct_calls;
117 gboolean use_trampolines_page;
118 gboolean no_instances;
124 int nrgctx_trampolines;
125 int nimt_trampolines;
126 int ngsharedvt_arg_trampolines;
127 int nrgctx_fetch_trampolines;
128 gboolean print_skipped_methods;
135 char *instances_logfile_path;
140 typedef struct MonoAotStats {
141 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
142 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
143 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
144 int got_slots, offsets_size;
145 int got_slot_types [MONO_PATCH_INFO_NONE];
146 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
147 int jit_time, gen_time, link_time;
150 typedef struct GotInfo {
151 GHashTable *patch_to_got_offset;
152 GHashTable **patch_to_got_offset_by_type;
153 GPtrArray *got_patches;
156 typedef struct MonoAotCompile {
159 GHashTable *method_indexes;
160 GHashTable *method_depth;
163 GHashTable **patch_to_plt_entry;
164 GHashTable *plt_offset_to_entry;
165 //GHashTable *patch_to_got_offset;
166 //GHashTable **patch_to_got_offset_by_type;
167 //GPtrArray *got_patches;
168 GotInfo got_info, llvm_got_info;
169 GHashTable *image_hash;
170 GHashTable *method_to_cfg;
171 GHashTable *token_info_hash;
172 GHashTable *method_to_pinvoke_import;
173 GPtrArray *extra_methods;
174 GPtrArray *image_table;
176 GPtrArray *method_order;
177 GHashTable *export_names;
178 /* Maps MonoClass* -> blob offset */
179 GHashTable *klass_blob_hash;
180 /* Maps MonoMethod* -> blob offset */
181 GHashTable *method_blob_hash;
182 GHashTable *gsharedvt_in_signatures;
183 GHashTable *gsharedvt_out_signatures;
184 guint32 *plt_got_info_offsets;
185 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
186 /* Number of GOT entries reserved for trampolines */
187 guint32 num_trampoline_got_entries;
188 guint32 tramp_page_size;
190 guint32 table_offsets [MONO_AOT_TABLE_NUM];
191 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
192 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
193 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
194 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
196 MonoAotOptions aot_opts;
200 MonoMemPool *mempool;
203 char *static_linking_symbol;
205 gboolean gas_line_numbers;
206 /* Whenever to emit an object file directly from llc */
207 gboolean llvm_owriter;
209 MonoDwarfWriter *dwarf;
216 GHashTable *unwind_info_offsets;
217 GPtrArray *unwind_ops;
218 guint32 unwind_info_offset;
221 char *llvm_got_symbol;
223 char *llvm_eh_frame_symbol;
224 GHashTable *method_label_hash;
225 const char *temp_prefix;
226 const char *user_symbol_prefix;
227 const char *llvm_label_prefix;
228 const char *inst_directive;
230 guint32 label_generator;
232 gboolean has_jitted_code;
233 MonoAotFileFlags flags;
234 MonoDynamicStream blob;
235 gboolean blob_closed;
236 MonoClass **typespec_classes;
239 char *assembly_name_sym;
240 GHashTable *plt_entry_debug_sym_cache;
241 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
242 GHashTable *ginst_hash;
243 GHashTable *dwarf_ln_filenames;
244 gboolean global_symbols;
245 int objc_selector_index, objc_selector_index_2;
246 GPtrArray *objc_selectors;
247 GHashTable *objc_selector_to_index;
249 FILE *instances_logfile;
257 char *symbol, *llvm_symbol, *debug_sym;
259 gboolean jit_used, llvm_used;
262 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
263 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
265 /* This points to the current acfg in LLVM mode */
266 static MonoAotCompile *llvm_acfg;
268 #ifdef HAVE_ARRAY_ELEM_INIT
269 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
270 #define MSGSTRFIELD1(line) str##line
271 static const struct msgstr_t {
272 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
273 #include "patch-info.h"
276 #define PATCH_INFO(a,b) b,
277 #include "patch-info.h"
280 static const gint16 opidx [] = {
281 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
282 #include "patch-info.h"
286 static G_GNUC_UNUSED const char*
287 get_patch_name (int info)
289 return (const char*)&opstr + opidx [info];
293 #define PATCH_INFO(a,b) b,
294 static const char* const
295 patch_types [MONO_PATCH_INFO_NUM + 1] = {
296 #include "patch-info.h"
300 static G_GNUC_UNUSED const char*
301 get_patch_name (int info)
303 return patch_types [info];
309 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
312 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
315 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
321 output = acfg->logfile;
325 va_start (args, format);
326 vfprintf (output, format, args);
331 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
337 output = acfg->logfile;
341 va_start (args, format);
342 vfprintf (output, format, args);
347 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
352 if (mono_error_ok (error))
356 output = acfg->logfile;
360 va_start (args, format);
361 vfprintf (output, format, args);
363 mono_error_cleanup (error);
365 g_error ("FullAOT cannot continue if there are loader errors");
368 /* Wrappers around the image writer functions */
371 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
373 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
377 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
379 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
383 emit_label (MonoAotCompile *acfg, const char *name)
385 mono_img_writer_emit_label (acfg->w, name);
389 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
391 mono_img_writer_emit_bytes (acfg->w, buf, size);
395 emit_string (MonoAotCompile *acfg, const char *value)
397 mono_img_writer_emit_string (acfg->w, value);
401 emit_line (MonoAotCompile *acfg)
403 mono_img_writer_emit_line (acfg->w);
407 emit_alignment (MonoAotCompile *acfg, int size)
409 mono_img_writer_emit_alignment (acfg->w, size);
413 emit_alignment_code (MonoAotCompile *acfg, int size)
415 if (acfg->align_pad_value)
416 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
418 mono_img_writer_emit_alignment (acfg->w, size);
422 emit_padding (MonoAotCompile *acfg, int size)
427 if (acfg->align_pad_value) {
428 for (i = 0; i < 16; ++i)
429 buf [i] = acfg->align_pad_value;
431 memset (buf, 0, sizeof (buf));
434 for (i = 0; i < size; i += 16) {
436 emit_bytes (acfg, buf, size - i);
438 emit_bytes (acfg, buf, 16);
443 emit_pointer (MonoAotCompile *acfg, const char *target)
445 mono_img_writer_emit_pointer (acfg->w, target);
449 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
451 if (prefix [0] != '\0') {
452 char *s = g_strdup_printf ("%s%s", prefix, target);
453 mono_img_writer_emit_pointer (acfg->w, s);
456 mono_img_writer_emit_pointer (acfg->w, target);
461 emit_int16 (MonoAotCompile *acfg, int value)
463 mono_img_writer_emit_int16 (acfg->w, value);
467 emit_int32 (MonoAotCompile *acfg, int value)
469 mono_img_writer_emit_int32 (acfg->w, value);
473 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
475 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
479 emit_zero_bytes (MonoAotCompile *acfg, int num)
481 mono_img_writer_emit_zero_bytes (acfg->w, num);
485 emit_byte (MonoAotCompile *acfg, guint8 val)
487 mono_img_writer_emit_byte (acfg->w, val);
490 #ifdef __native_client_codegen__
492 emit_nacl_call_alignment (MonoAotCompile *acfg)
494 mono_img_writer_emit_nacl_call_alignment (acfg->w);
498 static G_GNUC_UNUSED void
499 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
501 mono_img_writer_emit_global (acfg->w, name, func);
505 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
507 if (acfg->aot_opts.no_dlsym) {
508 g_ptr_array_add (acfg->globals, g_strdup (name));
509 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
511 mono_img_writer_emit_global (acfg->w, name, func);
516 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
518 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
521 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
523 emit_info_symbol (MonoAotCompile *acfg, const char *name)
528 emit_label (acfg, name);
529 /* LLVM generated code references this */
530 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
531 emit_label (acfg, symbol);
532 emit_global_inner (acfg, symbol, FALSE);
534 emit_label (acfg, name);
539 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
542 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
546 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
548 /* On apple, all symbols need to be aligned to avoid warnings from ld */
549 emit_alignment (acfg, 4);
551 mono_img_writer_emit_label (acfg->w, name);
552 mono_img_writer_emit_string (acfg->w, value);
555 static G_GNUC_UNUSED void
556 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
559 guint8 b = value & 0x7f;
561 if (value != 0) /* more bytes to come */
567 static G_GNUC_UNUSED void
568 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
571 gboolean negative = (value < 0);
578 /* the following is unnecessary if the
579 * implementation of >>= uses an arithmetic rather
580 * than logical shift for a signed left operand
584 value |= - ((gint64)1 <<(size - 7));
585 /* sign bit of byte is second high order bit (0x40) */
586 if ((value == 0 && !(byte & 0x40)) ||
587 (value == -1 && (byte & 0x40)))
591 emit_byte (acfg, byte);
595 static G_GNUC_UNUSED void
596 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
601 guint8 b = value & 0x7f;
603 if (value != 0) /* more bytes to come */
611 static G_GNUC_UNUSED void
612 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
615 gboolean negative = (value < 0);
623 /* the following is unnecessary if the
624 * implementation of >>= uses an arithmetic rather
625 * than logical shift for a signed left operand
629 value |= - (1 <<(size - 7));
630 /* sign bit of byte is second high order bit (0x40) */
631 if ((value == 0 && !(byte & 0x40)) ||
632 (value == -1 && (byte & 0x40)))
643 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
646 buf [0] = (val >> 0) & 0xff;
647 buf [1] = (val >> 8) & 0xff;
648 buf [2] = (val >> 16) & 0xff;
649 buf [3] = (val >> 24) & 0xff;
655 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
657 buf [0] = (val >> 0) & 0xff;
658 buf [1] = (val >> 8) & 0xff;
664 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
666 int len = strlen (s);
668 memcpy (buf, s, len + 1);
669 *endbuf = buf + len + 1;
673 emit_unset_mode (MonoAotCompile *acfg)
675 mono_img_writer_emit_unset_mode (acfg->w);
678 static G_GNUC_UNUSED void
679 emit_set_thumb_mode (MonoAotCompile *acfg)
681 emit_unset_mode (acfg);
682 fprintf (acfg->fp, ".code 16\n");
685 static G_GNUC_UNUSED void
686 emit_set_arm_mode (MonoAotCompile *acfg)
688 emit_unset_mode (acfg);
689 fprintf (acfg->fp, ".code 32\n");
693 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
698 g_assert (size % 4 == 0);
699 emit_unset_mode (acfg);
700 for (i = 0; i < size; i += 4)
701 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
703 emit_bytes (acfg, buf, size);
707 /* ARCHITECTURE SPECIFIC CODE */
709 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
710 #define EMIT_DWARF_INFO 1
713 #if defined(TARGET_ARM)
714 #define AOT_FUNC_ALIGNMENT 4
716 #define AOT_FUNC_ALIGNMENT 16
718 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
719 #undef AOT_FUNC_ALIGNMENT
720 #define AOT_FUNC_ALIGNMENT 32
723 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
724 #define PPC_LD_OP "ld"
725 #define PPC_LDX_OP "ldx"
727 #define PPC_LD_OP "lwz"
728 #define PPC_LDX_OP "lwzx"
732 #define AOT_TARGET_STR "AMD64"
737 #define AOT_TARGET_STR "ARM (MACH)"
739 #define AOT_TARGET_STR "ARM (!MACH)"
745 #define AOT_TARGET_STR "ARM64 (MACH)"
747 #define AOT_TARGET_STR "ARM64 (!MACH)"
751 #ifdef TARGET_POWERPC64
752 #ifdef __mono_ilp32__
753 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
755 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
758 #ifdef TARGET_POWERPC
759 #ifdef __mono_ilp32__
760 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
762 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
769 #define AOT_TARGET_STR "X86 (WIN32)"
770 #elif defined(__native_client_codegen__)
771 #define AOT_TARGET_STR "X86 (native client codegen)"
773 #define AOT_TARGET_STR "X86 (!native client codegen)"
777 #ifndef AOT_TARGET_STR
778 #define AOT_TARGET_STR ""
782 arch_init (MonoAotCompile *acfg)
784 acfg->llc_args = g_string_new ("");
785 acfg->as_args = g_string_new ("");
788 * The prefix LLVM likes to put in front of symbol names on darwin.
789 * The mach-os specs require this for globals, but LLVM puts them in front of all
790 * symbols. We need to handle this, since we need to refer to LLVM generated
793 acfg->llvm_label_prefix = "";
794 acfg->user_symbol_prefix = "";
796 #if defined(TARGET_X86)
797 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
800 #if defined(TARGET_AMD64)
801 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
803 acfg->align_pad_value = 0x90;
807 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
808 g_string_append (acfg->llc_args, "-mattr=+v6");
811 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
812 g_string_append (acfg->as_args, " -mfpu=vfp3");
814 g_string_append (acfg->llc_args, " -soft-float");
817 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
818 acfg->thumb_mixed = TRUE;
820 if (acfg->aot_opts.mtriple)
821 mono_arch_set_target (acfg->aot_opts.mtriple);
825 acfg->inst_directive = ".inst";
826 if (acfg->aot_opts.mtriple)
827 mono_arch_set_target (acfg->aot_opts.mtriple);
831 acfg->user_symbol_prefix = "_";
832 acfg->llvm_label_prefix = "_";
833 acfg->inst_directive = ".word";
834 acfg->need_no_dead_strip = TRUE;
835 acfg->aot_opts.gnu_asm = TRUE;
838 #if defined(__linux__) && !defined(TARGET_ARM)
839 acfg->need_pt_gnu_stack = TRUE;
843 acfg->global_symbols = TRUE;
849 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
853 #ifdef MONO_ARCH_AOT_SUPPORTED
855 * arch_emit_direct_call:
857 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
861 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
863 #if defined(TARGET_X86) || defined(TARGET_AMD64)
864 /* Need to make sure this is exactly 5 bytes long */
865 emit_unset_mode (acfg);
866 fprintf (acfg->fp, "call %s\n", target);
868 #elif defined(TARGET_ARM)
869 emit_unset_mode (acfg);
871 fprintf (acfg->fp, "blx %s\n", target);
873 fprintf (acfg->fp, "bl %s\n", target);
875 #elif defined(TARGET_ARM64)
876 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
877 #elif defined(TARGET_POWERPC)
878 emit_unset_mode (acfg);
879 fprintf (acfg->fp, "bl %s\n", target);
882 g_assert_not_reached ();
889 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
891 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
892 * in in the 2. slot of every GOT, and require every method to place the GOT
893 * address in r30, even when it doesn't access the GOT otherwise. This way,
894 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
899 * PPC64 uses function descriptors which greatly complicate all code, since
900 * these are used very inconsistently in the runtime. Some functions like
901 * mono_compile_method () return ftn descriptors, while others like the
902 * trampoline creation functions do not.
903 * We assume that all GOT slots contain function descriptors, and create
904 * descriptors in aot-runtime.c when needed.
905 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
906 * from function descriptors, we could do the same, but it would require
907 * rewriting all the ppc/aot code to handle function descriptors properly.
908 * So instead, we use the same approach as on PPC32.
909 * This is a horrible mess, but fixing it would probably lead to an even bigger
915 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
918 #ifdef MONO_ARCH_AOT_SUPPORTED
920 * arch_emit_got_offset:
922 * The memory pointed to by CODE should hold native code for computing the GOT
923 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
924 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
927 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
929 #if defined(TARGET_POWERPC64)
930 emit_unset_mode (acfg);
932 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
933 * unsupported relocations. So we store the got address into the .Lgot_addr
934 * symbol which is in the text segment, compute its address, and load it.
936 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
937 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
938 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
939 fprintf (acfg->fp, "add 30, 30, 0\n");
940 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
941 acfg->label_generator ++;
943 #elif defined(TARGET_POWERPC)
944 emit_unset_mode (acfg);
945 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
946 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
947 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
948 acfg->label_generator ++;
951 guint32 offset = mono_arch_get_patch_offset (code);
952 emit_bytes (acfg, code, offset);
953 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
955 *code_size = offset + 4;
960 * arch_emit_got_access:
962 * The memory pointed to by CODE should hold native code for loading a GOT
963 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
964 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
967 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
970 /* mov reg, got+offset(%rip) */
972 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
976 /* Decode reg, see amd64_mov_reg_membase () */
977 rex_r = code [0] & AMD64_REX_R;
978 g_assert (code [0] == 0x49 + rex_r);
979 g_assert (code [1] == 0x8b);
980 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
982 emit_unset_mode (acfg);
983 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
986 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
987 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
988 *code_size = mono_arch_get_patch_offset (code) + 4;
990 #elif defined(TARGET_X86)
991 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
992 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
993 *code_size = mono_arch_get_patch_offset (code) + 4;
994 #elif defined(TARGET_ARM)
995 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
996 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
997 *code_size = mono_arch_get_patch_offset (code) + 4;
998 #elif defined(TARGET_ARM64)
999 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1000 arm64_emit_got_access (acfg, code, got_slot, code_size);
1001 #elif defined(TARGET_POWERPC)
1006 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1008 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1009 g_assert (code - buf == 8);
1010 emit_bytes (acfg, buf, code - buf);
1011 *code_size = code - buf;
1014 g_assert_not_reached ();
1020 #ifdef MONO_ARCH_AOT_SUPPORTED
1022 * arch_emit_objc_selector_ref:
1024 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1027 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1029 #if defined(TARGET_ARM)
1032 int lindex = acfg->objc_selector_index_2 ++;
1034 /* Emit ldr.imm/b */
1035 emit_bytes (acfg, code, 8);
1037 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1038 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1040 emit_label (acfg, symbol1);
1041 mono_img_writer_emit_unset_mode (acfg->w);
1042 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1045 #elif defined(TARGET_ARM64)
1046 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1048 g_assert_not_reached ();
1054 * arch_emit_plt_entry:
1056 * Emit code for the PLT entry.
1057 * The plt entry should look like this:
1058 * <indirect jump to GOT_SYMBOL + OFFSET>
1059 * <INFO_OFFSET embedded into the instruction stream>
1062 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1064 #if defined(TARGET_X86)
1065 #if defined(__default_codegen__)
1066 /* jmp *<offset>(%ebx) */
1067 emit_byte (acfg, 0xff);
1068 emit_byte (acfg, 0xa3);
1069 emit_int32 (acfg, offset);
1070 /* Used by mono_aot_get_plt_info_offset */
1071 emit_int32 (acfg, info_offset);
1072 #elif defined(__native_client_codegen__)
1073 const guint8 kSizeOfNaClJmp = 11;
1074 guint8 bytes[kSizeOfNaClJmp];
1075 guint8 *pbytes = &bytes[0];
1077 x86_jump_membase32 (pbytes, X86_EBX, offset);
1078 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1079 /* four bytes of data, used by mono_arch_patch_plt_entry */
1080 /* For Native Client, make this work with data embedded in push. */
1081 emit_byte (acfg, 0x68); /* hide data in a push */
1082 emit_int32 (acfg, info_offset);
1083 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1084 #endif /*__native_client_codegen__*/
1085 #elif defined(TARGET_AMD64)
1086 #if defined(__default_codegen__)
1087 emit_unset_mode (acfg);
1088 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1089 /* Used by mono_aot_get_plt_info_offset */
1090 emit_int32 (acfg, info_offset);
1091 acfg->stats.plt_size += 10;
1092 #elif defined(__native_client_codegen__)
1094 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1095 guint8 *code = buf_aligned;
1097 /* mov <OFFSET>(%rip), %r11d */
1098 emit_byte (acfg, '\x45');
1099 emit_byte (acfg, '\x8b');
1100 emit_byte (acfg, '\x1d');
1101 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1103 amd64_jump_reg (code, AMD64_R11);
1104 /* This should be constant for the plt patch */
1105 g_assert ((size_t)(code-buf_aligned) == 10);
1106 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1108 /* Hide data in a push imm32 so it passes validation */
1109 emit_byte (acfg, 0x68); /* push */
1110 emit_int32 (acfg, info_offset);
1111 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1112 #endif /*__native_client_codegen__*/
1113 #elif defined(TARGET_ARM)
1118 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1119 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1120 emit_bytes (acfg, buf, code - buf);
1121 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1122 /* Used by mono_aot_get_plt_info_offset */
1123 emit_int32 (acfg, info_offset);
1124 #elif defined(TARGET_ARM64)
1125 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1126 #elif defined(TARGET_POWERPC)
1127 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1128 emit_unset_mode (acfg);
1129 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1130 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1131 fprintf (acfg->fp, "add 11, 11, 30\n");
1132 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1133 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1134 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1135 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1137 fprintf (acfg->fp, "mtctr 11\n");
1138 fprintf (acfg->fp, "bctr\n");
1139 emit_int32 (acfg, info_offset);
1141 g_assert_not_reached ();
1146 * arch_emit_llvm_plt_entry:
1148 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1149 * This is only needed on arm to handle thumb interop.
1152 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1154 #if defined(TARGET_ARM)
1155 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1156 /* The caller already transitioned to thumb */
1157 /* The code below should be 12 bytes long */
1158 /* clang has trouble encoding these instructions, so emit the binary */
1160 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1161 /* thumb can't encode ld pc, [pc, ip] */
1162 fprintf (acfg->fp, "add ip, pc, ip\n");
1163 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1164 fprintf (acfg->fp, "bx ip\n");
1166 emit_set_thumb_mode (acfg);
1167 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1168 fprintf (acfg->fp, ".2byte 0x44fc\n");
1169 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1170 fprintf (acfg->fp, ".2byte 0x4760\n");
1171 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1172 emit_int32 (acfg, info_offset);
1173 emit_unset_mode (acfg);
1174 emit_set_arm_mode (acfg);
1176 g_assert_not_reached ();
1180 /* Save unwind_info in the module and emit the offset to the information at symbol */
1181 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1183 guint32 uw_offset, encoded_len;
1186 emit_section_change (acfg, RODATA_SECT, 0);
1187 emit_global (acfg, symbol, FALSE);
1188 emit_label (acfg, symbol);
1190 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1191 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1193 emit_int32 (acfg, uw_offset);
1197 * arch_emit_specific_trampoline_pages:
1199 * Emits a page full of trampolines: each trampoline uses its own address to
1200 * lookup both the generic trampoline code and the data argument.
1201 * This page can be remapped in process multiple times so we can get an
1202 * unlimited number of trampolines.
1203 * Specifically this implementation uses the following trick: two memory pages
1204 * are allocated, with the first containing the data and the second containing the trampolines.
1205 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1206 * implementation does all the lifting.
1207 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1208 * on the arm 32 bit system.
1211 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1213 #if defined(TARGET_ARM)
1216 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1218 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1219 GSList *unwind_ops = NULL;
1220 #define COMMON_TRAMP_SIZE 16
1221 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1222 int imm8, rot_amount;
1225 if (!acfg->aot_opts.use_trampolines_page)
1228 acfg->tramp_page_size = pagesize;
1230 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1231 emit_alignment (acfg, pagesize);
1232 emit_global (acfg, symbol, TRUE);
1233 emit_label (acfg, symbol);
1235 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1237 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1238 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1239 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1240 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1242 g_assert (code - buf == COMMON_TRAMP_SIZE);
1245 emit_bytes (acfg, buf, code - buf);
1247 for (i = 0; i < count; ++i) {
1249 ARM_PUSH (code, 0x5fff);
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 rgctx 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 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1262 emit_global (acfg, symbol, TRUE);
1263 emit_label (acfg, symbol);
1265 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1266 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1267 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1268 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1270 g_assert (code - buf == COMMON_TRAMP_SIZE);
1273 emit_bytes (acfg, buf, code - buf);
1275 for (i = 0; i < count; ++i) {
1277 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1279 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1280 g_assert (code - buf == 8);
1281 emit_bytes (acfg, buf, code - buf);
1285 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1287 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1288 emit_global (acfg, symbol, TRUE);
1289 emit_label (acfg, symbol);
1291 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1292 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1293 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1294 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1295 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1296 g_assert (code - buf == COMMON_TRAMP_SIZE);
1298 emit_bytes (acfg, buf, code - buf);
1300 for (i = 0; i < count; ++i) {
1302 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1304 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1305 g_assert (code - buf == 8);
1306 emit_bytes (acfg, buf, code - buf);
1309 /* now the imt trampolines: each specific trampolines puts in the ip register
1310 * the instruction pointer address, so the generic trampoline at the start of the page
1311 * subtracts 4096 to get to the data page and loads the values
1313 #define IMT_TRAMP_SIZE 72
1314 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1315 emit_global (acfg, symbol, TRUE);
1316 emit_label (acfg, symbol);
1318 /* Need at least two free registers, plus a slot for storing the pc */
1319 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1321 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1322 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1323 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1325 /* The IMT method is in v5, r0 has the imt array address */
1328 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1329 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1330 imt_found_check = code;
1331 ARM_B_COND (code, ARMCOND_EQ, 0);
1333 /* End-of-loop check */
1334 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1335 loop_end_check = code;
1336 ARM_B_COND (code, ARMCOND_EQ, 0);
1339 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1340 loop_branch_back = code;
1342 arm_patch (loop_branch_back, loop_start);
1345 arm_patch (imt_found_check, code);
1346 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1347 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1348 /* Save it to the third stack slot */
1349 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1350 /* Restore the registers and branch */
1351 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1354 arm_patch (loop_end_check, code);
1355 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1356 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1357 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1361 g_assert (code - buf == IMT_TRAMP_SIZE);
1362 emit_bytes (acfg, buf, code - buf);
1364 for (i = 0; i < count; ++i) {
1366 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1368 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1369 g_assert (code - buf == 8);
1370 emit_bytes (acfg, buf, code - buf);
1373 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1374 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1375 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1376 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1378 /* Unwind info for specifc trampolines */
1379 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1380 /* We unwind to the original caller, from the stack, since lr is clobbered */
1381 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1382 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1383 save_unwind_info (acfg, symbol, unwind_ops);
1384 mono_free_unwind_info (unwind_ops);
1386 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1387 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1388 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1389 save_unwind_info (acfg, symbol, unwind_ops);
1390 mono_free_unwind_info (unwind_ops);
1392 /* Unwind info for rgctx trampolines */
1393 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1394 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1395 save_unwind_info (acfg, symbol, unwind_ops);
1397 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1398 save_unwind_info (acfg, symbol, unwind_ops);
1399 mono_free_unwind_info (unwind_ops);
1401 /* Unwind info for gsharedvt trampolines */
1402 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1403 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1404 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1405 save_unwind_info (acfg, symbol, unwind_ops);
1406 mono_free_unwind_info (unwind_ops);
1408 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1409 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1410 save_unwind_info (acfg, symbol, unwind_ops);
1411 mono_free_unwind_info (unwind_ops);
1413 /* Unwind info for imt trampolines */
1414 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1415 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1416 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1417 save_unwind_info (acfg, symbol, unwind_ops);
1418 mono_free_unwind_info (unwind_ops);
1420 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1421 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1422 save_unwind_info (acfg, symbol, unwind_ops);
1423 mono_free_unwind_info (unwind_ops);
1424 #elif defined(TARGET_ARM64)
1425 arm64_emit_specific_trampoline_pages (acfg);
1430 * arch_emit_specific_trampoline:
1432 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1433 * two GOT slots which contain the generic trampoline address and the trampoline
1434 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1437 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1440 * The trampolines created here are variations of the specific
1441 * trampolines created in mono_arch_create_specific_trampoline (). The
1443 * - the generic trampoline address is taken from a got slot.
1444 * - the offset of the got slot where the trampoline argument is stored
1445 * is embedded in the instruction stream, and the generic trampoline
1446 * can load the argument by loading the offset, adding it to the
1447 * address of the trampoline to get the address of the got slot, and
1448 * loading the argument from there.
1449 * - all the trampolines should be of the same length.
1451 #if defined(TARGET_AMD64)
1452 #if defined(__default_codegen__)
1453 /* This should be exactly 8 bytes long */
1455 /* call *<offset>(%rip) */
1457 emit_unset_mode (acfg);
1458 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1459 emit_zero_bytes (acfg, 2);
1461 emit_byte (acfg, '\x41');
1462 emit_byte (acfg, '\xff');
1463 emit_byte (acfg, '\x15');
1464 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1465 emit_zero_bytes (acfg, 1);
1467 #elif defined(__native_client_codegen__)
1469 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1470 guint8 *code = buf_aligned;
1475 /* Emit this call in 'code' so we can find out how long it is. */
1476 amd64_call_reg (code, AMD64_R11);
1477 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1478 call_len = code - call_start;
1480 /* The tramp_size is twice the NaCl alignment because it starts with */
1481 /* a call which needs to be aligned to the end of the boundary. */
1482 *tramp_size = kNaClAlignment*2;
1484 /* Emit nops to align call site below which is 7 bytes plus */
1485 /* the length of the call sequence emitted above. */
1486 /* Note: this requires the specific trampoline starts on a */
1487 /* kNaclAlignedment aligned address, which it does because */
1488 /* it's its own function that is aligned. */
1489 guint8 nop_buf[256];
1490 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1491 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1492 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1494 /* The trampoline is stored at the offset'th pointer, the -4 is */
1495 /* present because RIP relative addressing starts at the end of */
1496 /* the current instruction, while the label "." is relative to */
1497 /* the beginning of the current asm location, which in this case */
1498 /* is not the mov instruction, but the offset itself, due to the */
1499 /* way the bytes and ints are emitted here. */
1500 got_offset = (offset * sizeof(gpointer)) - 4;
1502 /* mov <OFFSET>(%rip), %r11d */
1503 emit_byte (acfg, '\x45');
1504 emit_byte (acfg, '\x8b');
1505 emit_byte (acfg, '\x1d');
1506 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1509 emit_bytes (acfg, call_start, call_len);
1511 /* The arg is stored at the offset+1 pointer, relative to beginning */
1512 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1513 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1515 /* We can't emit this data directly, hide in a "push imm32" */
1516 emit_byte (acfg, '\x68'); /* push */
1517 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1518 emit_alignment (acfg, kNaClAlignment);
1519 #endif /*__native_client_codegen__*/
1520 #elif defined(TARGET_ARM)
1524 /* This should be exactly 20 bytes long */
1527 ARM_PUSH (code, 0x5fff);
1528 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1529 /* Load the value from the GOT */
1530 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1532 ARM_BLX_REG (code, ARMREG_R1);
1534 g_assert (code - buf == 16);
1537 emit_bytes (acfg, buf, code - buf);
1539 * Only one offset is needed, since the second one would be equal to the
1542 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1543 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1544 #elif defined(TARGET_ARM64)
1545 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1546 #elif defined(TARGET_POWERPC)
1554 * PPC has no ip relative addressing, so we need to compute the address
1555 * of the mscorlib got. That is slow and complex, so instead, we store it
1556 * in the second got slot of every aot image. The caller already computed
1557 * the address of its got and placed it into r30.
1559 emit_unset_mode (acfg);
1560 /* Load mscorlib got address */
1561 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1562 /* Load generic trampoline address */
1563 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1564 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1565 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1566 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1567 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1569 fprintf (acfg->fp, "mtctr 11\n");
1570 /* Load trampoline argument */
1571 /* On ppc, we pass it normally to the generic trampoline */
1572 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1573 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1574 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1575 /* Branch to generic trampoline */
1576 fprintf (acfg->fp, "bctr\n");
1578 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1579 *tramp_size = 10 * 4;
1581 *tramp_size = 9 * 4;
1583 #elif defined(TARGET_X86)
1587 /* Similar to the PPC code above */
1589 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1592 /* Load mscorlib got address */
1593 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1594 /* Push trampoline argument */
1595 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1596 /* Load generic trampoline address */
1597 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1598 /* Branch to generic trampoline */
1599 x86_jump_reg (code, X86_ECX);
1601 #ifdef __native_client_codegen__
1603 /* emit nops to next 32 byte alignment */
1604 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1605 while (code < (buf + a)) x86_nop(code);
1608 emit_bytes (acfg, buf, code - buf);
1610 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1611 g_assert (code - buf == *tramp_size);
1613 g_assert_not_reached ();
1618 * arch_emit_unbox_trampoline:
1620 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1621 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1624 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1626 #if defined(TARGET_AMD64)
1631 this_reg = mono_arch_get_this_arg_reg (NULL);
1633 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1635 emit_bytes (acfg, buf, code - buf);
1638 emit_unset_mode (acfg);
1639 fprintf (acfg->fp, "jmp %s\n", call_target);
1641 emit_byte (acfg, '\xe9');
1642 emit_symbol_diff (acfg, call_target, ".", -4);
1644 #elif defined(TARGET_X86)
1651 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1653 emit_bytes (acfg, buf, code - buf);
1656 emit_byte (acfg, '\xe9');
1657 emit_symbol_diff (acfg, call_target, ".", -4);
1658 #elif defined(TARGET_ARM)
1662 if (acfg->thumb_mixed && cfg->compile_llvm) {
1663 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1664 fprintf (acfg->fp, "b %s\n", call_target);
1665 fprintf (acfg->fp, ".arm\n");
1666 fprintf (acfg->fp, ".align 2\n");
1672 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1674 emit_bytes (acfg, buf, code - buf);
1675 /* jump to method */
1676 if (acfg->thumb_mixed && cfg->compile_llvm)
1677 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1679 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1680 #elif defined(TARGET_ARM64)
1681 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1682 #elif defined(TARGET_POWERPC)
1685 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1686 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1688 g_assert_not_reached ();
1693 * arch_emit_static_rgctx_trampoline:
1695 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1696 * two GOT slots which contain the rgctx argument, and the method to jump to.
1697 * TRAMP_SIZE is set to the size of the emitted trampoline.
1698 * These kinds of trampolines cannot be enumerated statically, since there could
1699 * be one trampoline per method instantiation, so we emit the same code for all
1700 * trampolines, and parameterize them using two GOT slots.
1703 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1705 #if defined(TARGET_AMD64)
1706 #if defined(__default_codegen__)
1707 /* This should be exactly 13 bytes long */
1711 emit_unset_mode (acfg);
1712 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1713 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1715 /* mov <OFFSET>(%rip), %r10 */
1716 emit_byte (acfg, '\x4d');
1717 emit_byte (acfg, '\x8b');
1718 emit_byte (acfg, '\x15');
1719 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1721 /* jmp *<offset>(%rip) */
1722 emit_byte (acfg, '\xff');
1723 emit_byte (acfg, '\x25');
1724 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1726 #elif defined(__native_client_codegen__)
1728 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1729 guint8 *code = buf_aligned;
1731 /* mov <OFFSET>(%rip), %r10d */
1732 emit_byte (acfg, '\x45');
1733 emit_byte (acfg, '\x8b');
1734 emit_byte (acfg, '\x15');
1735 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1737 /* mov <OFFSET>(%rip), %r11d */
1738 emit_byte (acfg, '\x45');
1739 emit_byte (acfg, '\x8b');
1740 emit_byte (acfg, '\x1d');
1741 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1744 amd64_jump_reg (code, AMD64_R11);
1745 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1747 emit_alignment (acfg, kNaClAlignment);
1748 *tramp_size = kNaClAlignment;
1749 #endif /*__native_client_codegen__*/
1751 #elif defined(TARGET_ARM)
1755 /* This should be exactly 24 bytes long */
1758 /* Load rgctx value */
1759 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1760 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1761 /* Load branch addr + branch */
1762 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1763 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1765 g_assert (code - buf == 16);
1768 emit_bytes (acfg, buf, code - buf);
1769 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1770 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1771 #elif defined(TARGET_ARM64)
1772 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1773 #elif defined(TARGET_POWERPC)
1781 * PPC has no ip relative addressing, so we need to compute the address
1782 * of the mscorlib got. That is slow and complex, so instead, we store it
1783 * in the second got slot of every aot image. The caller already computed
1784 * the address of its got and placed it into r30.
1786 emit_unset_mode (acfg);
1787 /* Load mscorlib got address */
1788 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1790 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1791 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1792 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1793 /* Load target address */
1794 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1795 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1796 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1797 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1798 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1799 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1801 fprintf (acfg->fp, "mtctr 11\n");
1802 /* Branch to the target address */
1803 fprintf (acfg->fp, "bctr\n");
1805 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1806 *tramp_size = 11 * 4;
1808 *tramp_size = 9 * 4;
1811 #elif defined(TARGET_X86)
1815 /* Similar to the PPC code above */
1817 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1820 /* Load mscorlib got address */
1821 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1823 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1824 /* Branch to the target address */
1825 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1827 #ifdef __native_client_codegen__
1829 /* emit nops to next 32 byte alignment */
1830 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1831 while (code < (buf + a)) x86_nop(code);
1835 emit_bytes (acfg, buf, code - buf);
1837 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1838 g_assert (code - buf == *tramp_size);
1840 g_assert_not_reached ();
1845 * arch_emit_imt_thunk:
1847 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1848 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1849 * key is the IMT key, and ptr holds the address of a memory location holding
1850 * the address to branch to if the IMT arg matches the key. The array is
1851 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1853 * TRAMP_SIZE is set to the size of the emitted trampoline.
1856 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1858 #if defined(TARGET_AMD64)
1860 #if defined(__native_client_codegen__)
1863 guint8 *labels [16];
1865 guint8 *mov_buf_ptr = mov_buf;
1867 const int kSizeOfMove = 7;
1868 #if defined(__default_codegen__)
1869 code = buf = (guint8 *)g_malloc (256);
1870 #elif defined(__native_client_codegen__)
1871 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1872 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1873 /* The RIP relative move below is emitted first */
1878 /* FIXME: Optimize this, i.e. use binary search etc. */
1879 /* Maybe move the body into a separate function (slower, but much smaller) */
1881 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1884 emit_unset_mode (acfg);
1885 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1889 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1891 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1894 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1896 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1899 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1900 amd64_jump_code (code, labels [0]);
1903 mono_amd64_patch (labels [2], code);
1904 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1905 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1908 mono_amd64_patch (labels [1], code);
1909 /* Load fail tramp */
1910 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1911 /* Check if there is a fail tramp */
1912 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1914 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1915 /* Jump to fail tramp */
1916 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1919 mono_amd64_patch (labels [3], code);
1920 x86_breakpoint (code);
1923 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1924 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1925 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1926 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1927 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1928 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1930 emit_bytes (acfg, buf, code - buf);
1932 *tramp_size = code - buf + kSizeOfMove;
1933 #if defined(__native_client_codegen__)
1934 /* The tramp will be padded to the next kNaClAlignment bundle. */
1935 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1938 #if defined(__default_codegen__)
1940 #elif defined(__native_client_codegen__)
1944 #elif defined(TARGET_X86)
1946 #ifdef __native_client_codegen__
1949 guint8 *labels [16];
1951 #if defined(__default_codegen__)
1952 code = buf = g_malloc (256);
1953 #elif defined(__native_client_codegen__)
1954 buf_alloc = g_malloc (256 + kNaClAlignment);
1955 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1958 /* Allocate a temporary stack slot */
1959 x86_push_reg (code, X86_EAX);
1961 x86_push_reg (code, X86_EAX);
1963 /* Load mscorlib got address */
1964 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1966 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1969 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1971 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1974 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1976 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1979 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1980 x86_jump_code (code, labels [0]);
1983 mono_x86_patch (labels [2], code);
1984 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1985 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1986 /* Save the target address to the temporary stack location */
1987 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1989 x86_pop_reg (code, X86_EAX);
1990 /* Jump to the target address */
1994 mono_x86_patch (labels [1], code);
1995 /* Load fail tramp */
1996 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1997 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1999 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2000 /* Jump to fail tramp */
2001 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2002 x86_pop_reg (code, X86_EAX);
2006 mono_x86_patch (labels [3], code);
2007 x86_breakpoint (code);
2009 #ifdef __native_client_codegen__
2011 /* emit nops to next 32 byte alignment */
2012 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2013 while (code < (buf + a)) x86_nop(code);
2016 emit_bytes (acfg, buf, code - buf);
2018 *tramp_size = code - buf;
2020 #if defined(__default_codegen__)
2022 #elif defined(__native_client_codegen__)
2026 #elif defined(TARGET_ARM)
2028 guint8 *code, *code2, *labels [16];
2032 /* The IMT method is in v5 */
2034 /* Need at least two free registers, plus a slot for storing the pc */
2035 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2037 /* Load the parameter from the GOT */
2038 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2039 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2042 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2043 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2045 ARM_B_COND (code, ARMCOND_EQ, 0);
2047 /* End-of-loop check */
2048 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2050 ARM_B_COND (code, ARMCOND_EQ, 0);
2053 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2056 arm_patch (labels [4], labels [1]);
2059 arm_patch (labels [2], code);
2060 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2061 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2062 /* Save it to the third stack slot */
2063 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2064 /* Restore the registers and branch */
2065 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2068 arm_patch (labels [3], code);
2069 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2070 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2071 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2075 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2077 emit_bytes (acfg, buf, code - buf);
2078 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2080 *tramp_size = code - buf + 4;
2081 #elif defined(TARGET_ARM64)
2082 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2083 #elif defined(TARGET_POWERPC)
2085 guint8 *code, *labels [16];
2089 /* Load the mscorlib got address */
2090 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2091 /* Load the parameter from the GOT */
2092 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2093 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2095 /* Load and check key */
2097 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2098 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2100 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2102 /* End-of-loop check */
2103 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2105 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2108 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2111 mono_ppc_patch (labels [4], labels [1]);
2114 mono_ppc_patch (labels [2], code);
2115 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2116 /* r12 now contains the value of the vtable slot */
2117 /* this is not a function descriptor on ppc64 */
2118 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2119 ppc_mtctr (code, ppc_r12);
2120 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2123 mono_ppc_patch (labels [3], code);
2127 *tramp_size = code - buf;
2129 emit_bytes (acfg, buf, code - buf);
2131 g_assert_not_reached ();
2136 * arch_emit_gsharedvt_arg_trampoline:
2138 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2139 * two GOT slots which contain the argument, and the code to jump to.
2140 * TRAMP_SIZE is set to the size of the emitted trampoline.
2141 * These kinds of trampolines cannot be enumerated statically, since there could
2142 * be one trampoline per method instantiation, so we emit the same code for all
2143 * trampolines, and parameterize them using two GOT slots.
2146 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2148 #if defined(TARGET_X86)
2152 /* Similar to the PPC code above */
2154 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2157 /* Load mscorlib got address */
2158 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2160 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2161 /* Branch to the target address */
2162 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2164 #ifdef __native_client_codegen__
2166 /* emit nops to next 32 byte alignment */
2167 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2168 while (code < (buf + a)) x86_nop(code);
2172 emit_bytes (acfg, buf, code - buf);
2174 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2175 g_assert (code - buf == *tramp_size);
2176 #elif defined(TARGET_ARM)
2180 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2181 /* Similar to arch_emit_specific_trampoline () */
2184 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2185 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2186 /* Load the arg value from the GOT */
2187 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2188 /* Load the addr from the GOT */
2189 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2191 ARM_BX (code, ARMREG_R1);
2193 g_assert (code - buf == 20);
2196 emit_bytes (acfg, buf, code - buf);
2197 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2198 #elif defined(TARGET_ARM64)
2199 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2201 g_assert_not_reached ();
2205 /* END OF ARCH SPECIFIC CODE */
2208 mono_get_field_token (MonoClassField *field)
2210 MonoClass *klass = field->parent;
2213 for (i = 0; i < klass->field.count; ++i) {
2214 if (field == &klass->fields [i])
2215 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2218 g_assert_not_reached ();
2223 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2227 //printf ("ENCODE: %d 0x%x.\n", value, value);
2230 * Same encoding as the one used in the metadata, extended to handle values
2231 * greater than 0x1fffffff.
2233 if ((value >= 0) && (value <= 127))
2235 else if ((value >= 0) && (value <= 16383)) {
2236 p [0] = 0x80 | (value >> 8);
2237 p [1] = value & 0xff;
2239 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2240 p [0] = (value >> 24) | 0xc0;
2241 p [1] = (value >> 16) & 0xff;
2242 p [2] = (value >> 8) & 0xff;
2243 p [3] = value & 0xff;
2248 p [1] = (value >> 24) & 0xff;
2249 p [2] = (value >> 16) & 0xff;
2250 p [3] = (value >> 8) & 0xff;
2251 p [4] = value & 0xff;
2259 stream_init (MonoDynamicStream *sh)
2262 sh->alloc_size = 4096;
2263 sh->data = (char *)g_malloc (4096);
2265 /* So offsets are > 0 */
2271 make_room_in_stream (MonoDynamicStream *stream, int size)
2273 if (size <= stream->alloc_size)
2276 while (stream->alloc_size <= size) {
2277 if (stream->alloc_size < 4096)
2278 stream->alloc_size = 4096;
2280 stream->alloc_size *= 2;
2283 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2287 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2291 make_room_in_stream (stream, stream->index + len);
2292 memcpy (stream->data + stream->index, data, len);
2293 idx = stream->index;
2294 stream->index += len;
2301 * Add data to the binary blob inside the aot image. Returns the offset inside the
2302 * blob where the data was stored.
2305 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2307 g_assert (!acfg->blob_closed);
2309 if (acfg->blob.alloc_size == 0)
2310 stream_init (&acfg->blob);
2312 return add_stream_data (&acfg->blob, (char*)data, data_len);
2316 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2321 if (acfg->blob.alloc_size == 0)
2322 stream_init (&acfg->blob);
2324 count = acfg->blob.index % align;
2326 /* we assume the stream data will be aligned */
2328 add_stream_data (&acfg->blob, buf, 4 - count);
2330 return add_stream_data (&acfg->blob, (char*)data, data_len);
2333 /* Emit a table of data into the aot image */
2335 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2337 if (acfg->data_outfile) {
2338 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2339 fwrite (data,1, size, acfg->data_outfile);
2340 acfg->datafile_offset += size;
2341 } else if (acfg->llvm) {
2342 mono_llvm_emit_aot_data (symbol, data, size);
2344 emit_section_change (acfg, RODATA_SECT, 0);
2345 emit_alignment (acfg, 8);
2346 emit_label (acfg, symbol);
2347 emit_bytes (acfg, data, size);
2352 * emit_offset_table:
2354 * Emit a table of increasing offsets in a compact form using differential encoding.
2355 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2356 * group size, the more compact the table becomes, but the slower it becomes to compute
2357 * a given entry. Returns the size of the table.
2360 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2362 gint32 current_offset;
2363 int i, buf_size, ngroups, index_entry_size;
2365 guint8 *data_p, *data_buf;
2366 guint32 *index_offsets;
2368 ngroups = (noffsets + (group_size - 1)) / group_size;
2370 index_offsets = g_new0 (guint32, ngroups);
2372 buf_size = noffsets * 4;
2373 p = buf = (guint8 *)g_malloc0 (buf_size);
2376 for (i = 0; i < noffsets; ++i) {
2377 //printf ("D: %d -> %d\n", i, offsets [i]);
2378 if ((i % group_size) == 0) {
2379 index_offsets [i / group_size] = p - buf;
2380 /* Emit the full value for these entries */
2381 encode_value (offsets [i], p, &p);
2383 /* The offsets are allowed to be non-increasing */
2384 //g_assert (offsets [i] >= current_offset);
2385 encode_value (offsets [i] - current_offset, p, &p);
2387 current_offset = offsets [i];
2392 if (ngroups && index_offsets [ngroups - 1] < 65000)
2393 index_entry_size = 2;
2395 index_entry_size = 4;
2397 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2398 p = buf = (guint8 *)g_malloc0 (buf_size);
2400 /* Emit the header */
2401 encode_int (noffsets, p, &p);
2402 encode_int (group_size, p, &p);
2403 encode_int (ngroups, p, &p);
2404 encode_int (index_entry_size, p, &p);
2406 /* Emit the index */
2407 for (i = 0; i < ngroups; ++i) {
2408 if (index_entry_size == 2)
2409 encode_int16 (index_offsets [i], p, &p);
2411 encode_int (index_offsets [i], p, &p);
2414 memcpy (p, data_buf, data_p - data_buf);
2415 p += data_p - data_buf;
2417 g_assert (p - buf <= buf_size);
2419 emit_aot_data (acfg, table, symbol, buf, p - buf);
2424 return (int)(p - buf);
2428 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2432 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2436 index = g_hash_table_size (cfg->image_hash);
2437 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2438 g_ptr_array_add (cfg->image_table, image);
2444 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2447 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2449 /* FIXME: Search referenced images as well */
2450 if (!acfg->typespec_classes) {
2451 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2452 for (i = 0; i < len; ++i) {
2454 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2455 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2458 for (i = 0; i < len; ++i) {
2459 if (acfg->typespec_classes [i] == klass)
2464 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2470 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2473 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2476 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2479 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2482 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2487 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2491 if (klass->generic_class) {
2493 g_assert (klass->type_token);
2495 /* Find a typespec for a class if possible */
2496 token = find_typespec_for_class (acfg, klass);
2498 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2499 encode_value (token, p, &p);
2501 MonoClass *gclass = klass->generic_class->container_class;
2502 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2503 static int count = 0;
2506 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2507 encode_klass_ref (acfg, gclass, p, &p);
2508 encode_ginst (acfg, inst, p, &p);
2512 } else if (klass->type_token) {
2513 int iindex = get_image_index (acfg, klass->image);
2515 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2517 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2518 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2520 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2521 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2522 encode_value (get_image_index (acfg, klass->image), p, &p);
2524 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2525 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2526 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2528 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2530 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2531 if (par->gshared_constraint) {
2532 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2533 encode_type (acfg, par->gshared_constraint, p, &p);
2534 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2536 encode_value (klass->byval_arg.type, p, &p);
2537 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2539 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2541 if (!container->is_anonymous) {
2542 encode_value (container->is_method, p, &p);
2543 if (container->is_method)
2544 encode_method_ref (acfg, container->owner.method, p, &p);
2546 encode_klass_ref (acfg, container->owner.klass, p, &p);
2549 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2550 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2551 encode_type (acfg, &klass->byval_arg, p, &p);
2554 g_assert (klass->rank > 0);
2555 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2556 encode_value (klass->rank, p, &p);
2557 encode_klass_ref (acfg, klass->element_class, p, &p);
2565 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2566 * standard metadata encoding.
2569 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2571 gboolean shared = FALSE;
2574 * The encoding of generic instances is large so emit them only once.
2576 if (klass->generic_class) {
2578 g_assert (klass->type_token);
2580 /* Find a typespec for a class if possible */
2581 token = find_typespec_for_class (acfg, klass);
2584 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2589 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2593 buf2 = (guint8 *)g_malloc (1024);
2596 encode_klass_ref_inner (acfg, klass, p, &p);
2597 g_assert (p - buf2 < 1024);
2599 offset = add_to_blob (acfg, buf2, p - buf2);
2602 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2608 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2609 encode_value (offset, p, &p);
2614 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2618 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2620 guint32 token = mono_get_field_token (field);
2623 encode_klass_ref (cfg, field->parent, p, &p);
2624 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2625 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2630 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2635 encode_value (inst->type_argc, p, &p);
2636 for (i = 0; i < inst->type_argc; ++i)
2637 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2642 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2645 MonoGenericInst *inst;
2647 inst = context->class_inst;
2649 g_assert (inst->type_argc);
2650 encode_ginst (acfg, inst, p, &p);
2652 encode_value (0, p, &p);
2654 inst = context->method_inst;
2656 g_assert (inst->type_argc);
2657 encode_ginst (acfg, inst, p, &p);
2659 encode_value (0, p, &p);
2665 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2669 g_assert (t->num_mods == 0);
2670 /* t->attrs can be ignored */
2671 //g_assert (t->attrs == 0);
2674 *p = MONO_TYPE_PINNED;
2678 *p = MONO_TYPE_BYREF;
2686 case MONO_TYPE_VOID:
2687 case MONO_TYPE_BOOLEAN:
2688 case MONO_TYPE_CHAR:
2701 case MONO_TYPE_STRING:
2702 case MONO_TYPE_OBJECT:
2703 case MONO_TYPE_TYPEDBYREF:
2705 case MONO_TYPE_VALUETYPE:
2706 case MONO_TYPE_CLASS:
2707 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2709 case MONO_TYPE_SZARRAY:
2710 encode_klass_ref (acfg, t->data.klass, p, &p);
2713 encode_type (acfg, t->data.type, p, &p);
2715 case MONO_TYPE_GENERICINST: {
2716 MonoClass *gclass = t->data.generic_class->container_class;
2717 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2719 encode_klass_ref (acfg, gclass, p, &p);
2720 encode_ginst (acfg, inst, p, &p);
2723 case MONO_TYPE_ARRAY: {
2724 MonoArrayType *array = t->data.array;
2727 encode_klass_ref (acfg, array->eklass, p, &p);
2728 encode_value (array->rank, p, &p);
2729 encode_value (array->numsizes, p, &p);
2730 for (i = 0; i < array->numsizes; ++i)
2731 encode_value (array->sizes [i], p, &p);
2732 encode_value (array->numlobounds, p, &p);
2733 for (i = 0; i < array->numlobounds; ++i)
2734 encode_value (array->lobounds [i], p, &p);
2738 case MONO_TYPE_MVAR:
2739 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2742 g_assert_not_reached ();
2749 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2755 /* Similar to the metadata encoding */
2756 if (sig->generic_param_count)
2760 if (sig->explicit_this)
2762 flags |= (sig->call_convention & 0x0F);
2766 if (sig->generic_param_count)
2767 encode_value (sig->generic_param_count, p, &p);
2768 encode_value (sig->param_count, p, &p);
2770 encode_type (acfg, sig->ret, p, &p);
2771 for (i = 0; i < sig->param_count; ++i) {
2772 if (sig->sentinelpos == i) {
2773 *p = MONO_TYPE_SENTINEL;
2776 encode_type (acfg, sig->params [i], p, &p);
2782 #define MAX_IMAGE_INDEX 250
2785 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2787 guint32 image_index = get_image_index (acfg, method->klass->image);
2788 guint32 token = method->token;
2789 MonoJumpInfoToken *ji;
2793 * The encoding for most methods is as follows:
2794 * - image index encoded as a leb128
2795 * - token index encoded as a leb128
2796 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2797 * types of method encodings.
2800 /* Mark methods which can't use aot trampolines because they need the further
2801 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2803 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2804 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2805 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2807 if (method->wrapper_type) {
2808 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2810 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2812 encode_value (method->wrapper_type, p, &p);
2814 switch (method->wrapper_type) {
2815 case MONO_WRAPPER_REMOTING_INVOKE:
2816 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2817 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2820 m = mono_marshal_method_from_wrapper (method);
2822 encode_method_ref (acfg, m, p, &p);
2825 case MONO_WRAPPER_PROXY_ISINST:
2826 case MONO_WRAPPER_LDFLD:
2827 case MONO_WRAPPER_LDFLDA:
2828 case MONO_WRAPPER_STFLD:
2829 case MONO_WRAPPER_ISINST: {
2831 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2834 case MONO_WRAPPER_LDFLD_REMOTE:
2835 case MONO_WRAPPER_STFLD_REMOTE:
2837 case MONO_WRAPPER_ALLOC: {
2838 /* The GC name is saved once in MonoAotFileInfo */
2839 g_assert (info->d.alloc.alloc_type != -1);
2840 encode_value (info->d.alloc.alloc_type, p, &p);
2843 case MONO_WRAPPER_WRITE_BARRIER: {
2847 case MONO_WRAPPER_STELEMREF: {
2849 encode_value (info->subtype, p, &p);
2850 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2851 encode_value (info->d.virtual_stelemref.kind, p, &p);
2854 case MONO_WRAPPER_UNKNOWN: {
2856 encode_value (info->subtype, p, &p);
2857 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2858 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2859 encode_klass_ref (acfg, method->klass, p, &p);
2860 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2861 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2862 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2863 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2864 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2865 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2866 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2867 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2870 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2872 encode_value (info->subtype, p, &p);
2873 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2874 strcpy ((char*)p, method->name);
2875 p += strlen (method->name) + 1;
2876 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2877 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2879 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2880 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2884 case MONO_WRAPPER_SYNCHRONIZED: {
2887 m = mono_marshal_method_from_wrapper (method);
2889 g_assert (m != method);
2890 encode_method_ref (acfg, m, p, &p);
2893 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2895 encode_value (info->subtype, p, &p);
2897 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2898 encode_value (info->d.element_addr.rank, p, &p);
2899 encode_value (info->d.element_addr.elem_size, p, &p);
2900 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2901 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2903 g_assert_not_reached ();
2907 case MONO_WRAPPER_CASTCLASS: {
2909 encode_value (info->subtype, p, &p);
2912 case MONO_WRAPPER_RUNTIME_INVOKE: {
2914 encode_value (info->subtype, p, &p);
2915 encode_value (info->d.runtime_invoke.pass_rgctx, p, &p);
2916 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2917 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2918 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2919 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2922 case MONO_WRAPPER_DELEGATE_INVOKE:
2923 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2924 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2925 if (method->is_inflated) {
2926 /* These wrappers are identified by their class */
2927 encode_value (1, p, &p);
2928 encode_klass_ref (acfg, method->klass, p, &p);
2930 MonoMethodSignature *sig = mono_method_signature (method);
2931 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2933 encode_value (0, p, &p);
2934 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2935 encode_value (info ? info->subtype : 0, p, &p);
2936 encode_signature (acfg, sig, p, &p);
2940 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2942 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2943 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2947 g_assert_not_reached ();
2949 } else if (mono_method_signature (method)->is_inflated) {
2951 * This is a generic method, find the original token which referenced it and
2953 * Obtain the token from information recorded by the JIT.
2955 ji = (MonoJumpInfoToken *)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);
2965 MonoMethod *declaring;
2966 MonoGenericContext *context = mono_method_get_context (method);
2968 g_assert (method->is_inflated);
2969 declaring = ((MonoMethodInflated*)method)->declaring;
2972 * This might be a non-generic method of a generic instance, which
2973 * doesn't have a token since the reference is generated by the JIT
2974 * like Nullable:Box/Unbox, or by generic sharing.
2976 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2977 /* Encode the klass */
2978 encode_klass_ref (acfg, method->klass, p, &p);
2979 /* Encode the method */
2980 image_index = get_image_index (acfg, method->klass->image);
2981 g_assert (image_index < MAX_IMAGE_INDEX);
2982 g_assert (declaring->token);
2983 token = declaring->token;
2984 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2985 encode_value (image_index, p, &p);
2986 encode_value (token, p, &p);
2987 encode_generic_context (acfg, context, p, &p);
2989 } else if (token == 0) {
2990 /* This might be a method of a constructed type like int[,].Set */
2991 /* Obtain the token from information recorded by the JIT */
2992 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2994 image_index = get_image_index (acfg, ji->image);
2995 g_assert (image_index < MAX_IMAGE_INDEX);
2998 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2999 encode_value (image_index, p, &p);
3000 encode_value (token, p, &p);
3003 g_assert (method->klass->rank);
3005 /* Encode directly */
3006 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3007 encode_klass_ref (acfg, method->klass, p, &p);
3008 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3009 encode_value (0, p, &p);
3010 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3011 encode_value (1, p, &p);
3012 else if (!strcmp (method->name, "Get"))
3013 encode_value (2, p, &p);
3014 else if (!strcmp (method->name, "Address"))
3015 encode_value (3, p, &p);
3016 else if (!strcmp (method->name, "Set"))
3017 encode_value (4, p, &p);
3019 g_assert_not_reached ();
3022 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3024 if (image_index >= MONO_AOT_METHODREF_MIN) {
3025 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3026 encode_value (image_index, p, &p);
3027 encode_value (mono_metadata_token_index (token), p, &p);
3029 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3036 compare_patches (gconstpointer a, gconstpointer b)
3040 i = (*(MonoJumpInfo**)a)->ip.i;
3041 j = (*(MonoJumpInfo**)b)->ip.i;
3052 static G_GNUC_UNUSED char*
3053 patch_to_string (MonoJumpInfo *patch_info)
3057 str = g_string_new ("");
3059 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3061 switch (patch_info->type) {
3062 case MONO_PATCH_INFO_VTABLE:
3063 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3068 g_string_append_printf (str, ")");
3069 return g_string_free (str, FALSE);
3075 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3078 static inline gboolean
3079 is_plt_patch (MonoJumpInfo *patch_info)
3081 switch (patch_info->type) {
3082 case MONO_PATCH_INFO_METHOD:
3083 case MONO_PATCH_INFO_INTERNAL_METHOD:
3084 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3085 case MONO_PATCH_INFO_ICALL_ADDR:
3086 case MONO_PATCH_INFO_RGCTX_FETCH:
3096 * Return the symbol identifying the plt entry PLT_OFFSET.
3099 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3103 * The Apple linker reorganizes object files, so it doesn't like branches to local
3104 * labels, since those have no relocations.
3106 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3108 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3115 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3117 static MonoPltEntry*
3118 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3121 gboolean synchronized = FALSE;
3122 static int synchronized_symbol_idx;
3124 if (!is_plt_patch (patch_info))
3127 if (!acfg->patch_to_plt_entry [patch_info->type])
3128 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3129 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3131 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3133 * Allocate a separate PLT slot for each such patch, since some plt
3134 * entries will refer to the method itself, and some will refer to the
3138 synchronized = TRUE;
3142 MonoJumpInfo *new_ji;
3144 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3146 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3147 res->plt_offset = acfg->plt_offset;
3149 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3150 if (acfg->aot_opts.write_symbols)
3151 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3153 /* Avoid duplicate symbols because we don't cache */
3154 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3156 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3157 synchronized_symbol_idx ++;
3160 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3162 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3164 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3166 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3168 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3169 //mono_print_ji (patch_info); printf ("\n");
3170 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3172 acfg->plt_offset ++;
3181 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3182 * JI could be found if it exists, otherwise allocates a new one.
3185 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3188 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3190 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3192 return got_offset - 1;
3195 got_offset = acfg->llvm_got_offset;
3196 acfg->llvm_got_offset ++;
3198 got_offset = acfg->got_offset;
3199 acfg->got_offset ++;
3202 acfg->stats.got_slots ++;
3203 acfg->stats.got_slot_types [ji->type] ++;
3205 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3206 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3207 g_ptr_array_add (info->got_patches, ji);
3212 /* Add a method to the list of methods which need to be emitted */
3214 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3217 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3218 g_ptr_array_add (acfg->methods, method);
3219 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3220 acfg->nmethods = acfg->methods->len + 1;
3223 if (method->wrapper_type || extra)
3224 g_ptr_array_add (acfg->extra_methods, method);
3228 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3230 /* One instantiation with valuetypes is generated for each async method */
3231 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3238 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3240 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3248 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3252 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3256 index = acfg->method_index;
3257 add_method_with_index (acfg, method, index, extra);
3259 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3261 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3263 acfg->method_index ++;
3269 add_method (MonoAotCompile *acfg, MonoMethod *method)
3271 return add_method_full (acfg, method, FALSE, 0);
3275 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3277 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3278 method = mini_get_shared_method (method);
3279 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3280 /* Use the gsharedvt version */
3281 method = mini_get_shared_method_full (method, TRUE, TRUE);
3283 if (acfg->aot_opts.log_generics)
3284 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3286 add_method_full (acfg, method, TRUE, depth);
3290 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3292 add_extra_method_with_depth (acfg, method, 0);
3296 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3298 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3299 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3300 MonoMethod *wrapper;
3306 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3307 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3310 add_method (acfg, wrapper);
3314 get_runtime_invoke_sig (MonoMethodSignature *sig)
3316 MonoMethodBuilder *mb;
3319 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3320 m = mono_mb_create_method (mb, sig, 16);
3321 return mono_marshal_get_runtime_invoke (m, FALSE, FALSE);
3325 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3327 return mono_marshal_get_runtime_invoke (method, virtual_, acfg->aot_opts.llvm_only && mono_method_needs_static_rgctx_invoke (method, TRUE));
3331 can_marshal_struct (MonoClass *klass)
3333 MonoClassField *field;
3334 gboolean can_marshal = TRUE;
3335 gpointer iter = NULL;
3336 MonoMarshalType *info;
3339 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3342 info = mono_marshal_load_type_info (klass);
3344 /* Only allow a few field types to avoid asserts in the marshalling code */
3345 while ((field = mono_class_get_fields (klass, &iter))) {
3346 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3349 switch (field->type->type) {
3354 case MONO_TYPE_BOOLEAN:
3357 case MONO_TYPE_CHAR:
3365 case MONO_TYPE_STRING:
3367 case MONO_TYPE_VALUETYPE:
3368 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3369 can_marshal = FALSE;
3371 case MONO_TYPE_SZARRAY: {
3372 gboolean has_mspec = FALSE;
3375 for (i = 0; i < info->num_fields; ++i) {
3376 if (info->fields [i].field == field && info->fields [i].mspec)
3381 can_marshal = FALSE;
3385 can_marshal = FALSE;
3391 /* Its hard to compute whenever these can be marshalled or not */
3392 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3399 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3401 /* Create a vtype instantiation */
3402 MonoGenericContext shared_context;
3404 MonoGenericInst *inst;
3405 MonoGenericContainer *container;
3406 MonoClass **constraints;
3409 memset (ctx, 0, sizeof (MonoGenericContext));
3411 if (method->klass->generic_container) {
3412 shared_context = method->klass->generic_container->context;
3413 inst = shared_context.class_inst;
3415 args = g_new0 (MonoType*, inst->type_argc);
3416 for (i = 0; i < inst->type_argc; ++i) {
3417 args [i] = &mono_defaults.int_class->byval_arg;
3419 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3421 if (method->is_generic) {
3422 container = mono_method_get_generic_container (method);
3423 shared_context = container->context;
3424 inst = shared_context.method_inst;
3426 args = g_new0 (MonoType*, inst->type_argc);
3427 for (i = 0; i < container->type_argc; ++i) {
3428 MonoGenericParamInfo *info = &container->type_params [i].info;
3429 gboolean ref_only = FALSE;
3431 if (info && info->constraints) {
3432 constraints = info->constraints;
3434 while (*constraints) {
3435 MonoClass *cklass = *constraints;
3436 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3437 /* Inflaring the method with our vtype would not be valid */
3444 args [i] = &mono_defaults.object_class->byval_arg;
3446 args [i] = &mono_defaults.int_class->byval_arg;
3448 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3453 add_wrappers (MonoAotCompile *acfg)
3455 MonoMethod *method, *m;
3457 MonoMethodSignature *sig, *csig;
3461 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3462 * so there is only one wrapper of a given type, or inlining their contents into their
3465 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3468 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3469 gboolean skip = FALSE;
3471 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3472 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3474 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3475 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3476 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3479 /* Skip methods which can not be handled by get_runtime_invoke () */
3480 sig = mono_method_signature (method);
3483 if ((sig->ret->type == MONO_TYPE_PTR) ||
3484 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3486 if (mono_class_is_open_constructed_type (sig->ret))
3489 for (j = 0; j < sig->param_count; j++) {
3490 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3492 if (mono_class_is_open_constructed_type (sig->params [j]))
3496 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3497 if (!mono_class_is_contextbound (method->klass)) {
3498 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3499 gboolean has_nullable = FALSE;
3501 for (j = 0; j < sig->param_count; j++) {
3502 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3503 has_nullable = TRUE;
3506 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3507 /* Supported by the dynamic runtime-invoke wrapper */
3511 mono_arch_dyn_call_free (info);
3515 if (!skip && acfg->aot_opts.llvm_only && (acfg->opts & MONO_OPT_GSHAREDVT) && mini_gsharedvt_runtime_invoke_supported (sig))
3516 /* Supported by the gsharedvt based runtime-invoke wrapper */
3520 //printf ("%s\n", mono_method_full_name (method, TRUE));
3521 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3525 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3528 /* Runtime invoke wrappers */
3530 /* void runtime-invoke () [.cctor] */
3531 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3532 csig->ret = &mono_defaults.void_class->byval_arg;
3533 add_method (acfg, get_runtime_invoke_sig (csig));
3535 /* void runtime-invoke () [Finalize] */
3536 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3538 csig->ret = &mono_defaults.void_class->byval_arg;
3539 add_method (acfg, get_runtime_invoke_sig (csig));
3541 /* void runtime-invoke (string) [exception ctor] */
3542 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3544 csig->ret = &mono_defaults.void_class->byval_arg;
3545 csig->params [0] = &mono_defaults.string_class->byval_arg;
3546 add_method (acfg, get_runtime_invoke_sig (csig));
3548 /* void runtime-invoke (string, string) [exception ctor] */
3549 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3551 csig->ret = &mono_defaults.void_class->byval_arg;
3552 csig->params [0] = &mono_defaults.string_class->byval_arg;
3553 csig->params [1] = &mono_defaults.string_class->byval_arg;
3554 add_method (acfg, get_runtime_invoke_sig (csig));
3556 /* string runtime-invoke () [Exception.ToString ()] */
3557 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3559 csig->ret = &mono_defaults.string_class->byval_arg;
3560 add_method (acfg, get_runtime_invoke_sig (csig));
3562 /* void runtime-invoke (string, Exception) [exception ctor] */
3563 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3565 csig->ret = &mono_defaults.void_class->byval_arg;
3566 csig->params [0] = &mono_defaults.string_class->byval_arg;
3567 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3568 add_method (acfg, get_runtime_invoke_sig (csig));
3570 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3571 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3573 csig->ret = &(mono_class_from_name (
3574 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3575 csig->params [0] = &mono_defaults.string_class->byval_arg;
3576 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3577 add_method (acfg, get_runtime_invoke_sig (csig));
3579 /* runtime-invoke used by finalizers */
3580 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3582 /* This is used by mono_runtime_capture_context () */
3583 method = mono_get_context_capture_method ();
3585 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3587 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3588 if (!acfg->aot_opts.llvm_only)
3589 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3592 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3593 if (acfg->aot_opts.llvm_only) {
3596 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3597 for (variants = 0; variants < 4; ++variants) {
3598 for (i = 0; i < 16; ++i) {
3599 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3600 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3608 add_method (acfg, mono_marshal_get_stelemref ());
3610 if (MONO_ARCH_HAVE_TLS_GET) {
3611 /* Managed Allocators */
3612 nallocators = mono_gc_get_managed_allocator_types ();
3613 for (i = 0; i < nallocators; ++i) {
3614 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3616 add_method (acfg, m);
3618 for (i = 0; i < nallocators; ++i) {
3619 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3621 add_method (acfg, m);
3625 /* write barriers */
3626 if (mono_gc_is_moving ()) {
3627 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3628 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3631 /* Stelemref wrappers */
3633 MonoMethod **wrappers;
3636 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3637 for (i = 0; i < nwrappers; ++i)
3638 add_method (acfg, wrappers [i]);
3642 /* castclass_with_check wrapper */
3643 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3644 /* isinst_with_check wrapper */
3645 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3647 /* JIT icall wrappers */
3648 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3649 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3653 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3654 * we use the original method instead at runtime.
3655 * Since full-aot doesn't support remoting, this is not a problem.
3658 /* remoting-invoke wrappers */
3659 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3660 MonoMethodSignature *sig;
3662 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3663 method = mono_get_method (acfg->image, token, NULL);
3665 sig = mono_method_signature (method);
3667 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3668 m = mono_marshal_get_remoting_invoke_with_check (method);
3670 add_method (acfg, m);
3675 /* delegate-invoke wrappers */
3676 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3679 MonoCustomAttrInfo *cattr;
3681 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3682 klass = mono_class_get_checked (acfg->image, token, &error);
3685 mono_error_cleanup (&error);
3689 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3692 if (!klass->generic_container) {
3693 method = mono_get_delegate_invoke (klass);
3695 m = mono_marshal_get_delegate_invoke (method, NULL);
3697 add_method (acfg, m);
3699 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3701 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3703 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3705 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3707 cattr = mono_custom_attrs_from_class (klass);
3712 for (j = 0; j < cattr->num_attrs; ++j)
3713 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3715 if (j < cattr->num_attrs) {
3717 MonoMethod *wrapper;
3718 MonoMethod *del_invoke;
3720 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3721 invoke = mono_get_delegate_invoke (klass);
3722 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3723 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3724 add_method (acfg, wrapper);
3725 add_method (acfg, del_invoke);
3728 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3730 MonoGenericContext ctx;
3731 MonoMethod *inst, *gshared;
3734 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3737 method = mono_get_delegate_invoke (klass);
3738 create_gsharedvt_inst (acfg, method, &ctx);
3740 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3741 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3743 m = mono_marshal_get_delegate_invoke (inst, NULL);
3744 g_assert (m->is_inflated);
3746 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3747 add_extra_method (acfg, gshared);
3750 method = mono_get_delegate_begin_invoke (klass);
3751 create_gsharedvt_inst (acfg, method, &ctx);
3753 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3754 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3756 m = mono_marshal_get_delegate_begin_invoke (inst);
3757 g_assert (m->is_inflated);
3759 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3760 add_extra_method (acfg, gshared);
3763 method = mono_get_delegate_end_invoke (klass);
3764 create_gsharedvt_inst (acfg, method, &ctx);
3766 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3767 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3769 m = mono_marshal_get_delegate_end_invoke (inst);
3770 g_assert (m->is_inflated);
3772 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3773 add_extra_method (acfg, gshared);
3778 /* array access wrappers */
3779 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3783 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3784 klass = mono_class_get_checked (acfg->image, token, &error);
3787 mono_error_cleanup (&error);
3791 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3792 MonoMethod *m, *wrapper;
3794 /* Add runtime-invoke wrappers too */
3796 m = mono_class_get_method_from_name (klass, "Get", -1);
3798 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3799 add_extra_method (acfg, wrapper);
3800 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3802 m = mono_class_get_method_from_name (klass, "Set", -1);
3804 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3805 add_extra_method (acfg, wrapper);
3806 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3810 /* Synchronized wrappers */
3811 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3813 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3814 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3815 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3817 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3818 if (method->is_generic) {
3820 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3822 MonoGenericContext ctx;
3823 MonoMethod *inst, *gshared, *m;
3826 * Create a generic wrapper for a generic instance, and AOT that.
3828 create_gsharedvt_inst (acfg, method, &ctx);
3829 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3830 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3831 m = mono_marshal_get_synchronized_wrapper (inst);
3832 g_assert (m->is_inflated);
3833 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3834 add_method (acfg, gshared);
3836 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3841 /* pinvoke wrappers */
3842 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3845 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3847 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3848 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3850 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3851 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3852 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3856 /* native-to-managed wrappers */
3857 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3860 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3861 MonoCustomAttrInfo *cattr;
3864 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3865 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3868 * Only generate native-to-managed wrappers for methods which have an
3869 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3870 * name to avoid defining a new assembly to contain it.
3872 cattr = mono_custom_attrs_from_method (method);
3875 for (j = 0; j < cattr->num_attrs; ++j)
3876 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3878 if (j < cattr->num_attrs) {
3879 MonoCustomAttrEntry *e = &cattr->attrs [j];
3880 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3881 const char *p = (const char*)e->data;
3883 int slen, num_named, named_type;
3887 char *export_name = NULL;
3888 MonoMethod *wrapper;
3890 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3891 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3892 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3893 mono_method_full_name (method, TRUE));
3897 g_assert (sig->param_count == 1);
3898 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3901 * Decode the cattr manually since we can't create objects
3902 * during aot compilation.
3908 /* From load_cattr_value () in reflection.c */
3909 slen = mono_metadata_decode_value (p, &p);
3910 n = (char *)g_memdup (p, slen + 1);
3912 t = mono_reflection_type_from_name (n, acfg->image);
3916 klass = mono_class_from_mono_type (t);
3917 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3921 num_named = read16 (p);
3924 g_assert (num_named < 2);
3925 if (num_named == 1) {
3929 /* parse ExportSymbol attribute */
3931 named_type = *named;
3933 /* data_type = *named; */
3936 name_len = mono_metadata_decode_blob_size (named, &named);
3937 name = (char *)g_malloc (name_len + 1);
3938 memcpy (name, named, name_len);
3939 name [name_len] = 0;
3942 g_assert (named_type == 0x54);
3943 g_assert (!strcmp (name, "ExportSymbol"));
3945 /* load_cattr_value (), string case */
3946 g_assert (*named != (char)0xff);
3947 slen = mono_metadata_decode_value (named, &named);
3948 export_name = (char *)g_malloc (slen + 1);
3949 memcpy (export_name, named, slen);
3950 export_name [slen] = 0;
3954 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3955 add_method (acfg, wrapper);
3957 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3961 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3962 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3963 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3967 /* StructureToPtr/PtrToStructure wrappers */
3968 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3972 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3973 klass = mono_class_get_checked (acfg->image, token, &error);
3976 mono_error_cleanup (&error);
3980 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3981 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3982 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3983 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3989 has_type_vars (MonoClass *klass)
3991 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3994 return has_type_vars (klass->element_class);
3995 if (klass->generic_class) {
3996 MonoGenericContext *context = &klass->generic_class->context;
3997 if (context->class_inst) {
4000 for (i = 0; i < context->class_inst->type_argc; ++i)
4001 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4005 if (klass->generic_container)
4011 is_vt_inst (MonoGenericInst *inst)
4015 for (i = 0; i < inst->type_argc; ++i) {
4016 MonoType *t = inst->type_argv [i];
4017 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4024 method_has_type_vars (MonoMethod *method)
4026 if (has_type_vars (method->klass))
4029 if (method->is_inflated) {
4030 MonoGenericContext *context = mono_method_get_context (method);
4031 if (context->method_inst) {
4034 for (i = 0; i < context->method_inst->type_argc; ++i)
4035 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4043 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4045 return opts->mode == MONO_AOT_MODE_FULL;
4048 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4051 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4053 /* This might lead to a huge code blowup so only do it if neccesary */
4054 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4057 add_generic_class_with_depth (acfg, klass, 0, ref);
4061 check_type_depth (MonoType *t, int depth)
4069 case MONO_TYPE_GENERICINST: {
4070 MonoGenericClass *gklass = t->data.generic_class;
4071 MonoGenericInst *ginst = gklass->context.class_inst;
4074 for (i = 0; i < ginst->type_argc; ++i) {
4075 if (check_type_depth (ginst->type_argv [i], depth + 1))
4089 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4092 * add_generic_class:
4094 * Add all methods of a generic class.
4097 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4100 MonoClassField *field;
4102 gboolean use_gsharedvt = FALSE;
4104 if (!acfg->ginst_hash)
4105 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4107 mono_class_init (klass);
4109 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4112 if (has_type_vars (klass))
4115 if (!klass->generic_class && !klass->rank)
4118 if (klass->exception_type)
4121 if (!acfg->ginst_hash)
4122 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4124 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4127 if (check_type_depth (&klass->byval_arg, 0))
4130 if (acfg->aot_opts.log_generics)
4131 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4133 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4136 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4137 * Enable this only for some classes since gsharedvt might not support all methods.
4139 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) &&
4140 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4141 use_gsharedvt = TRUE;
4144 while ((method = mono_class_get_methods (klass, &iter))) {
4145 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4147 * This is partial sharing, and we can't handle it yet
4152 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4154 add_types_from_method_header (acfg, method);
4158 if (method->is_generic)
4163 * FIXME: Instances which are referenced by these methods are not added,
4164 * for example Array.Resize<int> for List<int>.Add ().
4166 add_extra_method_with_depth (acfg, method, depth + 1);
4170 while ((field = mono_class_get_fields (klass, &iter))) {
4171 if (field->type->type == MONO_TYPE_GENERICINST)
4172 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4175 if (klass->delegate) {
4176 method = mono_get_delegate_invoke (klass);
4178 method = mono_marshal_get_delegate_invoke (method, NULL);
4180 if (acfg->aot_opts.log_generics)
4181 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4183 add_method (acfg, method);
4186 /* Add superclasses */
4188 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4191 * For ICollection<T>, add instances of the helper methods
4192 * in Array, since a T[] could be cast to ICollection<T>.
4194 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4195 (!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"))) {
4196 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4197 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4201 if (!strcmp (klass->name, "IEnumerator`1"))
4202 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4204 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4206 /* Add the T[]/InternalEnumerator class */
4207 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4211 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4212 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4216 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4217 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4221 while ((method = mono_class_get_methods (array_class, &iter))) {
4222 if (strstr (method->name, name_prefix)) {
4223 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4225 add_extra_method_with_depth (acfg, m, depth);
4229 g_free (name_prefix);
4232 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4233 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4234 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4235 MonoClass *icomparable, *gcomparer;
4236 MonoGenericContext ctx;
4237 MonoType *args [16];
4239 memset (&ctx, 0, sizeof (ctx));
4241 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4242 g_assert (icomparable);
4243 args [0] = &tclass->byval_arg;
4244 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4246 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4247 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4248 g_assert (gcomparer);
4249 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4253 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4254 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4255 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4256 MonoClass *iface, *gcomparer;
4257 MonoGenericContext ctx;
4258 MonoType *args [16];
4260 memset (&ctx, 0, sizeof (ctx));
4262 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4264 args [0] = &tclass->byval_arg;
4265 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4267 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4268 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4269 g_assert (gcomparer);
4270 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4274 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4275 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4276 MonoClass *enum_comparer;
4277 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4278 MonoGenericContext ctx;
4279 MonoType *args [16];
4281 if (mono_class_is_enum (tclass)) {
4282 memset (&ctx, 0, sizeof (ctx));
4283 args [0] = &tclass->byval_arg;
4284 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4286 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4287 g_assert (enum_comparer);
4288 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4292 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4293 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4294 MonoClass *comparer;
4295 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4296 MonoGenericContext ctx;
4297 MonoType *args [16];
4299 if (mono_class_is_enum (tclass)) {
4300 memset (&ctx, 0, sizeof (ctx));
4301 args [0] = &tclass->byval_arg;
4302 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4304 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4305 g_assert (comparer);
4306 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4312 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4315 MonoGenericContext ctx;
4316 MonoType *args [16];
4318 if (acfg->aot_opts.no_instances)
4321 memset (&ctx, 0, sizeof (ctx));
4323 for (i = 0; i < ninsts; ++i) {
4324 args [0] = insts [i];
4325 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4326 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4331 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4333 MonoMethodHeader *header;
4334 MonoMethodSignature *sig;
4337 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4339 sig = mono_method_signature (method);
4342 for (j = 0; j < sig->param_count; ++j)
4343 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4344 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4347 header = mono_method_get_header (method);
4350 for (j = 0; j < header->num_locals; ++j)
4351 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4352 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4354 mono_loader_clear_error ();
4359 * add_generic_instances:
4361 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4364 add_generic_instances (MonoAotCompile *acfg)
4369 MonoGenericContext *context;
4371 if (acfg->aot_opts.no_instances)
4374 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4376 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4377 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4380 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4381 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4382 mono_error_cleanup (&error);
4386 if (method->klass->image != acfg->image)
4389 context = mono_method_get_context (method);
4391 if (context && ((context->class_inst && context->class_inst->is_open)))
4395 * For open methods, create an instantiation which can be passed to the JIT.
4396 * FIXME: Handle class_inst as well.
4398 if (context && context->method_inst && context->method_inst->is_open) {
4400 MonoGenericContext shared_context;
4401 MonoGenericInst *inst;
4402 MonoType **type_argv;
4404 MonoMethod *declaring_method;
4405 gboolean supported = TRUE;
4407 /* Check that the context doesn't contain open constructed types */
4408 if (context->class_inst) {
4409 inst = context->class_inst;
4410 for (i = 0; i < inst->type_argc; ++i) {
4411 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)
4413 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4417 if (context->method_inst) {
4418 inst = context->method_inst;
4419 for (i = 0; i < inst->type_argc; ++i) {
4420 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)
4422 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4430 memset (&shared_context, 0, sizeof (MonoGenericContext));
4432 inst = context->class_inst;
4434 type_argv = g_new0 (MonoType*, inst->type_argc);
4435 for (i = 0; i < inst->type_argc; ++i) {
4436 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)
4437 type_argv [i] = &mono_defaults.object_class->byval_arg;
4439 type_argv [i] = inst->type_argv [i];
4442 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4446 inst = context->method_inst;
4448 type_argv = g_new0 (MonoType*, inst->type_argc);
4449 for (i = 0; i < inst->type_argc; ++i) {
4450 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)
4451 type_argv [i] = &mono_defaults.object_class->byval_arg;
4453 type_argv [i] = inst->type_argv [i];
4456 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4460 if (method->is_generic || method->klass->generic_container)
4461 declaring_method = method;
4463 declaring_method = mono_method_get_declaring_generic_method (method);
4465 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4466 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4470 * If the method is fully sharable, it was already added in place of its
4471 * generic definition.
4473 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4477 * FIXME: Partially shared methods are not shared here, so we end up with
4478 * many identical methods.
4480 add_extra_method (acfg, method);
4483 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4487 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4489 klass = mono_class_get_checked (acfg->image, token, &error);
4490 if (!klass || klass->rank) {
4491 mono_error_cleanup (&error);
4495 add_generic_class (acfg, klass, FALSE, "typespec");
4498 /* Add types of args/locals */
4499 for (i = 0; i < acfg->methods->len; ++i) {
4500 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4501 add_types_from_method_header (acfg, method);
4504 if (acfg->image == mono_defaults.corlib) {
4506 MonoType *insts [256];
4509 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4510 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4511 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4512 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4513 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4514 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4515 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4516 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4517 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4518 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4519 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4520 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4522 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4523 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4525 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4526 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4528 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4530 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4532 MonoClass *enum_comparer;
4533 MonoType *insts [16];
4537 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4538 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4539 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4540 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4541 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4542 g_assert (enum_comparer);
4543 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4546 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4547 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4548 g_assert (enum_comparer);
4549 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4552 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4553 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4554 g_assert (enum_comparer);
4555 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4557 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4558 g_assert (enum_comparer);
4560 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4561 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4562 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4565 /* Add instances of the array generic interfaces for primitive types */
4566 /* This will add instances of the InternalArray_ helper methods in Array too */
4567 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4569 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4570 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4572 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4573 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4575 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4578 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4579 * used for all instances of GetGenericValueImpl by the AOT runtime.
4582 MonoGenericContext ctx;
4583 MonoType *args [16];
4584 MonoMethod *get_method;
4585 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4587 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4591 memset (&ctx, 0, sizeof (ctx));
4592 args [0] = &mono_defaults.object_class->byval_arg;
4593 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4594 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4595 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4599 /* Same for CompareExchange<T>/Exchange<T> */
4601 MonoGenericContext ctx;
4602 MonoType *args [16];
4604 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4605 gpointer iter = NULL;
4607 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4608 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4610 memset (&ctx, 0, sizeof (ctx));
4611 args [0] = &mono_defaults.object_class->byval_arg;
4612 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4613 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4614 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4619 /* Same for Volatile.Read/Write<T> */
4621 MonoGenericContext ctx;
4622 MonoType *args [16];
4624 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4625 gpointer iter = NULL;
4627 if (volatile_klass) {
4628 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4629 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4631 memset (&ctx, 0, sizeof (ctx));
4632 args [0] = &mono_defaults.object_class->byval_arg;
4633 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4634 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4635 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4641 /* object[] accessor wrappers. */
4643 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4646 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4649 m = mono_marshal_get_array_accessor_wrapper (m);
4650 add_extra_method (acfg, m);
4652 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4655 m = mono_marshal_get_array_accessor_wrapper (m);
4656 add_extra_method (acfg, m);
4658 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4661 m = mono_marshal_get_array_accessor_wrapper (m);
4662 add_extra_method (acfg, m);
4668 * is_direct_callable:
4670 * Return whenever the method identified by JI is directly callable without
4671 * going through the PLT.
4674 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4676 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4677 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4679 gboolean direct_callable = TRUE;
4681 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4682 direct_callable = FALSE;
4683 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4684 // FIXME: Maybe call the wrapper directly ?
4685 direct_callable = FALSE;
4687 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4688 /* Disable this so all calls go through load_method (), see the
4689 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4690 * mono_debugger_agent_init ().
4692 direct_callable = FALSE;
4695 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4696 /* sgen does some initialization when the allocator method is created */
4697 direct_callable = FALSE;
4698 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4699 /* we don't know at compile time whether sgen is concurrent or not */
4700 direct_callable = FALSE;
4702 if (direct_callable)
4705 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4706 if (acfg->aot_opts.direct_pinvoke)
4708 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4709 if (acfg->aot_opts.direct_icalls)
4717 #ifdef MONO_ARCH_AOT_SUPPORTED
4719 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4721 MonoImage *image = method->klass->image;
4722 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4723 MonoTableInfo *tables = image->tables;
4724 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4725 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4726 guint32 im_cols [MONO_IMPLMAP_SIZE];
4729 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4733 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4736 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4738 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4741 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4743 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4750 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4752 if (a->native_offset == b->native_offset)
4753 return a->il_offset - b->il_offset;
4755 return a->native_offset - b->native_offset;
4759 * compute_line_numbers:
4761 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4764 static MonoDebugSourceLocation**
4765 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4767 MonoDebugMethodInfo *minfo;
4768 MonoDebugLineNumberEntry *ln_array;
4769 MonoDebugSourceLocation *loc;
4770 int i, prev_line, prev_il_offset;
4771 int *native_to_il_offset = NULL;
4772 MonoDebugSourceLocation **res;
4775 minfo = mono_debug_lookup_method (method);
4778 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4779 if (debug_info->code_size != code_size)
4782 g_assert (code_size);
4784 /* Compute the native->IL offset mapping */
4786 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4787 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4789 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4791 native_to_il_offset = g_new0 (int, code_size + 1);
4793 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4795 MonoDebugLineNumberEntry *lne = &ln_array [i];
4798 for (j = 0; j < lne->native_offset; ++j)
4799 native_to_il_offset [j] = -1;
4802 if (i < debug_info->num_line_numbers - 1) {
4803 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4805 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4806 native_to_il_offset [j] = lne->il_offset;
4808 for (j = lne->native_offset; j < code_size; ++j)
4809 native_to_il_offset [j] = lne->il_offset;
4814 /* Compute the native->line number mapping */
4815 res = g_new0 (MonoDebugSourceLocation*, code_size);
4816 prev_il_offset = -1;
4819 for (i = 0; i < code_size; ++i) {
4820 int il_offset = native_to_il_offset [i];
4822 if (il_offset == -1 || il_offset == prev_il_offset)
4824 prev_il_offset = il_offset;
4825 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4826 if (!(loc && loc->source_file))
4828 if (loc->row == prev_line) {
4829 mono_debug_symfile_free_location (loc);
4832 prev_line = loc->row;
4833 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4835 /* This will cover the prolog too */
4845 get_file_index (MonoAotCompile *acfg, const char *source_file)
4849 // FIXME: Free these
4850 if (!acfg->dwarf_ln_filenames)
4851 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4852 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4854 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4855 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4856 emit_unset_mode (acfg);
4857 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4869 * emit_and_reloc_code:
4871 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4872 * is true, calls are made through the GOT too. This is used for emitting trampolines
4873 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4874 * since trampolines are needed to make PTL work.
4877 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4879 int i, pindex, start_index;
4881 MonoJumpInfo *patch_info;
4882 MonoDebugSourceLocation **locs = NULL;
4884 #ifdef MONO_ARCH_AOT_SUPPORTED
4885 gboolean direct_call, external_call;
4887 const char *direct_call_target = 0;
4888 const char *direct_pinvoke;
4891 if (acfg->gas_line_numbers && method && debug_info) {
4892 locs = compute_line_numbers (method, code_len, debug_info);
4894 int findex = get_file_index (acfg, "<unknown>");
4895 emit_unset_mode (acfg);
4896 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4900 /* Collect and sort relocations */
4901 patches = g_ptr_array_new ();
4902 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4903 g_ptr_array_add (patches, patch_info);
4904 g_ptr_array_sort (patches, compare_patches);
4907 for (i = 0; i < code_len; i += INST_LEN) {
4909 for (pindex = start_index; pindex < patches->len; ++pindex) {
4910 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4911 if (patch_info->ip.i >= i)
4915 if (locs && locs [i]) {
4916 MonoDebugSourceLocation *loc = locs [i];
4919 findex = get_file_index (acfg, loc->source_file);
4920 emit_unset_mode (acfg);
4921 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4922 mono_debug_symfile_free_location (loc);
4926 #ifdef MONO_ARCH_AOT_SUPPORTED
4927 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4928 start_index = pindex;
4930 switch (patch_info->type) {
4931 case MONO_PATCH_INFO_NONE:
4933 case MONO_PATCH_INFO_GOT_OFFSET: {
4936 arch_emit_got_offset (acfg, code + i, &code_size);
4937 i += code_size - INST_LEN;
4939 patch_info->type = MONO_PATCH_INFO_NONE;
4942 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4943 int code_size, index;
4944 char *selector = (char *)patch_info->data.target;
4946 if (!acfg->objc_selector_to_index)
4947 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4948 if (!acfg->objc_selectors)
4949 acfg->objc_selectors = g_ptr_array_new ();
4950 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4954 index = acfg->objc_selector_index;
4955 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4956 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4957 acfg->objc_selector_index ++;
4960 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4961 i += code_size - INST_LEN;
4963 patch_info->type = MONO_PATCH_INFO_NONE;
4968 * If this patch is a call, try emitting a direct call instead of
4969 * through a PLT entry. This is possible if the called method is in
4970 * the same assembly and requires no initialization.
4972 direct_call = FALSE;
4973 external_call = FALSE;
4974 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4975 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4976 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4977 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4979 direct_call_target = callee_cfg->asm_symbol;
4980 patch_info->type = MONO_PATCH_INFO_NONE;
4981 acfg->stats.direct_calls ++;
4984 acfg->stats.all_calls ++;
4985 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4986 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4987 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4988 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4990 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4991 if (direct_pinvoke) {
4993 g_assert (strlen (direct_pinvoke) < 1000);
4994 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4997 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4998 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4999 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5000 /* Call to a C function implementing a jit icall */
5002 external_call = TRUE;
5003 g_assert (strlen (sym) < 1000);
5004 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5006 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5007 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5008 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5009 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5010 /* Call to a jit icall without a wrapper */
5012 external_call = TRUE;
5013 g_assert (strlen (sym) < 1000);
5014 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5019 patch_info->type = MONO_PATCH_INFO_NONE;
5020 acfg->stats.direct_calls ++;
5023 if (!got_only && !direct_call) {
5024 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5026 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5028 direct_call_target = plt_entry->symbol;
5030 /* Nullify the patch */
5031 patch_info->type = MONO_PATCH_INFO_NONE;
5032 plt_entry->jit_used = TRUE;
5039 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5040 i += call_size - INST_LEN;
5044 got_slot = get_got_offset (acfg, FALSE, patch_info);
5046 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5047 i += code_size - INST_LEN;
5053 #endif /* MONO_ARCH_AOT_SUPPORTED */
5056 /* Find next patch */
5058 for (pindex = start_index; pindex < patches->len; ++pindex) {
5059 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5060 if (patch_info->ip.i >= i)
5064 /* Try to emit multiple bytes at once */
5065 if (pindex < patches->len && patch_info->ip.i > i) {
5068 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5069 if (locs && locs [limit])
5073 emit_code_bytes (acfg, code + i, limit - i);
5074 i = limit - INST_LEN;
5076 emit_code_bytes (acfg, code + i, INST_LEN);
5087 * Return a modified version of S which only includes characters permissible in symbols.
5090 sanitize_symbol (MonoAotCompile *acfg, char *s)
5092 gboolean process = FALSE;
5101 for (i = 0; i < len; ++i)
5102 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5107 gs = g_string_sized_new (len);
5108 for (i = 0; i < len; ++i) {
5110 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5111 g_string_append_c (gs, c);
5112 } else if (c > 0x7f) {
5113 /* multi-byte utf8 */
5114 g_string_append_printf (gs, "_0x%x", c);
5117 while (c >> 6 == 0x2) {
5118 g_string_append_printf (gs, "%x", c);
5122 g_string_append_printf (gs, "_");
5125 g_string_append_c (gs, '_');
5129 res = mono_mempool_strdup (acfg->mempool, gs->str);
5130 g_string_free (gs, TRUE);
5135 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5137 char *name1, *name2, *cached;
5138 int i, j, len, count;
5139 MonoMethod *cached_method;
5141 name1 = mono_method_full_name (method, TRUE);
5144 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5145 if ((!prefix || !*prefix) && name1 [0] == 'L')
5149 len = strlen (name1);
5150 name2 = (char *)malloc (strlen (prefix) + len + 16);
5151 memcpy (name2, prefix, strlen (prefix));
5152 j = strlen (prefix);
5153 for (i = 0; i < len; ++i) {
5154 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5156 } else if (isalnum (name1 [i])) {
5157 name2 [j ++] = name1 [i];
5158 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5160 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5163 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5173 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5174 if (!(cached_method && cached_method != method))
5176 sprintf (name2 + j, "_%d", count);
5180 cached = g_strdup (name2);
5181 g_hash_table_insert (cache, cached, method);
5187 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5192 char *debug_sym = NULL;
5193 char *symbol = NULL;
5194 int func_alignment = AOT_FUNC_ALIGNMENT;
5197 method = cfg->orig_method;
5198 code = cfg->native_code;
5200 method_index = get_method_index (acfg, method);
5201 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5203 /* Make the labels local */
5204 emit_section_change (acfg, ".text", 0);
5205 emit_alignment_code (acfg, func_alignment);
5207 if (acfg->global_symbols && acfg->need_no_dead_strip)
5208 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5210 emit_label (acfg, cfg->asm_symbol);
5212 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5214 * Write a C style symbol for every method, this has two uses:
5215 * - it works on platforms where the dwarf debugging info is not
5217 * - it allows the setting of breakpoints of aot-ed methods.
5219 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5220 cfg->asm_debug_symbol = g_strdup (debug_sym);
5222 if (acfg->need_no_dead_strip)
5223 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5224 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5225 emit_label (acfg, debug_sym);
5228 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5230 /* Emit a global symbol for the method */
5231 emit_global_inner (acfg, export_name, TRUE);
5232 emit_label (acfg, export_name);
5235 if (cfg->verbose_level > 0)
5236 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5238 acfg->stats.code_size += cfg->code_len;
5240 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5242 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 ()));
5246 if (acfg->aot_opts.write_symbols) {
5248 emit_symbol_size (acfg, debug_sym, ".");
5250 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5254 emit_label (acfg, symbol);
5261 * Encode PATCH_INFO into its disk representation.
5264 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5268 switch (patch_info->type) {
5269 case MONO_PATCH_INFO_NONE:
5271 case MONO_PATCH_INFO_IMAGE:
5272 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5274 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5275 case MONO_PATCH_INFO_JIT_TLS_ID:
5276 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5277 case MONO_PATCH_INFO_GC_NURSERY_START:
5278 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5280 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5281 encode_value (patch_info->data.index, p, &p);
5283 case MONO_PATCH_INFO_METHOD_REL:
5284 encode_value ((gint)patch_info->data.offset, p, &p);
5286 case MONO_PATCH_INFO_SWITCH: {
5287 gpointer *table = (gpointer *)patch_info->data.table->table;
5290 encode_value (patch_info->data.table->table_size, p, &p);
5291 for (k = 0; k < patch_info->data.table->table_size; k++)
5292 encode_value ((int)(gssize)table [k], p, &p);
5295 case MONO_PATCH_INFO_METHODCONST:
5296 case MONO_PATCH_INFO_METHOD:
5297 case MONO_PATCH_INFO_METHOD_JUMP:
5298 case MONO_PATCH_INFO_ICALL_ADDR:
5299 case MONO_PATCH_INFO_METHOD_RGCTX:
5300 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5301 encode_method_ref (acfg, patch_info->data.method, p, &p);
5303 case MONO_PATCH_INFO_AOT_JIT_INFO:
5304 encode_value (patch_info->data.index, p, &p);
5306 case MONO_PATCH_INFO_INTERNAL_METHOD:
5307 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5308 guint32 len = strlen (patch_info->data.name);
5310 encode_value (len, p, &p);
5312 memcpy (p, patch_info->data.name, len);
5317 case MONO_PATCH_INFO_LDSTR: {
5318 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5319 guint32 token = patch_info->data.token->token;
5320 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5321 encode_value (image_index, p, &p);
5322 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5325 case MONO_PATCH_INFO_RVA:
5326 case MONO_PATCH_INFO_DECLSEC:
5327 case MONO_PATCH_INFO_LDTOKEN:
5328 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5329 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5330 encode_value (patch_info->data.token->token, p, &p);
5331 encode_value (patch_info->data.token->has_context, p, &p);
5332 if (patch_info->data.token->has_context)
5333 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5335 case MONO_PATCH_INFO_EXC_NAME: {
5336 MonoClass *ex_class;
5339 mono_class_from_name (mono_defaults.exception_class->image,
5340 "System", (const char *)patch_info->data.target);
5341 g_assert (ex_class);
5342 encode_klass_ref (acfg, ex_class, p, &p);
5345 case MONO_PATCH_INFO_R4:
5346 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5348 case MONO_PATCH_INFO_R8:
5349 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5350 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5352 case MONO_PATCH_INFO_VTABLE:
5353 case MONO_PATCH_INFO_CLASS:
5354 case MONO_PATCH_INFO_IID:
5355 case MONO_PATCH_INFO_ADJUSTED_IID:
5356 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5358 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5359 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5360 if (patch_info->data.del_tramp->method) {
5361 encode_value (1, p, &p);
5362 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5364 encode_value (0, p, &p);
5366 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5368 case MONO_PATCH_INFO_FIELD:
5369 case MONO_PATCH_INFO_SFLDA:
5370 encode_field_info (acfg, patch_info->data.field, p, &p);
5372 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5374 case MONO_PATCH_INFO_RGCTX_FETCH:
5375 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5376 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5381 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5382 * reference the same method, so encode the method only once.
5384 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5386 buf2 = (guint8 *)g_malloc (1024);
5389 encode_method_ref (acfg, entry->method, p2, &p2);
5390 g_assert (p2 - buf2 < 1024);
5392 offset = add_to_blob (acfg, buf2, p2 - buf2);
5395 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5400 encode_value (offset, p, &p);
5401 g_assert ((int)entry->info_type < 256);
5402 g_assert (entry->data->type < 256);
5403 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5404 encode_patch (acfg, entry->data, p, &p);
5407 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5408 case MONO_PATCH_INFO_AOT_MODULE:
5410 case MONO_PATCH_INFO_SIGNATURE:
5411 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5413 case MONO_PATCH_INFO_TLS_OFFSET:
5414 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5416 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5417 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5418 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5420 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5421 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5424 encode_method_ref (acfg, info->method, p, &p);
5425 encode_value (info->num_entries, p, &p);
5426 for (i = 0; i < info->num_entries; ++i) {
5427 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5429 encode_value (template_->info_type, p, &p);
5430 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5431 case MONO_PATCH_INFO_CLASS:
5432 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5434 case MONO_PATCH_INFO_FIELD:
5435 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5438 g_assert_not_reached ();
5444 case MONO_PATCH_INFO_LDSTR_LIT: {
5445 const char *s = (const char *)patch_info->data.target;
5446 int len = strlen (s);
5448 encode_value (len, p, &p);
5449 memcpy (p, s, len + 1);
5453 case MONO_PATCH_INFO_VIRT_METHOD:
5454 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5455 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5457 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5460 g_warning ("unable to handle jump info %d", patch_info->type);
5461 g_assert_not_reached ();
5468 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5471 guint32 pindex, offset;
5472 MonoJumpInfo *patch_info;
5474 encode_value (n_patches, p, &p);
5476 for (pindex = 0; pindex < patches->len; ++pindex) {
5477 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5479 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5483 offset = get_got_offset (acfg, llvm, patch_info);
5484 encode_value (offset, p, &p);
5491 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5494 int pindex, buf_size, n_patches;
5496 MonoJumpInfo *patch_info;
5497 guint32 method_index;
5499 guint32 first_got_offset;
5501 method = cfg->orig_method;
5503 method_index = get_method_index (acfg, method);
5505 /* Sort relocations */
5506 patches = g_ptr_array_new ();
5507 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5508 g_ptr_array_add (patches, patch_info);
5509 g_ptr_array_sort (patches, compare_patches);
5511 first_got_offset = acfg->cfgs [method_index]->got_offset;
5513 /**********************/
5514 /* Encode method info */
5515 /**********************/
5517 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5518 p = buf = (guint8 *)g_malloc (buf_size);
5520 if (mono_class_get_cctor (method->klass))
5521 encode_klass_ref (acfg, method->klass, p, &p);
5523 /* Not needed when loading the method */
5524 encode_value (0, p, &p);
5526 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5529 for (pindex = 0; pindex < patches->len; ++pindex) {
5530 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5532 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5533 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5534 patch_info->type = MONO_PATCH_INFO_NONE;
5539 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5540 /* Stored in a GOT slot initialized at module load time */
5541 patch_info->type = MONO_PATCH_INFO_NONE;
5545 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5546 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5547 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5548 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5549 /* Stored in a GOT slot initialized at module load time */
5550 patch_info->type = MONO_PATCH_INFO_NONE;
5554 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5555 /* Calls are made through the PLT */
5556 patch_info->type = MONO_PATCH_INFO_NONE;
5564 g_assert (cfg->has_got_slots);
5566 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5568 acfg->stats.info_size += p - buf;
5570 g_assert (p - buf < buf_size);
5572 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5577 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5579 guint32 cache_index;
5582 /* Reuse the unwind module to canonize and store unwind info entries */
5583 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5585 /* Use +/- 1 to distinguish 0s from missing entries */
5586 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5594 * It would be easier to use assembler symbols, but the caller needs an
5597 offset = acfg->unwind_info_offset;
5598 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5599 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5602 encode_value (encoded_len, p, &p);
5604 acfg->unwind_info_offset += encoded_len + (p - buf);
5610 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5613 guint32 debug_info_size, seq_points_size;
5615 MonoMethodHeader *header;
5616 guint8 *p, *buf, *debug_info;
5617 MonoJitInfo *jinfo = cfg->jit_info;
5619 gboolean use_unwind_ops = FALSE;
5620 MonoSeqPointInfo *seq_points;
5622 code = cfg->native_code;
5623 header = cfg->header;
5625 if (!acfg->aot_opts.nodebug) {
5626 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5629 debug_info_size = 0;
5632 seq_points = cfg->seq_point_info;
5633 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5635 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5637 p = buf = (guint8 *)g_malloc (buf_size);
5639 use_unwind_ops = cfg->unwind_ops != NULL;
5641 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 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);
5643 encode_value (flags, p, &p);
5645 if (use_unwind_ops) {
5646 guint32 encoded_len;
5648 guint32 unwind_desc;
5650 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5652 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5653 encode_value (unwind_desc, p, &p);
5655 encode_value (jinfo->unwind_info, p, &p);
5658 /*Encode the number of holes before the number of clauses to make decoding easier*/
5659 if (jinfo->has_try_block_holes) {
5660 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5661 encode_value (table->num_holes, p, &p);
5664 if (jinfo->has_arch_eh_info) {
5666 * In AOT mode, the code length is calculated from the address of the previous method,
5667 * which could include alignment padding, so calculating the start of the epilog as
5668 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5670 encode_value (jinfo->code_size, p, &p);
5673 /* Exception table */
5674 if (cfg->compile_llvm) {
5676 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5677 * since the information is only available to llc. Instead, we let llc save the data
5678 * into the LSDA, and read it from there at runtime.
5680 /* The assembly might be CIL stripped so emit the data ourselves */
5681 if (header->num_clauses)
5682 encode_value (header->num_clauses, p, &p);
5684 for (k = 0; k < header->num_clauses; ++k) {
5685 MonoExceptionClause *clause;
5687 clause = &header->clauses [k];
5689 encode_value (clause->flags, p, &p);
5690 if (clause->data.catch_class) {
5691 encode_value (1, p, &p);
5692 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5694 encode_value (0, p, &p);
5697 /* Emit the IL ranges too, since they might not be available at runtime */
5698 encode_value (clause->try_offset, p, &p);
5699 encode_value (clause->try_len, p, &p);
5700 encode_value (clause->handler_offset, p, &p);
5701 encode_value (clause->handler_len, p, &p);
5703 /* Emit a list of nesting clauses */
5704 for (i = 0; i < header->num_clauses; ++i) {
5706 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5708 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5710 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5711 encode_value (i, p, &p);
5713 encode_value (-1, p, &p);
5716 if (jinfo->num_clauses)
5717 encode_value (jinfo->num_clauses, p, &p);
5719 for (k = 0; k < jinfo->num_clauses; ++k) {
5720 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5722 encode_value (ei->flags, p, &p);
5723 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5724 /* Not used for catch clauses */
5725 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5726 encode_value (ei->exvar_offset, p, &p);
5728 encode_value (ei->exvar_offset, p, &p);
5731 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5732 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5734 if (ei->data.catch_class) {
5738 buf2 = (guint8 *)g_malloc (4096);
5740 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5742 g_assert (len < 4096);
5743 encode_value (len, p, &p);
5744 memcpy (p, buf2, len);
5748 encode_value (0, p, &p);
5752 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5753 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5754 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5758 if (jinfo->has_try_block_holes) {
5759 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5760 for (i = 0; i < table->num_holes; ++i) {
5761 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5762 encode_value (hole->clause, p, &p);
5763 encode_value (hole->length, p, &p);
5764 encode_value (hole->offset, p, &p);
5768 if (jinfo->has_arch_eh_info) {
5769 MonoArchEHJitInfo *eh_info;
5771 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5772 encode_value (eh_info->stack_size, p, &p);
5773 encode_value (eh_info->epilog_size, p, &p);
5776 if (jinfo->has_generic_jit_info) {
5777 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5778 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5782 encode_value (gi->nlocs, p, &p);
5784 for (i = 0; i < gi->nlocs; ++i) {
5785 MonoDwarfLocListEntry *entry = &gi->locations [i];
5787 encode_value (entry->is_reg ? 1 : 0, p, &p);
5788 encode_value (entry->reg, p, &p);
5790 encode_value (entry->offset, p, &p);
5792 g_assert (entry->from == 0);
5794 encode_value (entry->from, p, &p);
5795 encode_value (entry->to, p, &p);
5798 if (!cfg->compile_llvm) {
5799 encode_value (gi->has_this ? 1 : 0, p, &p);
5800 encode_value (gi->this_reg, p, &p);
5801 encode_value (gi->this_offset, p, &p);
5806 * Need to encode jinfo->method too, since it is not equal to 'method'
5807 * when using generic sharing.
5809 buf2 = (guint8 *)g_malloc (4096);
5811 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5813 g_assert (len < 4096);
5814 encode_value (len, p, &p);
5815 memcpy (p, buf2, len);
5819 if (gsctx && gsctx->is_gsharedvt) {
5820 encode_value (1, p, &p);
5822 encode_value (0, p, &p);
5826 if (seq_points_size)
5827 p += mono_seq_point_info_write (seq_points, p);
5829 g_assert (debug_info_size < buf_size);
5831 encode_value (debug_info_size, p, &p);
5832 if (debug_info_size) {
5833 memcpy (p, debug_info, debug_info_size);
5834 p += debug_info_size;
5835 g_free (debug_info);
5840 encode_value (cfg->gc_map_size, p, &p);
5841 /* The GC map requires 4 bytes of alignment */
5842 while ((gsize)p % 4)
5844 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5845 p += cfg->gc_map_size;
5848 acfg->stats.ex_info_size += p - buf;
5850 g_assert (p - buf < buf_size);
5853 /* The GC Map requires 4 byte alignment */
5854 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5859 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5862 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5864 int i, buf_size, res;
5865 gboolean no_special_static, cant_encode;
5866 gpointer iter = NULL;
5869 mono_error_cleanup (&error);
5873 p = buf = (guint8 *)g_malloc (buf_size);
5875 /* Mark as unusable */
5876 encode_value (-1, p, &p);
5878 res = add_to_blob (acfg, buf, p - buf);
5884 buf_size = 10240 + (klass->vtable_size * 16);
5885 p = buf = (guint8 *)g_malloc (buf_size);
5889 mono_class_init (klass);
5891 mono_class_get_nested_types (klass, &iter);
5892 g_assert (klass->nested_classes_inited);
5894 mono_class_setup_vtable (klass);
5897 * Emit all the information which is required for creating vtables so
5898 * the runtime does not need to create the MonoMethod structures which
5899 * take up a lot of space.
5902 no_special_static = !mono_class_has_special_static_fields (klass);
5904 /* Check whenever we have enough info to encode the vtable */
5905 cant_encode = FALSE;
5906 for (i = 0; i < klass->vtable_size; ++i) {
5907 MonoMethod *cm = klass->vtable [i];
5909 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5913 mono_class_has_finalizer (klass);
5915 if (klass->generic_container || cant_encode) {
5916 encode_value (-1, p, &p);
5918 encode_value (klass->vtable_size, p, &p);
5919 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);
5920 if (klass->has_cctor)
5921 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5922 if (klass->has_finalize)
5923 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5925 encode_value (klass->instance_size, p, &p);
5926 encode_value (mono_class_data_size (klass), p, &p);
5927 encode_value (klass->packing_size, p, &p);
5928 encode_value (klass->min_align, p, &p);
5930 for (i = 0; i < klass->vtable_size; ++i) {
5931 MonoMethod *cm = klass->vtable [i];
5934 encode_method_ref (acfg, cm, p, &p);
5936 encode_value (0, p, &p);
5940 acfg->stats.class_info_size += p - buf;
5942 g_assert (p - buf < buf_size);
5943 res = add_to_blob (acfg, buf, p - buf);
5950 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5952 char *debug_sym = NULL;
5955 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5956 /* Need to add a prefix to create unique symbols */
5957 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5959 prefix = g_strdup ("plt_");
5963 case MONO_PATCH_INFO_METHOD:
5964 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5966 case MONO_PATCH_INFO_INTERNAL_METHOD:
5967 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5969 case MONO_PATCH_INFO_RGCTX_FETCH:
5970 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5972 case MONO_PATCH_INFO_ICALL_ADDR: {
5973 char *s = get_debug_sym (ji->data.method, "", cache);
5975 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5979 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5980 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5988 return sanitize_symbol (acfg, debug_sym);
5992 * Calls made from AOTed code are routed through a table of jumps similar to the
5993 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5994 * control to the AOT runtime through a trampoline.
5997 emit_plt (MonoAotCompile *acfg)
6001 if (acfg->aot_opts.llvm_only) {
6002 g_assert (acfg->plt_offset == 1);
6008 emit_section_change (acfg, ".text", 0);
6009 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6010 emit_info_symbol (acfg, "plt");
6011 emit_label (acfg, acfg->plt_symbol);
6013 for (i = 0; i < acfg->plt_offset; ++i) {
6014 char *debug_sym = NULL;
6015 MonoPltEntry *plt_entry = NULL;
6019 * The first plt entry is unused.
6023 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6025 debug_sym = plt_entry->debug_sym;
6027 if (acfg->thumb_mixed && !plt_entry->jit_used)
6028 /* Emit only a thumb version */
6031 /* Skip plt entries not actually called */
6032 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6035 if (acfg->llvm && !acfg->thumb_mixed) {
6036 emit_label (acfg, plt_entry->llvm_symbol);
6038 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6039 #if defined(TARGET_MACH)
6040 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6046 if (acfg->need_no_dead_strip) {
6047 emit_unset_mode (acfg);
6048 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6050 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6051 emit_label (acfg, debug_sym);
6054 emit_label (acfg, plt_entry->symbol);
6056 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6059 emit_symbol_size (acfg, debug_sym, ".");
6062 if (acfg->thumb_mixed) {
6063 /* Make sure the ARM symbols don't alias the thumb ones */
6064 emit_zero_bytes (acfg, 16);
6067 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6070 for (i = 0; i < acfg->plt_offset; ++i) {
6071 char *debug_sym = NULL;
6072 MonoPltEntry *plt_entry = NULL;
6077 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6079 /* Skip plt entries not actually called by LLVM code */
6080 if (!plt_entry->llvm_used)
6083 if (acfg->aot_opts.write_symbols) {
6084 if (plt_entry->debug_sym)
6085 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6089 #if defined(TARGET_MACH)
6090 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6091 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6093 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6094 emit_label (acfg, debug_sym);
6096 fprintf (acfg->fp, "\n.thumb_func\n");
6098 emit_label (acfg, plt_entry->llvm_symbol);
6101 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6103 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6106 emit_symbol_size (acfg, debug_sym, ".");
6112 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6114 emit_info_symbol (acfg, "plt_end");
6118 * emit_trampoline_full:
6120 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6121 * create_jit_info_for_trampoline ().
6123 static G_GNUC_UNUSED void
6124 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6126 char start_symbol [256];
6127 char end_symbol [256];
6129 guint32 buf_size, info_offset;
6130 MonoJumpInfo *patch_info;
6143 code_size = info->code_size;
6145 unwind_ops = info->unwind_ops;
6147 #ifdef __native_client_codegen__
6148 mono_nacl_fix_patches (code, ji);
6153 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6155 emit_section_change (acfg, ".text", 0);
6156 emit_global (acfg, start_symbol, TRUE);
6157 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6158 emit_label (acfg, start_symbol);
6160 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6161 emit_label (acfg, symbol);
6164 * The code should access everything through the GOT, so we pass
6167 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6169 emit_symbol_size (acfg, start_symbol, ".");
6172 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6173 emit_label (acfg, end_symbol);
6178 /* Sort relocations */
6179 patches = g_ptr_array_new ();
6180 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6181 if (patch_info->type != MONO_PATCH_INFO_NONE)
6182 g_ptr_array_add (patches, patch_info);
6183 g_ptr_array_sort (patches, compare_patches);
6185 buf_size = patches->len * 128 + 128;
6186 buf = (guint8 *)g_malloc (buf_size);
6189 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6190 g_assert (p - buf < buf_size);
6192 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6194 info_offset = add_to_blob (acfg, buf, p - buf);
6196 emit_section_change (acfg, RODATA_SECT, 0);
6197 emit_global (acfg, symbol, FALSE);
6198 emit_label (acfg, symbol);
6200 emit_int32 (acfg, info_offset);
6204 guint32 encoded_len;
6208 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6210 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6211 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6214 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6215 emit_int32 (acfg, uw_offset);
6218 /* Emit debug info */
6222 sprintf (symbol, "%s", name);
6223 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6226 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6230 static G_GNUC_UNUSED void
6231 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6233 emit_trampoline_full (acfg, got_offset, info, TRUE);
6237 emit_trampolines (MonoAotCompile *acfg)
6240 char end_symbol [256];
6241 int i, tramp_got_offset;
6243 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6247 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6250 g_assert (acfg->image->assembly);
6252 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6253 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6254 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6255 MonoTrampInfo *info;
6258 * Emit the generic trampolines.
6260 * We could save some code by treating the generic trampolines as a wrapper
6261 * method, but that approach has its own complexities, so we choose the simpler
6264 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6265 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6266 #ifdef DISABLE_REMOTING
6267 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6270 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6271 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6274 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6275 emit_trampoline (acfg, acfg->got_offset, info);
6278 /* Emit the exception related code pieces */
6279 mono_arch_get_restore_context (&info, TRUE);
6280 emit_trampoline (acfg, acfg->got_offset, info);
6281 mono_arch_get_call_filter (&info, TRUE);
6282 emit_trampoline (acfg, acfg->got_offset, info);
6283 mono_arch_get_throw_exception (&info, TRUE);
6284 emit_trampoline (acfg, acfg->got_offset, info);
6285 mono_arch_get_rethrow_exception (&info, TRUE);
6286 emit_trampoline (acfg, acfg->got_offset, info);
6287 mono_arch_get_throw_corlib_exception (&info, TRUE);
6288 emit_trampoline (acfg, acfg->got_offset, info);
6290 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6291 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6292 emit_trampoline (acfg, acfg->got_offset, info);
6293 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6294 emit_trampoline (acfg, acfg->got_offset, info);
6297 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6298 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6300 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6302 /* Create a separate out trampoline for more information in stack traces */
6303 info->name = g_strdup ("gsharedvt_out_trampoline");
6304 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6308 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6310 GSList *l = mono_arch_get_trampolines (TRUE);
6313 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6315 emit_trampoline (acfg, acfg->got_offset, info);
6321 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6324 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6325 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6326 emit_trampoline (acfg, acfg->got_offset, info);
6328 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6329 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6330 emit_trampoline (acfg, acfg->got_offset, info);
6333 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6334 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6335 emit_trampoline (acfg, acfg->got_offset, info);
6341 /* delegate_invoke_impl trampolines */
6342 l = mono_arch_get_delegate_invoke_impls ();
6344 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6346 emit_trampoline (acfg, acfg->got_offset, info);
6351 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6353 /* Emit trampolines which are numerous */
6356 * These include the following:
6357 * - specific trampolines
6358 * - static rgctx invoke trampolines
6360 * These trampolines have the same code, they are parameterized by GOT
6362 * They are defined in this file, in the arch_... routines instead of
6363 * in tramp-<ARCH>.c, since it is easier to do it this way.
6367 * When running in aot-only mode, we can't create specific trampolines at
6368 * runtime, so we create a few, and save them in the AOT file.
6369 * Normal trampolines embed their argument as a literal inside the
6370 * trampoline code, we can't do that here, so instead we embed an offset
6371 * which needs to be added to the trampoline address to get the address of
6372 * the GOT slot which contains the argument value.
6373 * The generated trampolines jump to the generic trampolines using another
6374 * GOT slot, which will be setup by the AOT loader to point to the
6375 * generic trampoline code of the given type.
6379 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6383 emit_section_change (acfg, ".text", 0);
6385 tramp_got_offset = acfg->got_offset;
6387 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6389 case MONO_AOT_TRAMP_SPECIFIC:
6390 sprintf (symbol, "specific_trampolines");
6392 case MONO_AOT_TRAMP_STATIC_RGCTX:
6393 sprintf (symbol, "static_rgctx_trampolines");
6395 case MONO_AOT_TRAMP_IMT_THUNK:
6396 sprintf (symbol, "imt_thunks");
6398 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6399 sprintf (symbol, "gsharedvt_arg_trampolines");
6402 g_assert_not_reached ();
6405 sprintf (end_symbol, "%s_e", symbol);
6407 if (acfg->aot_opts.write_symbols)
6408 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6410 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6411 emit_info_symbol (acfg, symbol);
6413 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6415 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6419 case MONO_AOT_TRAMP_SPECIFIC:
6420 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6421 tramp_got_offset += 2;
6423 case MONO_AOT_TRAMP_STATIC_RGCTX:
6424 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6425 tramp_got_offset += 2;
6427 case MONO_AOT_TRAMP_IMT_THUNK:
6428 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6429 tramp_got_offset += 1;
6431 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6432 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6433 tramp_got_offset += 2;
6436 g_assert_not_reached ();
6438 #ifdef __native_client_codegen__
6439 /* align to avoid 32-byte boundary crossings */
6440 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6443 if (!acfg->trampoline_size [ntype]) {
6444 g_assert (tramp_size);
6445 acfg->trampoline_size [ntype] = tramp_size;
6449 emit_label (acfg, end_symbol);
6450 emit_int32 (acfg, 0);
6453 arch_emit_specific_trampoline_pages (acfg);
6455 /* Reserve some entries at the end of the GOT for our use */
6456 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6459 acfg->got_offset += acfg->num_trampoline_got_entries;
6463 str_begins_with (const char *str1, const char *str2)
6465 int len = strlen (str2);
6466 return strncmp (str1, str2, len) == 0;
6470 mono_aot_readonly_field_override (MonoClassField *field)
6473 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6474 char *p = rdv->name;
6476 len = strlen (field->parent->name_space);
6477 if (strncmp (p, field->parent->name_space, len))
6482 len = strlen (field->parent->name);
6483 if (strncmp (p, field->parent->name, len))
6488 if (strcmp (p, field->name))
6490 switch (rdv->type) {
6492 return &rdv->value.i1;
6494 return &rdv->value.i2;
6496 return &rdv->value.i4;
6505 add_readonly_value (MonoAotOptions *opts, const char *val)
6510 /* the format of val is:
6511 * namespace.typename.fieldname=type/value
6512 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6514 fval = strrchr (val, '/');
6516 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6519 tval = strrchr (val, '=');
6521 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6524 rdv = g_new0 (ReadOnlyValue, 1);
6525 rdv->name = (char *)g_malloc0 (tval - val + 1);
6526 memcpy (rdv->name, val, tval - val);
6529 if (strncmp (tval, "i1", 2) == 0) {
6530 rdv->value.i1 = atoi (fval);
6531 rdv->type = MONO_TYPE_I1;
6532 } else if (strncmp (tval, "i2", 2) == 0) {
6533 rdv->value.i2 = atoi (fval);
6534 rdv->type = MONO_TYPE_I2;
6535 } else if (strncmp (tval, "i4", 2) == 0) {
6536 rdv->value.i4 = atoi (fval);
6537 rdv->type = MONO_TYPE_I4;
6539 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6542 rdv->next = readonly_values;
6543 readonly_values = rdv;
6547 clean_path (gchar * path)
6552 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6555 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6562 mono_aot_split_options (const char *aot_options)
6564 enum MonoAotOptionState {
6565 MONO_AOT_OPTION_STATE_DEFAULT,
6566 MONO_AOT_OPTION_STATE_STRING,
6567 MONO_AOT_OPTION_STATE_ESCAPE,
6570 GPtrArray *args = g_ptr_array_new ();
6571 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6572 gchar const *opt_start = aot_options;
6573 gboolean end_of_string = FALSE;
6576 g_return_val_if_fail (aot_options != NULL, NULL);
6578 while ((cur = *aot_options) != '\0') {
6579 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6584 // If we find a quote, then if we're in the default case then
6585 // it means we've found the start of a string, if not then it
6586 // means we've found the end of the string and should switch
6587 // back to the default case.
6589 case MONO_AOT_OPTION_STATE_DEFAULT:
6590 state = MONO_AOT_OPTION_STATE_STRING;
6592 case MONO_AOT_OPTION_STATE_STRING:
6593 state = MONO_AOT_OPTION_STATE_DEFAULT;
6595 case MONO_AOT_OPTION_STATE_ESCAPE:
6596 g_assert_not_reached ();
6601 // If we've found an escaping operator, then this means we
6602 // should not process the next character if inside a string.
6603 if (state == MONO_AOT_OPTION_STATE_STRING)
6604 state = MONO_AOT_OPTION_STATE_ESCAPE;
6607 // If we're in the default state then this means we've found
6608 // an option, store it for later processing.
6609 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6616 // If the next character is end of string, then process the last option.
6617 if (*(aot_options) == '\0') {
6618 end_of_string = TRUE;
6624 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6625 opt_start = ++aot_options;
6635 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6639 args = mono_aot_split_options (aot_options ? aot_options : "");
6640 for (int i = 0; i < args->len; ++i) {
6641 const char *arg = (const char *)g_ptr_array_index (args, i);
6643 if (str_begins_with (arg, "outfile=")) {
6644 opts->outfile = g_strdup (arg + strlen ("outfile="));
6645 } else if (str_begins_with (arg, "llvm-outfile=")) {
6646 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6647 } else if (str_begins_with (arg, "temp-path=")) {
6648 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6649 } else if (str_begins_with (arg, "save-temps")) {
6650 opts->save_temps = TRUE;
6651 } else if (str_begins_with (arg, "keep-temps")) {
6652 opts->save_temps = TRUE;
6653 } else if (str_begins_with (arg, "write-symbols")) {
6654 opts->write_symbols = TRUE;
6655 } else if (str_begins_with (arg, "no-write-symbols")) {
6656 opts->write_symbols = FALSE;
6657 } else if (str_begins_with (arg, "metadata-only")) {
6658 opts->metadata_only = TRUE;
6659 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6660 opts->bind_to_runtime_version = TRUE;
6661 } else if (str_begins_with (arg, "full")) {
6662 opts->mode = MONO_AOT_MODE_FULL;
6663 } else if (str_begins_with (arg, "hybrid")) {
6664 opts->mode = MONO_AOT_MODE_HYBRID;
6665 } else if (str_begins_with (arg, "threads=")) {
6666 opts->nthreads = atoi (arg + strlen ("threads="));
6667 } else if (str_begins_with (arg, "static")) {
6668 opts->static_link = TRUE;
6669 opts->no_dlsym = TRUE;
6670 } else if (str_begins_with (arg, "asmonly")) {
6671 opts->asm_only = TRUE;
6672 } else if (str_begins_with (arg, "asmwriter")) {
6673 opts->asm_writer = TRUE;
6674 } else if (str_begins_with (arg, "nodebug")) {
6675 opts->nodebug = TRUE;
6676 } else if (str_begins_with (arg, "dwarfdebug")) {
6677 opts->dwarf_debug = TRUE;
6678 } else if (str_begins_with (arg, "nopagetrampolines")) {
6679 opts->use_trampolines_page = FALSE;
6680 } else if (str_begins_with (arg, "ntrampolines=")) {
6681 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6682 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6683 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6684 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6685 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6686 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6687 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6688 } else if (str_begins_with (arg, "tool-prefix=")) {
6689 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6690 } else if (str_begins_with (arg, "ld-flags=")) {
6691 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6692 } else if (str_begins_with (arg, "soft-debug")) {
6693 opts->soft_debug = TRUE;
6694 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6695 opts->gen_seq_points_file = TRUE;
6696 } else if (str_begins_with (arg, "direct-pinvoke")) {
6697 opts->direct_pinvoke = TRUE;
6698 } else if (str_begins_with (arg, "direct-icalls")) {
6699 opts->direct_icalls = TRUE;
6700 } else if (str_begins_with (arg, "no-direct-calls")) {
6701 opts->no_direct_calls = TRUE;
6702 } else if (str_begins_with (arg, "print-skipped")) {
6703 opts->print_skipped_methods = TRUE;
6704 } else if (str_begins_with (arg, "stats")) {
6706 } else if (str_begins_with (arg, "no-instances")) {
6707 opts->no_instances = TRUE;
6708 } else if (str_begins_with (arg, "log-generics")) {
6709 opts->log_generics = TRUE;
6710 } else if (str_begins_with (arg, "log-instances=")) {
6711 opts->log_instances = TRUE;
6712 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6713 } else if (str_begins_with (arg, "log-instances")) {
6714 opts->log_instances = TRUE;
6715 } else if (str_begins_with (arg, "internal-logfile=")) {
6716 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6717 } else if (str_begins_with (arg, "mtriple=")) {
6718 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6719 } else if (str_begins_with (arg, "llvm-path=")) {
6720 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6721 } else if (!strcmp (arg, "llvm")) {
6723 } else if (str_begins_with (arg, "readonly-value=")) {
6724 add_readonly_value (opts, arg + strlen ("readonly-value="));
6725 } else if (str_begins_with (arg, "info")) {
6726 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6728 } else if (str_begins_with (arg, "gc-maps")) {
6729 mini_gc_enable_gc_maps_for_aot ();
6730 } else if (str_begins_with (arg, "dump")) {
6731 opts->dump_json = TRUE;
6732 } else if (str_begins_with (arg, "llvmonly")) {
6733 opts->mode = MONO_AOT_MODE_FULL;
6735 opts->llvm_only = TRUE;
6736 } else if (str_begins_with (arg, "data-outfile=")) {
6737 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6738 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6739 printf ("Supported options for --aot:\n");
6740 printf (" outfile=\n");
6741 printf (" llvm-outfile=\n");
6742 printf (" llvm-path=\n");
6743 printf (" temp-path=\n");
6744 printf (" save-temps\n");
6745 printf (" keep-temps\n");
6746 printf (" write-symbols\n");
6747 printf (" metadata-only\n");
6748 printf (" bind-to-runtime-version\n");
6750 printf (" threads=\n");
6751 printf (" static\n");
6752 printf (" asmonly\n");
6753 printf (" asmwriter\n");
6754 printf (" nodebug\n");
6755 printf (" dwarfdebug\n");
6756 printf (" ntrampolines=\n");
6757 printf (" nrgctx-trampolines=\n");
6758 printf (" nimt-trampolines=\n");
6759 printf (" ngsharedvt-trampolines=\n");
6760 printf (" tool-prefix=\n");
6761 printf (" readonly-value=\n");
6762 printf (" soft-debug\n");
6763 printf (" gen-seq-points-file\n");
6764 printf (" gc-maps\n");
6765 printf (" print-skipped\n");
6766 printf (" no-instances\n");
6767 printf (" stats\n");
6770 printf (" help/?\n");
6773 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6777 g_free ((gpointer) arg);
6780 if (opts->use_trampolines_page) {
6781 opts->ntrampolines = 0;
6782 opts->nrgctx_trampolines = 0;
6783 opts->nimt_trampolines = 0;
6784 opts->ngsharedvt_arg_trampolines = 0;
6787 g_ptr_array_free (args, /*free_seg=*/TRUE);
6791 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6793 MonoMethod *method = (MonoMethod*)key;
6794 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6795 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6796 MonoJumpInfoToken *new_ji;
6798 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6799 new_ji->image = ji->image;
6800 new_ji->token = ji->token;
6801 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6805 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6807 if (klass->type_token)
6809 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6812 return can_encode_class (acfg, klass->element_class);
6817 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6819 if (method->wrapper_type) {
6820 switch (method->wrapper_type) {
6821 case MONO_WRAPPER_NONE:
6822 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6823 case MONO_WRAPPER_XDOMAIN_INVOKE:
6824 case MONO_WRAPPER_STFLD:
6825 case MONO_WRAPPER_LDFLD:
6826 case MONO_WRAPPER_LDFLDA:
6827 case MONO_WRAPPER_LDFLD_REMOTE:
6828 case MONO_WRAPPER_STFLD_REMOTE:
6829 case MONO_WRAPPER_STELEMREF:
6830 case MONO_WRAPPER_ISINST:
6831 case MONO_WRAPPER_PROXY_ISINST:
6832 case MONO_WRAPPER_ALLOC:
6833 case MONO_WRAPPER_REMOTING_INVOKE:
6834 case MONO_WRAPPER_UNKNOWN:
6835 case MONO_WRAPPER_WRITE_BARRIER:
6836 case MONO_WRAPPER_DELEGATE_INVOKE:
6837 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6838 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6839 case MONO_WRAPPER_SYNCHRONIZED:
6841 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6842 case MONO_WRAPPER_CASTCLASS: {
6843 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6852 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6856 if (!method->token) {
6857 /* The method is part of a constructed type like Int[,].Set (). */
6858 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6859 if (method->klass->rank)
6869 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6871 switch (patch_info->type) {
6872 case MONO_PATCH_INFO_METHOD:
6873 case MONO_PATCH_INFO_METHODCONST:
6874 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6875 MonoMethod *method = patch_info->data.method;
6877 return can_encode_method (acfg, method);
6879 case MONO_PATCH_INFO_VTABLE:
6880 case MONO_PATCH_INFO_CLASS:
6881 case MONO_PATCH_INFO_IID:
6882 case MONO_PATCH_INFO_ADJUSTED_IID:
6883 if (!can_encode_class (acfg, patch_info->data.klass)) {
6884 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6888 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6889 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6890 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6895 case MONO_PATCH_INFO_RGCTX_FETCH:
6896 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6897 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6899 if (!can_encode_method (acfg, entry->method))
6901 if (!can_encode_patch (acfg, entry->data))
6912 /* LOCKING: Assumes the loader lock is held */
6914 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
6916 MonoMethod *wrapper;
6917 gboolean concrete = TRUE;
6918 gboolean add_in = gsharedvt_in;
6919 gboolean add_out = gsharedvt_out;
6921 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
6923 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
6926 if (!add_in && !add_out)
6929 if (mini_is_gsharedvt_variable_signature (sig))
6933 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
6935 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
6937 if (!sig->has_type_parameters) {
6938 //printf ("%s\n", mono_signature_full_name (sig));
6941 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
6942 add_extra_method (acfg, wrapper);
6944 if (gsharedvt_out) {
6945 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
6946 add_extra_method (acfg, wrapper);
6949 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
6950 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
6953 //printf ("%s\n", mono_signature_full_name (sig));
6955 copy->ret = mini_get_underlying_type (sig->ret);
6956 // FIXME: Add more cases
6957 if (copy->ret->type == MONO_TYPE_VAR || copy->ret->type == MONO_TYPE_MVAR || copy->ret->type == MONO_TYPE_GENERICINST)
6959 for (i = 0; i < sig->param_count; ++i) {
6960 MonoType *t = mini_get_underlying_type (sig->params [i]);
6962 * Create a concrete type for Nullable<T_REF> etc.
6963 * FIXME: Generalize this
6965 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6966 MonoType *arg = mono_class_from_mono_type (t)->generic_class->context.class_inst->type_argv[0];
6967 arg = mini_get_underlying_type (arg);
6968 if (arg->type == MONO_TYPE_VAR || arg->type == MONO_TYPE_MVAR || arg->type == MONO_TYPE_GENERICINST) {
6971 MonoGenericContext ctx;
6973 MonoType *args [16];
6975 memset (&ctx, 0, sizeof (MonoGenericContext));
6977 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
6979 klass = mono_class_inflate_generic_class (mono_defaults.generic_nullable_class, &ctx);
6980 t = &klass->byval_arg;
6983 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR || t->type == MONO_TYPE_GENERICINST)
6986 copy->params [i] = t;
6989 copy->has_type_parameters = 0;
6992 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
6993 add_extra_method (acfg, wrapper);
6996 if (gsharedvt_out) {
6997 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
6998 add_extra_method (acfg, wrapper);
7001 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7009 * AOT compile a given method.
7010 * This function might be called by multiple threads, so it must be thread-safe.
7013 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7016 MonoJumpInfo *patch_info;
7019 MonoMethod *wrapped;
7022 if (acfg->aot_opts.metadata_only)
7025 mono_acfg_lock (acfg);
7026 index = get_method_index (acfg, method);
7027 mono_acfg_unlock (acfg);
7029 /* fixme: maybe we can also precompile wrapper methods */
7030 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7031 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7032 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7033 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7037 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7040 wrapped = mono_marshal_method_from_wrapper (method);
7041 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7042 // FIXME: The wrapper should be generic too, but it is not
7045 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7048 InterlockedIncrement (&acfg->stats.mcount);
7051 if (method->is_generic || method->klass->generic_container) {
7052 InterlockedIncrement (&acfg->stats.genericcount);
7057 //acfg->aot_opts.print_skipped_methods = TRUE;
7060 * Since these methods are the only ones which are compiled with
7061 * AOT support, and they are not used by runtime startup/shutdown code,
7062 * the runtime will not see AOT methods during AOT compilation,so it
7063 * does not need to support them by creating a fake GOT etc.
7065 flags = JIT_FLAG_AOT;
7066 if (mono_aot_mode_is_full (&acfg->aot_opts))
7067 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7069 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7070 if (acfg->aot_opts.llvm_only)
7071 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7072 if (acfg->aot_opts.no_direct_calls)
7073 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7074 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7075 mono_loader_clear_error ();
7077 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7078 if (acfg->aot_opts.print_skipped_methods)
7079 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
7080 InterlockedIncrement (&acfg->stats.genericcount);
7083 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7084 if (acfg->aot_opts.print_skipped_methods)
7085 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
7086 /* Let the exception happen at runtime */
7090 if (cfg->disable_aot) {
7091 if (acfg->aot_opts.print_skipped_methods)
7092 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
7093 InterlockedIncrement (&acfg->stats.ocount);
7094 mono_destroy_compile (cfg);
7097 cfg->method_index = index;
7099 /* Nullify patches which need no aot processing */
7100 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7101 switch (patch_info->type) {
7102 case MONO_PATCH_INFO_LABEL:
7103 case MONO_PATCH_INFO_BB:
7104 patch_info->type = MONO_PATCH_INFO_NONE;
7111 /* Collect method->token associations from the cfg */
7112 mono_acfg_lock (acfg);
7113 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7114 mono_acfg_unlock (acfg);
7115 g_hash_table_destroy (cfg->token_info_hash);
7116 cfg->token_info_hash = NULL;
7119 * Check for absolute addresses.
7122 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7123 switch (patch_info->type) {
7124 case MONO_PATCH_INFO_ABS:
7125 /* unable to handle this */
7134 if (acfg->aot_opts.print_skipped_methods)
7135 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
7136 InterlockedIncrement (&acfg->stats.abscount);
7137 mono_destroy_compile (cfg);
7141 /* Lock for the rest of the code */
7142 mono_acfg_lock (acfg);
7145 * Check for methods/klasses we can't encode.
7148 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7149 if (!can_encode_patch (acfg, patch_info))
7154 if (acfg->aot_opts.print_skipped_methods)
7155 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
7156 acfg->stats.ocount++;
7157 mono_destroy_compile (cfg);
7158 mono_acfg_unlock (acfg);
7162 if (!cfg->compile_llvm)
7163 acfg->has_jitted_code = TRUE;
7165 if (method->is_inflated && acfg->aot_opts.log_instances) {
7166 if (acfg->instances_logfile)
7167 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7169 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7172 /* Adds generic instances referenced by this method */
7174 * The depth is used to avoid infinite loops when generic virtual recursion is
7177 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7178 if (!acfg->aot_opts.no_instances && depth < 32) {
7179 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7180 switch (patch_info->type) {
7181 case MONO_PATCH_INFO_RGCTX_FETCH:
7182 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7183 case MONO_PATCH_INFO_METHOD: {
7184 MonoMethod *m = NULL;
7186 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7187 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7189 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7190 m = e->data->data.method;
7192 m = patch_info->data.method;
7197 if (m->is_inflated) {
7198 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7199 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7200 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7201 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7202 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7203 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7205 add_extra_method_with_depth (acfg, m, depth + 1);
7206 add_types_from_method_header (acfg, m);
7209 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7211 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7212 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7214 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7215 add_extra_method_with_depth (acfg, m, depth + 1);
7219 case MONO_PATCH_INFO_VTABLE: {
7220 MonoClass *klass = patch_info->data.klass;
7222 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7223 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7226 case MONO_PATCH_INFO_SFLDA: {
7227 MonoClass *klass = patch_info->data.field->parent;
7229 /* The .cctor needs to run at runtime. */
7230 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7231 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7240 /* Determine whenever the method has GOT slots */
7241 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7242 switch (patch_info->type) {
7243 case MONO_PATCH_INFO_GOT_OFFSET:
7244 case MONO_PATCH_INFO_NONE:
7245 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7246 case MONO_PATCH_INFO_GC_NURSERY_START:
7247 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7249 case MONO_PATCH_INFO_IMAGE:
7250 /* The assembly is stored in GOT slot 0 */
7251 if (patch_info->data.image != acfg->image)
7252 cfg->has_got_slots = TRUE;
7255 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7256 cfg->has_got_slots = TRUE;
7261 if (!cfg->has_got_slots)
7262 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7264 if (!cfg->method->wrapper_type)
7265 /* These only need out wrappers */
7266 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7268 /* Add gsharedvt wrappers for signatures used by the method */
7269 if (acfg->aot_opts.llvm_only && (acfg->opts & MONO_OPT_GSHAREDVT)) {
7272 for (l = cfg->signatures; l; l = l->next) {
7273 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7275 /* These only need in wrappers */
7276 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7281 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7283 /* Make a copy of the patch info which is in the mempool */
7285 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7287 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7288 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7291 patches = new_patch_info;
7293 patches_end->next = new_patch_info;
7294 patches_end = new_patch_info;
7296 cfg->patch_info = patches;
7298 /* Make a copy of the unwind info */
7300 GSList *l, *unwind_ops;
7304 for (l = cfg->unwind_ops; l; l = l->next) {
7305 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7306 memcpy (op, l->data, sizeof (MonoUnwindOp));
7307 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7309 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7311 /* Make a copy of the argument/local info */
7313 MonoInst **args, **locals;
7314 MonoMethodSignature *sig;
7315 MonoMethodHeader *header;
7318 sig = mono_method_signature (method);
7319 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7320 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7321 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7322 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7326 header = mono_method_get_header (method);
7327 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7328 for (i = 0; i < header->num_locals; ++i) {
7329 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7330 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7332 cfg->locals = locals;
7335 /* Free some fields used by cfg to conserve memory */
7336 mono_mempool_destroy (cfg->mempool);
7337 cfg->mempool = NULL;
7338 g_free (cfg->varinfo);
7339 cfg->varinfo = NULL;
7343 mono_regstate_free (cfg->rs);
7347 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7349 while (index >= acfg->cfgs_size) {
7350 MonoCompile **new_cfgs;
7353 new_size = acfg->cfgs_size * 2;
7354 new_cfgs = g_new0 (MonoCompile*, new_size);
7355 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7356 g_free (acfg->cfgs);
7357 acfg->cfgs = new_cfgs;
7358 acfg->cfgs_size = new_size;
7360 acfg->cfgs [index] = cfg;
7362 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7365 if (cfg->orig_method->wrapper_type)
7366 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7369 mono_acfg_unlock (acfg);
7371 InterlockedIncrement (&acfg->stats.ccount);
7375 compile_thread_main (gpointer *user_data)
7377 MonoDomain *domain = (MonoDomain *)user_data [0];
7378 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7379 GPtrArray *methods = (GPtrArray *)user_data [2];
7382 mono_thread_attach (domain);
7384 for (i = 0; i < methods->len; ++i)
7385 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7389 load_profile_files (MonoAotCompile *acfg)
7393 int file_index, res, method_index, i;
7396 GList *unordered, *l;
7401 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7403 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7408 infile = fopen (tmp, "r");
7411 printf ("Using profile data file '%s'\n", tmp);
7416 res = fscanf (infile, "%32s\n", ver);
7417 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7418 printf ("Profile file has wrong version or invalid.\n");
7425 MonoMethodDesc *desc;
7428 if (fgets (name, 1023, infile) == NULL)
7431 /* Kill the newline */
7432 if (strlen (name) > 0)
7433 name [strlen (name) - 1] = '\0';
7435 desc = mono_method_desc_new (name, TRUE);
7437 method = mono_method_desc_search_in_image (desc, acfg->image);
7439 if (method && mono_method_get_token (method)) {
7440 token = mono_method_get_token (method);
7441 method_index = mono_metadata_token_index (token) - 1;
7444 for (i = 0; i < acfg->method_order->len; ++i) {
7445 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7451 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7453 //printf ("No method found matching '%s'.\n", name);
7459 /* Add missing methods */
7461 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7463 for (i = 0; i < acfg->method_order->len; ++i) {
7464 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7470 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7472 unordered = g_list_reverse (unordered);
7473 for (l = unordered; l; l = l->next)
7474 g_ptr_array_add (acfg->method_order, l->data);
7477 /* Used by the LLVM backend */
7479 mono_aot_get_got_offset (MonoJumpInfo *ji)
7481 return get_got_offset (llvm_acfg, TRUE, ji);
7485 * mono_aot_is_shared_got_offset:
7487 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7488 * when the AOT image is loaded.
7491 mono_aot_is_shared_got_offset (int offset)
7493 return offset < llvm_acfg->nshared_got_entries;
7497 mono_aot_get_method_name (MonoCompile *cfg)
7499 if (llvm_acfg->aot_opts.static_link)
7500 /* Include the assembly name too to avoid duplicate symbol errors */
7501 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7503 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7507 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7509 return is_direct_callable (llvm_acfg, NULL, patch_info);
7513 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7515 MonoPltEntry *plt_entry;
7517 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7518 plt_entry->llvm_used = FALSE;
7522 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7524 const char *sym = NULL;
7526 if (llvm_acfg->aot_opts.direct_icalls) {
7527 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7528 /* Call to a C function implementing a jit icall */
7529 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7530 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7531 MonoMethod *method = (MonoMethod *)data;
7532 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7533 sym = mono_lookup_icall_symbol (method);
7536 return g_strdup (sym);
7542 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7544 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7545 MonoPltEntry *plt_entry;
7546 const char *sym = NULL;
7549 ji->data.target = data;
7551 if (!can_encode_patch (llvm_acfg, ji))
7554 if (llvm_acfg->aot_opts.direct_icalls) {
7555 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7556 /* Call to a C function implementing a jit icall */
7557 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7558 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7559 MonoMethod *method = (MonoMethod *)data;
7560 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7561 sym = mono_lookup_icall_symbol (method);
7564 return g_strdup (sym);
7567 plt_entry = get_plt_entry (llvm_acfg, ji);
7568 plt_entry->llvm_used = TRUE;
7570 #if defined(TARGET_MACH)
7571 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7573 return g_strdup_printf (plt_entry->llvm_symbol);
7578 mono_aot_get_method_index (MonoMethod *method)
7580 g_assert (llvm_acfg);
7581 return get_method_index (llvm_acfg, method);
7585 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7589 mono_acfg_lock (llvm_acfg);
7590 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7591 mono_acfg_unlock (llvm_acfg);
7597 execute_system (const char * command)
7602 // We need an extra set of quotes around the whole command to properly handle commands
7603 // with spaces since internally the command is called through "cmd /c.
7604 command = g_strdup_printf ("\"%s\"", command);
7606 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7607 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7608 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7609 status = _wsystem (wstr);
7613 #elif defined (HAVE_SYSTEM)
7614 status = system (command);
7616 g_assert_not_reached ();
7627 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7631 emit_llvm_file (MonoAotCompile *acfg)
7633 char *command, *opts, *tempbc, *output_fname;
7635 /* Emit the LLVM code into a .bc file */
7636 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7637 mono_llvm_emit_aot_module (acfg->aot_opts.llvm_outfile, g_path_get_basename (acfg->image->name));
7641 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7642 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7645 if (acfg->aot_opts.llvm_only) {
7646 /* Use the stock clang from xcode */
7649 // FIXME: llc/opt flags
7650 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7651 //command = g_strdup_printf ("/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk -Qunused-arguments -miphoneos-version-min=8.2 -arch arm64 -fpic -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7653 aot_printf (acfg, "Executing clang: %s\n", command);
7654 if (execute_system (command) != 0)
7660 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7661 * a lot of time, and doesn't seem to save much space.
7662 * The following optimizations cannot be enabled:
7664 * - 'jump-threading' changes our blockaddress references to int constants.
7665 * - 'basiccg' fails because it contains:
7666 * if (CS && !isa<IntrinsicInst>(II)) {
7667 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7668 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7669 * The opt list below was produced by taking the output of:
7670 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7671 * then removing tailcallelim + the global opts.
7672 * strip-dead-prototypes deletes unused intrinsics definitions.
7674 //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");
7675 /* The dse pass is disabled because of #13734 and #17616 */
7677 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7678 * // If we have no DataLayout information around, then the size of the store
7679 * // is inferrable from the pointee type. If they are the same type, then
7680 * // we know that the store is safe.
7681 * if (AA.getDataLayout() == 0 &&
7682 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7683 * return OverwriteComplete;
7684 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7686 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -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");
7687 opts = g_strdup ("");
7689 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7690 aot_printf (acfg, "Executing opt: %s\n", command);
7691 if (execute_system (command) != 0)
7696 if (!acfg->llc_args)
7697 acfg->llc_args = g_string_new ("");
7699 /* Verbose asm slows down llc greatly */
7700 g_string_append (acfg->llc_args, " -asm-verbose=false");
7702 if (acfg->aot_opts.mtriple)
7703 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7705 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7707 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7709 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7710 /* ios requires PIC code now */
7711 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7713 if (llvm_acfg->aot_opts.static_link)
7714 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7716 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7719 if (acfg->llvm_owriter) {
7720 /* Emit an object file directly */
7721 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7722 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7724 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7726 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7727 g_free (output_fname);
7729 aot_printf (acfg, "Executing llc: %s\n", command);
7731 if (execute_system (command) != 0)
7738 emit_code (MonoAotCompile *acfg)
7740 int oindex, i, prev_index;
7741 gboolean saved_unbox_info = FALSE;
7744 if (acfg->aot_opts.llvm_only)
7747 #if defined(TARGET_POWERPC64)
7748 sprintf (symbol, ".Lgot_addr");
7749 emit_section_change (acfg, ".text", 0);
7750 emit_alignment (acfg, 8);
7751 emit_label (acfg, symbol);
7752 emit_pointer (acfg, acfg->got_symbol);
7756 * This global symbol is used to compute the address of each method using the
7757 * code_offsets array. It is also used to compute the memory ranges occupied by
7758 * AOT code, so it must be equal to the address of the first emitted method.
7760 emit_section_change (acfg, ".text", 0);
7761 emit_alignment_code (acfg, 8);
7762 emit_info_symbol (acfg, "jit_code_start");
7765 * Emit some padding so the local symbol for the first method doesn't have the
7766 * same address as 'methods'.
7768 #if defined(__default_codegen__)
7769 emit_padding (acfg, 16);
7770 #elif defined(__native_client_codegen__)
7772 const int kPaddingSize = 16;
7773 guint8 pad_buffer[kPaddingSize];
7774 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7775 emit_bytes (acfg, pad_buffer, kPaddingSize);
7779 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7783 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7785 cfg = acfg->cfgs [i];
7790 method = cfg->orig_method;
7792 /* Emit unbox trampoline */
7793 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7794 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7796 emit_section_change (acfg, ".text", 0);
7797 #ifdef __native_client_codegen__
7798 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7801 if (acfg->thumb_mixed && cfg->compile_llvm) {
7802 emit_set_thumb_mode (acfg);
7803 fprintf (acfg->fp, "\n.thumb_func\n");
7806 emit_label (acfg, symbol);
7808 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7810 if (acfg->thumb_mixed && cfg->compile_llvm)
7811 emit_set_arm_mode (acfg);
7813 if (!saved_unbox_info) {
7814 char user_symbol [128];
7816 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
7818 emit_label (acfg, "ut_end");
7820 unwind_ops = mono_unwind_get_cie_program ();
7821 save_unwind_info (acfg, user_symbol, unwind_ops);
7822 mono_free_unwind_info (unwind_ops);
7824 /* Save the unbox trampoline size */
7825 emit_symbol_diff (acfg, "ut_end", symbol, 0);
7827 saved_unbox_info = TRUE;
7831 if (cfg->compile_llvm)
7832 acfg->stats.llvm_count ++;
7834 emit_method_code (acfg, cfg);
7837 emit_section_change (acfg, ".text", 0);
7838 emit_alignment_code (acfg, 8);
7839 emit_info_symbol (acfg, "jit_code_end");
7841 /* To distinguish it from the next symbol */
7842 emit_padding (acfg, 4);
7845 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7846 * from optimizing them away, since it doesn't see that code_offsets references them.
7847 * JITted methods don't need this since they are referenced using assembler local
7849 * FIXME: This is why write-symbols doesn't work on OSX ?
7851 if (acfg->llvm && acfg->need_no_dead_strip) {
7852 fprintf (acfg->fp, "\n");
7853 for (i = 0; i < acfg->nmethods; ++i) {
7854 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7855 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7860 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7861 * This is PIE code, and the linker can update it if needed.
7863 sprintf (symbol, "method_addresses");
7864 emit_section_change (acfg, ".text", 1);
7865 emit_alignment_code (acfg, 8);
7866 emit_info_symbol (acfg, symbol);
7867 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7868 emit_unset_mode (acfg);
7869 if (acfg->need_no_dead_strip)
7870 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7872 for (i = 0; i < acfg->nmethods; ++i) {
7873 #ifdef MONO_ARCH_AOT_SUPPORTED
7876 if (acfg->cfgs [i]) {
7877 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
7878 /* Obtained by calling a generated function in the LLVM image */
7879 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7881 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7883 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7888 sprintf (symbol, "method_addresses_end");
7889 emit_label (acfg, symbol);
7892 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7893 sprintf (symbol, "unbox_trampolines");
7894 emit_section_change (acfg, RODATA_SECT, 0);
7895 emit_alignment (acfg, 8);
7896 emit_info_symbol (acfg, symbol);
7899 for (i = 0; i < acfg->nmethods; ++i) {
7904 cfg = acfg->cfgs [i];
7908 method = cfg->orig_method;
7910 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7911 index = get_method_index (acfg, method);
7913 emit_int32 (acfg, index);
7914 /* Make sure the table is sorted by index */
7915 g_assert (index > prev_index);
7919 sprintf (symbol, "unbox_trampolines_end");
7920 emit_info_symbol (acfg, symbol);
7921 emit_int32 (acfg, 0);
7923 /* Emit a separate table with the trampoline addresses/offsets */
7924 sprintf (symbol, "unbox_trampoline_addresses");
7925 emit_section_change (acfg, ".text", 0);
7926 emit_alignment_code (acfg, 8);
7927 emit_info_symbol (acfg, symbol);
7929 for (i = 0; i < acfg->nmethods; ++i) {
7934 cfg = acfg->cfgs [i];
7938 method = cfg->orig_method;
7940 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
7941 #ifdef MONO_ARCH_AOT_SUPPORTED
7944 index = get_method_index (acfg, method);
7945 sprintf (symbol, "ut_%d", index);
7947 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7951 emit_int32 (acfg, 0);
7955 emit_info (MonoAotCompile *acfg)
7960 offsets = g_new0 (gint32, acfg->nmethods);
7962 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7963 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7965 if (acfg->cfgs [i]) {
7966 emit_method_info (acfg, acfg->cfgs [i]);
7967 offsets [i] = acfg->cfgs [i]->method_info_offset;
7973 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
7978 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7980 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7981 #define mix(a,b,c) { \
7982 a -= c; a ^= rot(c, 4); c += b; \
7983 b -= a; b ^= rot(a, 6); a += c; \
7984 c -= b; c ^= rot(b, 8); b += a; \
7985 a -= c; a ^= rot(c,16); c += b; \
7986 b -= a; b ^= rot(a,19); a += c; \
7987 c -= b; c ^= rot(b, 4); b += a; \
7989 #define final(a,b,c) { \
7990 c ^= b; c -= rot(b,14); \
7991 a ^= c; a -= rot(c,11); \
7992 b ^= a; b -= rot(a,25); \
7993 c ^= b; c -= rot(b,16); \
7994 a ^= c; a -= rot(c,4); \
7995 b ^= a; b -= rot(a,14); \
7996 c ^= b; c -= rot(b,24); \
8000 mono_aot_type_hash (MonoType *t1)
8002 guint hash = t1->type;
8004 hash |= t1->byref << 6; /* do not collide with t1->type values */
8006 case MONO_TYPE_VALUETYPE:
8007 case MONO_TYPE_CLASS:
8008 case MONO_TYPE_SZARRAY:
8009 /* check if the distribution is good enough */
8010 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8012 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8013 case MONO_TYPE_ARRAY:
8014 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8015 case MONO_TYPE_GENERICINST:
8016 return ((hash << 5) - hash) ^ 0;
8023 * mono_aot_method_hash:
8025 * Return a hash code for methods which only depends on metadata.
8028 mono_aot_method_hash (MonoMethod *method)
8030 MonoMethodSignature *sig;
8034 guint32 *hashes_start, *hashes;
8036 MonoGenericInst *class_ginst = NULL;
8037 MonoGenericInst *ginst = NULL;
8039 /* Similar to the hash in mono_method_get_imt_slot () */
8041 sig = mono_method_signature (method);
8043 if (method->klass->generic_class)
8044 class_ginst = method->klass->generic_class->context.class_inst;
8045 if (method->is_inflated)
8046 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8048 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8049 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8050 hashes = hashes_start;
8052 /* Some wrappers are assigned to random classes */
8053 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8054 klass = method->klass;
8056 klass = mono_defaults.object_class;
8058 if (!method->wrapper_type) {
8061 if (klass->generic_class)
8062 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8064 full_name = mono_type_full_name (&klass->byval_arg);
8066 hashes [0] = mono_metadata_str_hash (full_name);
8070 hashes [0] = mono_metadata_str_hash (klass->name);
8071 hashes [1] = mono_metadata_str_hash (klass->name_space);
8073 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8074 /* The method name includes a stringified pointer */
8077 hashes [2] = mono_metadata_str_hash (method->name);
8078 hashes [3] = method->wrapper_type;
8079 hashes [4] = mono_aot_type_hash (sig->ret);
8081 for (i = 0; i < sig->param_count; i++) {
8082 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8085 for (i = 0; i < class_ginst->type_argc; ++i)
8086 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8089 for (i = 0; i < ginst->type_argc; ++i)
8090 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8092 g_assert (hindex == hashes_count);
8094 /* Setup internal state */
8095 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8097 /* Handle most of the hashes */
8098 while (hashes_count > 3) {
8107 /* Handle the last 3 hashes (all the case statements fall through) */
8108 switch (hashes_count) {
8109 case 3 : c += hashes [2];
8110 case 2 : b += hashes [1];
8111 case 1 : a += hashes [0];
8113 case 0: /* nothing left to add */
8117 free (hashes_start);
8126 * mono_aot_get_array_helper_from_wrapper;
8128 * Get the helper method in Array called by an array wrapper method.
8131 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8135 MonoGenericContext ctx;
8136 MonoType *args [16];
8137 char *mname, *iname, *s, *s2, *helper_name = NULL;
8139 prefix = "System.Collections.Generic";
8140 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8141 s2 = strstr (s, "`1.");
8147 //printf ("X: %s %s\n", iname, mname);
8149 if (!strcmp (iname, "IList"))
8150 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8152 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8153 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8155 g_free (helper_name);
8158 if (m->is_generic) {
8160 memset (&ctx, 0, sizeof (ctx));
8161 args [0] = &method->klass->element_class->byval_arg;
8162 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8163 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8164 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8170 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8172 typedef struct HashEntry {
8173 guint32 key, value, index;
8174 struct HashEntry *next;
8178 * emit_extra_methods:
8180 * Emit methods which are not in the METHOD table, like wrappers.
8183 emit_extra_methods (MonoAotCompile *acfg)
8185 int i, table_size, buf_size;
8187 guint32 *info_offsets;
8190 HashEntry *entry, *new_entry;
8191 int nmethods, max_chain_length;
8194 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8196 /* Emit method info */
8198 for (i = 0; i < acfg->extra_methods->len; ++i) {
8199 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8200 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8206 p = buf = (guint8 *)g_malloc (buf_size);
8210 method = cfg->method_to_register;
8212 encode_method_ref (acfg, method, p, &p);
8214 g_assert ((p - buf) < buf_size);
8216 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8221 * Construct a chained hash table for mapping indexes in extra_method_info to
8224 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8225 table = g_ptr_array_sized_new (table_size);
8226 for (i = 0; i < table_size; ++i)
8227 g_ptr_array_add (table, NULL);
8228 chain_lengths = g_new0 (int, table_size);
8229 max_chain_length = 0;
8230 for (i = 0; i < acfg->extra_methods->len; ++i) {
8231 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8232 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8238 key = info_offsets [i];
8239 value = get_method_index (acfg, method);
8241 hash = mono_aot_method_hash (method) % table_size;
8242 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
8244 chain_lengths [hash] ++;
8245 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8247 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8248 new_entry->key = key;
8249 new_entry->value = value;
8251 entry = (HashEntry *)g_ptr_array_index (table, hash);
8252 if (entry == NULL) {
8253 new_entry->index = hash;
8254 g_ptr_array_index (table, hash) = new_entry;
8257 entry = entry->next;
8259 entry->next = new_entry;
8260 new_entry->index = table->len;
8261 g_ptr_array_add (table, new_entry);
8265 //printf ("MAX: %d\n", max_chain_length);
8267 buf_size = table->len * 12 + 4;
8268 p = buf = (guint8 *)g_malloc (buf_size);
8269 encode_int (table_size, p, &p);
8271 for (i = 0; i < table->len; ++i) {
8272 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8274 if (entry == NULL) {
8275 encode_int (0, p, &p);
8276 encode_int (0, p, &p);
8277 encode_int (0, p, &p);
8279 //g_assert (entry->key > 0);
8280 encode_int (entry->key, p, &p);
8281 encode_int (entry->value, p, &p);
8283 encode_int (entry->next->index, p, &p);
8285 encode_int (0, p, &p);
8288 g_assert (p - buf <= buf_size);
8290 /* Emit the table */
8291 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8294 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8295 * This is used by mono_aot_find_jit_info ().
8297 buf_size = acfg->extra_methods->len * 8 + 4;
8298 p = buf = (guint8 *)g_malloc (buf_size);
8299 encode_int (acfg->extra_methods->len, p, &p);
8300 for (i = 0; i < acfg->extra_methods->len; ++i) {
8301 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8303 encode_int (get_method_index (acfg, method), p, &p);
8304 encode_int (info_offsets [i], p, &p);
8306 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8310 emit_exception_info (MonoAotCompile *acfg)
8314 SeqPointData sp_data;
8315 gboolean seq_points_to_file = FALSE;
8317 offsets = g_new0 (gint32, acfg->nmethods);
8318 for (i = 0; i < acfg->nmethods; ++i) {
8319 if (acfg->cfgs [i]) {
8320 MonoCompile *cfg = acfg->cfgs [i];
8322 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8323 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8324 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8325 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8326 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8328 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8329 offsets [i] = cfg->ex_info_offset;
8331 if (method_seq_points_to_file) {
8332 if (!seq_points_to_file) {
8333 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8334 seq_points_to_file = TRUE;
8336 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8343 if (seq_points_to_file) {
8344 char *seq_points_aot_file;
8345 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8346 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8347 mono_seq_point_data_free (&sp_data);
8348 g_free (seq_points_aot_file);
8351 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8356 emit_unwind_info (MonoAotCompile *acfg)
8361 if (acfg->aot_opts.llvm_only) {
8362 g_assert (acfg->unwind_ops->len == 0);
8367 * The unwind info contains a lot of duplicates so we emit each unique
8368 * entry once, and only store the offset from the start of the table in the
8372 sprintf (symbol, "unwind_info");
8373 emit_section_change (acfg, RODATA_SECT, 1);
8374 emit_alignment (acfg, 8);
8375 emit_info_symbol (acfg, symbol);
8377 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8378 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8379 guint8 *unwind_info;
8380 guint32 unwind_info_len;
8384 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8387 encode_value (unwind_info_len, p, &p);
8388 emit_bytes (acfg, buf, p - buf);
8389 emit_bytes (acfg, unwind_info, unwind_info_len);
8391 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8396 emit_class_info (MonoAotCompile *acfg)
8401 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8402 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8403 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8405 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8409 typedef struct ClassNameTableEntry {
8410 guint32 token, index;
8411 struct ClassNameTableEntry *next;
8412 } ClassNameTableEntry;
8415 emit_class_name_table (MonoAotCompile *acfg)
8417 int i, table_size, buf_size;
8418 guint32 token, hash;
8423 ClassNameTableEntry *entry, *new_entry;
8426 * Construct a chained hash table for mapping class names to typedef tokens.
8428 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8429 table = g_ptr_array_sized_new (table_size);
8430 for (i = 0; i < table_size; ++i)
8431 g_ptr_array_add (table, NULL);
8432 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8434 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8435 klass = mono_class_get_checked (acfg->image, token, &error);
8437 mono_error_cleanup (&error);
8440 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8441 hash = mono_metadata_str_hash (full_name) % table_size;
8444 /* FIXME: Allocate from the mempool */
8445 new_entry = g_new0 (ClassNameTableEntry, 1);
8446 new_entry->token = token;
8448 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8449 if (entry == NULL) {
8450 new_entry->index = hash;
8451 g_ptr_array_index (table, hash) = new_entry;
8454 entry = entry->next;
8456 entry->next = new_entry;
8457 new_entry->index = table->len;
8458 g_ptr_array_add (table, new_entry);
8462 /* Emit the table */
8463 buf_size = table->len * 4 + 4;
8464 p = buf = (guint8 *)g_malloc0 (buf_size);
8466 /* FIXME: Optimize memory usage */
8467 g_assert (table_size < 65000);
8468 encode_int16 (table_size, p, &p);
8469 g_assert (table->len < 65000);
8470 for (i = 0; i < table->len; ++i) {
8471 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8473 if (entry == NULL) {
8474 encode_int16 (0, p, &p);
8475 encode_int16 (0, p, &p);
8477 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8479 encode_int16 (entry->next->index, p, &p);
8481 encode_int16 (0, p, &p);
8484 g_assert (p - buf <= buf_size);
8486 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8490 emit_image_table (MonoAotCompile *acfg)
8496 * The image table is small but referenced in a lot of places.
8497 * So we emit it at once, and reference its elements by an index.
8499 buf_size = acfg->image_table->len * 28 + 4;
8500 for (i = 0; i < acfg->image_table->len; i++) {
8501 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8502 MonoAssemblyName *aname = &image->assembly->aname;
8504 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8507 buf = p = (guint8 *)g_malloc0 (buf_size);
8508 encode_int (acfg->image_table->len, p, &p);
8509 for (i = 0; i < acfg->image_table->len; i++) {
8510 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8511 MonoAssemblyName *aname = &image->assembly->aname;
8513 /* FIXME: Support multi-module assemblies */
8514 g_assert (image->assembly->image == image);
8516 encode_string (image->assembly_name, p, &p);
8517 encode_string (image->guid, p, &p);
8518 encode_string (aname->culture ? aname->culture : "", p, &p);
8519 encode_string ((const char*)aname->public_key_token, p, &p);
8521 while (GPOINTER_TO_UINT (p) % 8 != 0)
8524 encode_int (aname->flags, p, &p);
8525 encode_int (aname->major, p, &p);
8526 encode_int (aname->minor, p, &p);
8527 encode_int (aname->build, p, &p);
8528 encode_int (aname->revision, p, &p);
8530 g_assert (p - buf <= buf_size);
8532 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8538 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8540 int i, first_plt_got_patch = 0, buf_size;
8542 guint32 *got_info_offsets;
8543 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8545 /* Add the patches needed by the PLT to the GOT */
8547 acfg->plt_got_offset_base = acfg->got_offset;
8548 first_plt_got_patch = info->got_patches->len;
8549 for (i = 1; i < acfg->plt_offset; ++i) {
8550 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8552 g_ptr_array_add (info->got_patches, plt_entry->ji);
8554 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8557 acfg->got_offset += acfg->plt_offset;
8562 * - optimize offsets table.
8563 * - reduce number of exported symbols.
8564 * - emit info for a klass only once.
8565 * - determine when a method uses a GOT slot which is guaranteed to be already
8567 * - clean up and document the code.
8568 * - use String.Empty in class libs.
8571 /* Encode info required to decode shared GOT entries */
8572 buf_size = info->got_patches->len * 128;
8573 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8574 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8576 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8578 if (acfg->plt_offset)
8579 acfg->plt_got_info_offsets [0] = 0;
8581 for (i = 0; i < info->got_patches->len; ++i) {
8582 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8587 encode_value (ji->type, p, &p);
8589 encode_patch (acfg, ji, p, &p);
8590 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8591 g_assert (p - buf <= buf_size);
8592 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8594 if (!llvm && i >= first_plt_got_patch)
8595 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8596 acfg->stats.got_info_size += p - buf;
8599 /* Emit got_info_offsets table */
8601 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8602 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8606 emit_got (MonoAotCompile *acfg)
8610 if (acfg->aot_opts.llvm_only)
8613 /* Don't make GOT global so accesses to it don't need relocations */
8614 sprintf (symbol, "%s", acfg->got_symbol);
8617 emit_unset_mode (acfg);
8618 fprintf (acfg->fp, ".section __DATA, __bss\n");
8619 emit_alignment (acfg, 8);
8621 emit_info_symbol (acfg, "jit_got");
8622 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8624 emit_section_change (acfg, ".bss", 0);
8625 emit_alignment (acfg, 8);
8626 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8627 emit_label (acfg, symbol);
8629 emit_info_symbol (acfg, "jit_got");
8630 if (acfg->got_offset > 0)
8631 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8634 sprintf (symbol, "got_end");
8635 emit_label (acfg, symbol);
8638 typedef struct GlobalsTableEntry {
8639 guint32 value, index;
8640 struct GlobalsTableEntry *next;
8641 } GlobalsTableEntry;
8644 emit_globals (MonoAotCompile *acfg)
8650 GlobalsTableEntry *entry, *new_entry;
8652 if (!acfg->aot_opts.static_link)
8656 * When static linking, we emit a table containing our globals.
8660 * Construct a chained hash table for mapping global names to their index in
8661 * the globals table.
8663 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8664 table = g_ptr_array_sized_new (table_size);
8665 for (i = 0; i < table_size; ++i)
8666 g_ptr_array_add (table, NULL);
8667 for (i = 0; i < acfg->globals->len; ++i) {
8668 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8670 hash = mono_metadata_str_hash (name) % table_size;
8672 /* FIXME: Allocate from the mempool */
8673 new_entry = g_new0 (GlobalsTableEntry, 1);
8674 new_entry->value = i;
8676 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
8677 if (entry == NULL) {
8678 new_entry->index = hash;
8679 g_ptr_array_index (table, hash) = new_entry;
8682 entry = entry->next;
8684 entry->next = new_entry;
8685 new_entry->index = table->len;
8686 g_ptr_array_add (table, new_entry);
8690 /* Emit the table */
8691 sprintf (symbol, ".Lglobals_hash");
8692 emit_section_change (acfg, RODATA_SECT, 0);
8693 emit_alignment (acfg, 8);
8694 emit_label (acfg, symbol);
8696 /* FIXME: Optimize memory usage */
8697 g_assert (table_size < 65000);
8698 emit_int16 (acfg, table_size);
8699 for (i = 0; i < table->len; ++i) {
8700 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
8702 if (entry == NULL) {
8703 emit_int16 (acfg, 0);
8704 emit_int16 (acfg, 0);
8706 emit_int16 (acfg, entry->value + 1);
8708 emit_int16 (acfg, entry->next->index);
8710 emit_int16 (acfg, 0);
8714 /* Emit the names */
8715 for (i = 0; i < acfg->globals->len; ++i) {
8716 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8718 sprintf (symbol, "name_%d", i);
8719 emit_section_change (acfg, RODATA_SECT, 1);
8721 emit_alignment (acfg, 4);
8723 emit_label (acfg, symbol);
8724 emit_string (acfg, name);
8727 /* Emit the globals table */
8728 sprintf (symbol, "globals");
8729 emit_section_change (acfg, ".data", 0);
8730 /* This is not a global, since it is accessed by the init function */
8731 emit_alignment (acfg, 8);
8732 emit_info_symbol (acfg, symbol);
8734 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8735 emit_pointer (acfg, symbol);
8737 for (i = 0; i < acfg->globals->len; ++i) {
8738 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8740 sprintf (symbol, "name_%d", i);
8741 emit_pointer (acfg, symbol);
8743 g_assert (strlen (name) < sizeof (symbol));
8744 sprintf (symbol, "%s", name);
8745 emit_pointer (acfg, symbol);
8747 /* Null terminate the table */
8748 emit_int32 (acfg, 0);
8749 emit_int32 (acfg, 0);
8753 emit_mem_end (MonoAotCompile *acfg)
8757 if (acfg->aot_opts.llvm_only)
8760 sprintf (symbol, "mem_end");
8761 emit_section_change (acfg, ".text", 1);
8762 emit_alignment_code (acfg, 8);
8763 emit_label (acfg, symbol);
8767 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8771 info->version = MONO_AOT_FILE_VERSION;
8772 info->plt_got_offset_base = acfg->plt_got_offset_base;
8773 info->got_size = acfg->got_offset * sizeof (gpointer);
8774 info->plt_size = acfg->plt_offset;
8775 info->nmethods = acfg->nmethods;
8776 info->flags = acfg->flags;
8777 info->opts = acfg->opts;
8778 info->simd_opts = acfg->simd_opts;
8779 info->gc_name_index = acfg->gc_name_offset;
8780 info->datafile_size = acfg->datafile_offset;
8781 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
8782 info->table_offsets [i] = acfg->table_offsets [i];
8783 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8784 info->num_trampolines [i] = acfg->num_trampolines [i];
8785 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8786 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8787 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8788 info->trampoline_size [i] = acfg->trampoline_size [i];
8789 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8791 info->double_align = MONO_ABI_ALIGNOF (double);
8792 info->long_align = MONO_ABI_ALIGNOF (gint64);
8793 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8794 info->tramp_page_size = acfg->tramp_page_size;
8795 info->nshared_got_entries = acfg->nshared_got_entries;
8796 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8797 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8801 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8805 const char **symbols;
8807 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8809 symbols [sindex ++] = acfg->got_symbol;
8811 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8812 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8814 symbols [sindex ++] = NULL;
8815 symbols [sindex ++] = NULL;
8817 /* llvm_get_method */
8818 symbols [sindex ++] = NULL;
8819 /* llvm_get_unbox_tramp */
8820 symbols [sindex ++] = NULL;
8821 if (!acfg->aot_opts.llvm_only) {
8822 symbols [sindex ++] = "jit_code_start";
8823 symbols [sindex ++] = "jit_code_end";
8824 symbols [sindex ++] = "method_addresses";
8826 symbols [sindex ++] = NULL;
8827 symbols [sindex ++] = NULL;
8828 symbols [sindex ++] = NULL;
8830 if (acfg->data_outfile) {
8831 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
8832 symbols [sindex ++] = NULL;
8834 symbols [sindex ++] = "blob";
8835 symbols [sindex ++] = "class_name_table";
8836 symbols [sindex ++] = "class_info_offsets";
8837 symbols [sindex ++] = "method_info_offsets";
8838 symbols [sindex ++] = "ex_info_offsets";
8839 symbols [sindex ++] = "extra_method_info_offsets";
8840 symbols [sindex ++] = "extra_method_table";
8841 symbols [sindex ++] = "got_info_offsets";
8843 symbols [sindex ++] = "llvm_got_info_offsets";
8845 symbols [sindex ++] = NULL;
8846 symbols [sindex ++] = "image_table";
8848 symbols [sindex ++] = "mem_end";
8849 symbols [sindex ++] = "assembly_guid";
8850 symbols [sindex ++] = "runtime_version";
8851 if (acfg->num_trampoline_got_entries) {
8852 symbols [sindex ++] = "specific_trampolines";
8853 symbols [sindex ++] = "static_rgctx_trampolines";
8854 symbols [sindex ++] = "imt_thunks";
8855 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8857 symbols [sindex ++] = NULL;
8858 symbols [sindex ++] = NULL;
8859 symbols [sindex ++] = NULL;
8860 symbols [sindex ++] = NULL;
8862 if (acfg->aot_opts.static_link) {
8863 symbols [sindex ++] = "globals";
8865 symbols [sindex ++] = NULL;
8867 symbols [sindex ++] = "assembly_name";
8868 symbols [sindex ++] = "plt";
8869 symbols [sindex ++] = "plt_end";
8870 symbols [sindex ++] = "unwind_info";
8871 if (!acfg->aot_opts.llvm_only) {
8872 symbols [sindex ++] = "unbox_trampolines";
8873 symbols [sindex ++] = "unbox_trampolines_end";
8874 symbols [sindex ++] = "unbox_trampoline_addresses";
8876 symbols [sindex ++] = NULL;
8877 symbols [sindex ++] = NULL;
8878 symbols [sindex ++] = NULL;
8881 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8883 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8884 emit_section_change (acfg, ".data", 0);
8885 emit_alignment (acfg, 8);
8886 emit_label (acfg, symbol);
8887 if (!acfg->aot_opts.static_link)
8888 emit_global (acfg, symbol, FALSE);
8890 /* The data emitted here must match MonoAotFileInfo. */
8892 emit_int32 (acfg, info->version);
8893 emit_int32 (acfg, info->dummy);
8896 * We emit pointers to our data structures instead of emitting global symbols which
8897 * point to them, to reduce the number of globals, and because using globals leads to
8898 * various problems (i.e. arm/thumb).
8900 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8901 emit_pointer (acfg, symbols [i]);
8903 emit_int32 (acfg, info->plt_got_offset_base);
8904 emit_int32 (acfg, info->got_size);
8905 emit_int32 (acfg, info->plt_size);
8906 emit_int32 (acfg, info->nmethods);
8907 emit_int32 (acfg, info->flags);
8908 emit_int32 (acfg, info->opts);
8909 emit_int32 (acfg, info->simd_opts);
8910 emit_int32 (acfg, info->gc_name_index);
8911 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8912 emit_int32 (acfg, info->double_align);
8913 emit_int32 (acfg, info->long_align);
8914 emit_int32 (acfg, info->generic_tramp_num);
8915 emit_int32 (acfg, info->tramp_page_size);
8916 emit_int32 (acfg, info->nshared_got_entries);
8917 emit_int32 (acfg, info->datafile_size);
8919 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
8920 emit_int32 (acfg, info->table_offsets [i]);
8921 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8922 emit_int32 (acfg, info->num_trampolines [i]);
8923 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8924 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8925 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8926 emit_int32 (acfg, info->trampoline_size [i]);
8927 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8928 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8930 if (acfg->aot_opts.static_link) {
8934 * Emit a global symbol which can be passed by an embedding app to
8935 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8938 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8940 /* Get rid of characters which cannot occur in symbols */
8942 for (p = symbol; *p; ++p) {
8943 if (!(isalnum (*p) || *p == '_'))
8946 acfg->static_linking_symbol = g_strdup (symbol);
8947 emit_global_inner (acfg, symbol, FALSE);
8948 emit_alignment (acfg, sizeof (gpointer));
8949 emit_label (acfg, symbol);
8950 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8955 * Emit a structure containing all the information not stored elsewhere.
8958 emit_file_info (MonoAotCompile *acfg)
8961 MonoAotFileInfo *info;
8963 if (acfg->aot_opts.bind_to_runtime_version) {
8964 build_info = mono_get_runtime_build_info ();
8965 emit_string_symbol (acfg, "runtime_version", build_info);
8966 g_free (build_info);
8968 emit_string_symbol (acfg, "runtime_version", "");
8971 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8973 /* Emit a string holding the assembly name */
8974 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8976 info = g_new0 (MonoAotFileInfo, 1);
8977 init_aot_file_info (acfg, info);
8980 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8982 emit_aot_file_info (acfg, info);
8986 emit_blob (MonoAotCompile *acfg)
8988 acfg->blob_closed = TRUE;
8990 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
8994 emit_objc_selectors (MonoAotCompile *acfg)
8999 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9004 * cat > foo.m << EOF
9007 * return @selector(print:);
9012 mono_img_writer_emit_unset_mode (acfg->w);
9013 g_assert (acfg->fp);
9014 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9015 fprintf (acfg->fp, ".align 3\n");
9016 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9017 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9018 emit_label (acfg, symbol);
9019 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9020 emit_pointer (acfg, symbol);
9023 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9024 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9025 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9026 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9029 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9030 fprintf (acfg->fp, ".align 3\n");
9031 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9032 fprintf (acfg->fp, ".long 0\n");
9033 fprintf (acfg->fp, ".long 16\n");
9037 emit_dwarf_info (MonoAotCompile *acfg)
9039 #ifdef EMIT_DWARF_INFO
9043 /* DIEs for methods */
9044 for (i = 0; i < acfg->nmethods; ++i) {
9045 MonoCompile *cfg = acfg->cfgs [i];
9050 // FIXME: LLVM doesn't define .Lme_...
9051 if (cfg->compile_llvm)
9054 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9056 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)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 ()));
9062 collect_methods (MonoAotCompile *acfg)
9065 MonoImage *image = acfg->image;
9067 /* Collect methods */
9068 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9071 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9073 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9076 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9077 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9078 mono_error_cleanup (&error);
9082 /* Load all methods eagerly to skip the slower lazy loading code */
9083 mono_class_setup_methods (method->klass);
9085 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9086 /* Compile the wrapper instead */
9087 /* We do this here instead of add_wrappers () because it is easy to do it here */
9088 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9092 /* FIXME: Some mscorlib methods don't have debug info */
9094 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9095 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9096 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9097 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9098 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9099 if (!mono_debug_lookup_method (method)) {
9100 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
9107 if (method->is_generic || method->klass->generic_container)
9108 /* Compile the ref shared version instead */
9109 method = mini_get_shared_method (method);
9111 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9112 add_method_with_index (acfg, method, i, FALSE);
9113 acfg->method_index ++;
9116 /* gsharedvt methods */
9117 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9120 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9122 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9125 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9126 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9128 if (method->is_generic || method->klass->generic_container) {
9129 MonoMethod *gshared;
9131 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9132 add_extra_method (acfg, gshared);
9136 add_generic_instances (acfg);
9138 if (mono_aot_mode_is_full (&acfg->aot_opts))
9139 add_wrappers (acfg);
9144 compile_methods (MonoAotCompile *acfg)
9148 if (acfg->aot_opts.nthreads > 0) {
9153 gpointer *user_data;
9154 MonoMethod **methods;
9156 methods_len = acfg->methods->len;
9158 len = acfg->methods->len / acfg->aot_opts.nthreads;
9161 * Partition the list of methods into fragments, and hand it to threads to
9164 threads = g_ptr_array_new ();
9165 /* Make a copy since acfg->methods is modified by compile_method () */
9166 methods = g_new0 (MonoMethod*, methods_len);
9167 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9168 for (i = 0; i < methods_len; ++i)
9169 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9171 while (i < methods_len) {
9172 frag = g_ptr_array_new ();
9173 for (j = 0; j < len; ++j) {
9174 if (i < methods_len) {
9175 g_ptr_array_add (frag, methods [i]);
9180 user_data = g_new0 (gpointer, 3);
9181 user_data [0] = mono_domain_get ();
9182 user_data [1] = acfg;
9183 user_data [2] = frag;
9185 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9186 g_ptr_array_add (threads, handle);
9190 for (i = 0; i < threads->len; ++i) {
9191 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9197 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9198 for (i = methods_len; i < acfg->methods->len; ++i) {
9199 /* This can new methods to acfg->methods */
9200 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9205 compile_asm (MonoAotCompile *acfg)
9207 char *command, *objfile;
9208 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9209 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9210 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9212 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9213 #define AS_OPTIONS "--64"
9214 #elif defined(TARGET_POWERPC64)
9215 #define AS_OPTIONS "-a64 -mppc64"
9216 #define LD_OPTIONS "-m elf64ppc"
9217 #elif defined(sparc) && SIZEOF_VOID_P == 8
9218 #define AS_OPTIONS "-xarch=v9"
9219 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9220 #define AS_OPTIONS "-arch i386"
9222 #define AS_OPTIONS ""
9225 #ifdef __native_client_codegen__
9226 #if defined(TARGET_AMD64)
9227 #define AS_NAME "nacl64-as"
9229 #define AS_NAME "nacl-as"
9231 #elif defined(TARGET_OSX)
9232 #define AS_NAME "clang"
9234 #define AS_NAME "as"
9238 #define LD_OPTIONS ""
9242 #define LD_NAME "ld -shared -G"
9243 #elif defined(__ppc__) && defined(TARGET_MACH)
9244 #define LD_NAME "gcc -dynamiclib"
9245 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9246 #define LD_NAME "clang --shared"
9247 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9248 #define LD_NAME "gcc -shared --dll"
9249 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9250 #define LD_NAME "clang -m32 -dynamiclib"
9251 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9252 #define LD_NAME "gcc --shared"
9255 if (acfg->aot_opts.asm_only) {
9256 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9257 if (acfg->aot_opts.static_link)
9258 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9260 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9264 if (acfg->aot_opts.static_link) {
9265 if (acfg->aot_opts.outfile)
9266 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9268 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9270 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9274 g_string_append (acfg->as_args, "-c -x assembler");
9277 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);
9278 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9279 if (execute_system (command) != 0) {
9285 if (acfg->llvm && !acfg->llvm_owriter) {
9286 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);
9287 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9288 if (execute_system (command) != 0) {
9297 if (acfg->aot_opts.static_link) {
9298 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9299 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9304 if (acfg->aot_opts.outfile)
9305 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9307 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9309 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9312 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9314 llvm_ofile = g_strdup ("");
9317 /* replace the ; flags separators with spaces */
9318 g_strdelimit (ld_flags, ";", ' ');
9320 if (acfg->aot_opts.llvm_only)
9321 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9324 command = g_strdup_printf ("%s -o \"%s\" %s \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9326 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9327 acfg->tmpfname, ld_flags);
9329 aot_printf (acfg, "Executing the native linker: %s\n", command);
9330 if (execute_system (command) != 0) {
9331 g_free (tmp_outfile_name);
9332 g_free (outfile_name);
9341 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9342 printf ("Stripping the binary: %s\n", com);
9343 execute_system (com);
9346 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9348 * gas generates 'mapping symbols' each time code and data is mixed, which
9349 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9351 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9352 aot_printf (acfg, "Stripping the binary: %s\n", command);
9353 if (execute_system (command) != 0) {
9354 g_free (tmp_outfile_name);
9355 g_free (outfile_name);
9362 rename (tmp_outfile_name, outfile_name);
9364 #if defined(TARGET_MACH)
9365 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9366 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9367 if (execute_system (command) != 0) {
9372 if (!acfg->aot_opts.save_temps)
9375 g_free (tmp_outfile_name);
9376 g_free (outfile_name);
9379 if (acfg->aot_opts.save_temps)
9380 aot_printf (acfg, "Retained input file.\n");
9382 unlink (acfg->tmpfname);
9387 static void init_got_info (GotInfo *info)
9391 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9392 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9393 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9394 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9395 info->got_patches = g_ptr_array_new ();
9398 static MonoAotCompile*
9399 acfg_create (MonoAssembly *ass, guint32 opts)
9401 MonoImage *image = ass->image;
9402 MonoAotCompile *acfg;
9404 acfg = g_new0 (MonoAotCompile, 1);
9405 acfg->methods = g_ptr_array_new ();
9406 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9407 acfg->method_depth = g_hash_table_new (NULL, NULL);
9408 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9409 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9410 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9411 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9412 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9413 acfg->image_hash = g_hash_table_new (NULL, NULL);
9414 acfg->image_table = g_ptr_array_new ();
9415 acfg->globals = g_ptr_array_new ();
9416 acfg->image = image;
9418 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9419 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9420 acfg->mempool = mono_mempool_new ();
9421 acfg->extra_methods = g_ptr_array_new ();
9422 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9423 acfg->unwind_ops = g_ptr_array_new ();
9424 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9425 acfg->method_order = g_ptr_array_new ();
9426 acfg->export_names = g_hash_table_new (NULL, NULL);
9427 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9428 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9429 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9430 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9431 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9432 mono_os_mutex_init_recursive (&acfg->mutex);
9434 init_got_info (&acfg->got_info);
9435 init_got_info (&acfg->llvm_got_info);
9441 got_info_free (GotInfo *info)
9445 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9446 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9447 g_free (info->patch_to_got_offset_by_type);
9448 g_hash_table_destroy (info->patch_to_got_offset);
9449 g_ptr_array_free (info->got_patches, TRUE);
9453 acfg_free (MonoAotCompile *acfg)
9457 mono_img_writer_destroy (acfg->w);
9458 for (i = 0; i < acfg->nmethods; ++i)
9460 g_free (acfg->cfgs [i]);
9461 g_free (acfg->cfgs);
9462 g_free (acfg->static_linking_symbol);
9463 g_free (acfg->got_symbol);
9464 g_free (acfg->plt_symbol);
9465 g_ptr_array_free (acfg->methods, TRUE);
9466 g_ptr_array_free (acfg->image_table, TRUE);
9467 g_ptr_array_free (acfg->globals, TRUE);
9468 g_ptr_array_free (acfg->unwind_ops, TRUE);
9469 g_hash_table_destroy (acfg->method_indexes);
9470 g_hash_table_destroy (acfg->method_depth);
9471 g_hash_table_destroy (acfg->plt_offset_to_entry);
9472 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9473 if (acfg->patch_to_plt_entry [i])
9474 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9476 g_free (acfg->patch_to_plt_entry);
9477 g_hash_table_destroy (acfg->method_to_cfg);
9478 g_hash_table_destroy (acfg->token_info_hash);
9479 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9480 g_hash_table_destroy (acfg->image_hash);
9481 g_hash_table_destroy (acfg->unwind_info_offsets);
9482 g_hash_table_destroy (acfg->method_label_hash);
9483 g_hash_table_destroy (acfg->export_names);
9484 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9485 g_hash_table_destroy (acfg->klass_blob_hash);
9486 g_hash_table_destroy (acfg->method_blob_hash);
9487 got_info_free (&acfg->got_info);
9488 got_info_free (&acfg->llvm_got_info);
9489 mono_mempool_destroy (acfg->mempool);
9493 #define WRAPPER(e,n) n,
9494 static const char* const
9495 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9496 #include "mono/metadata/wrapper-types.h"
9500 static G_GNUC_UNUSED const char*
9501 get_wrapper_type_name (int type)
9503 return wrapper_type_names [type];
9509 static void aot_dump (MonoAotCompile *acfg)
9515 mono_json_writer_init (&writer);
9517 mono_json_writer_object_begin(&writer);
9520 mono_json_writer_indent (&writer);
9521 mono_json_writer_object_key(&writer, "methods");
9522 mono_json_writer_array_begin (&writer);
9525 for (i = 0; i < acfg->nmethods; ++i) {
9530 cfg = acfg->cfgs [i];
9534 method = cfg->orig_method;
9536 mono_json_writer_indent (&writer);
9537 mono_json_writer_object_begin(&writer);
9539 mono_json_writer_indent (&writer);
9540 mono_json_writer_object_key(&writer, "name");
9541 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9543 mono_json_writer_indent (&writer);
9544 mono_json_writer_object_key(&writer, "signature");
9545 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9546 /*signature=*/TRUE));
9548 mono_json_writer_indent (&writer);
9549 mono_json_writer_object_key(&writer, "code_size");
9550 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9552 klass = method->klass;
9554 mono_json_writer_indent (&writer);
9555 mono_json_writer_object_key(&writer, "class");
9556 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9558 mono_json_writer_indent (&writer);
9559 mono_json_writer_object_key(&writer, "namespace");
9560 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9562 mono_json_writer_indent (&writer);
9563 mono_json_writer_object_key(&writer, "wrapper_type");
9564 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9566 mono_json_writer_indent_pop (&writer);
9567 mono_json_writer_indent (&writer);
9568 mono_json_writer_object_end (&writer);
9569 mono_json_writer_printf (&writer, ",\n");
9572 mono_json_writer_indent_pop (&writer);
9573 mono_json_writer_indent (&writer);
9574 mono_json_writer_array_end (&writer);
9575 mono_json_writer_printf (&writer, ",\n");
9579 mono_json_writer_indent_push (&writer);
9580 mono_json_writer_indent (&writer);
9581 mono_json_writer_object_key(&writer, "plt");
9582 mono_json_writer_array_begin (&writer);
9584 for (i = 0; i < acfg->plt_offset; ++i) {
9585 MonoPltEntry *plt_entry = NULL;
9590 * The first plt entry is unused.
9594 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9597 mono_json_writer_indent (&writer);
9598 mono_json_writer_printf (&writer, "{ ");
9599 mono_json_writer_object_key(&writer, "symbol");
9600 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9603 mono_json_writer_indent_pop (&writer);
9604 mono_json_writer_indent (&writer);
9605 mono_json_writer_array_end (&writer);
9606 mono_json_writer_printf (&writer, ",\n");
9611 mono_json_writer_indent_push (&writer);
9612 mono_json_writer_indent (&writer);
9613 mono_json_writer_object_key(&writer, "got");
9614 mono_json_writer_array_begin (&writer);
9616 mono_json_writer_indent_push (&writer);
9617 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9618 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9620 mono_json_writer_indent (&writer);
9621 mono_json_writer_printf (&writer, "{ ");
9622 mono_json_writer_object_key(&writer, "patch_name");
9623 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9626 mono_json_writer_indent_pop (&writer);
9627 mono_json_writer_indent (&writer);
9628 mono_json_writer_array_end (&writer);
9629 mono_json_writer_printf (&writer, ",\n");
9632 mono_json_writer_indent_pop (&writer);
9633 mono_json_writer_indent (&writer);
9634 mono_json_writer_object_end (&writer);
9636 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9637 dumpfile = fopen (dumpname, "w+");
9640 fprintf (dumpfile, "%s", writer.text->str);
9643 mono_json_writer_destroy (&writer);
9646 static const char *preinited_jit_icalls[] = {
9647 "mono_aot_init_llvm_method",
9648 "mono_aot_init_gshared_method_this",
9649 "mono_aot_init_gshared_method_rgctx",
9650 "mono_llvm_throw_corlib_exception",
9651 "mono_init_vtable_slot",
9652 "mono_helper_ldstr_mscorlib"
9656 add_preinit_got_slots (MonoAotCompile *acfg)
9662 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9663 * during method initialization etc.
9666 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9667 ji->type = MONO_PATCH_INFO_IMAGE;
9668 ji->data.image = acfg->image;
9669 get_got_offset (acfg, FALSE, ji);
9670 get_got_offset (acfg, TRUE, ji);
9672 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9673 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9674 get_got_offset (acfg, FALSE, ji);
9675 get_got_offset (acfg, TRUE, ji);
9677 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9678 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9679 get_got_offset (acfg, FALSE, ji);
9680 get_got_offset (acfg, TRUE, ji);
9682 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9683 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9684 get_got_offset (acfg, FALSE, ji);
9685 get_got_offset (acfg, TRUE, ji);
9687 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9688 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9689 get_got_offset (acfg, FALSE, ji);
9690 get_got_offset (acfg, TRUE, ji);
9692 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9693 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9694 get_got_offset (acfg, FALSE, ji);
9695 get_got_offset (acfg, TRUE, ji);
9697 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9698 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
9699 get_got_offset (acfg, FALSE, ji);
9700 get_got_offset (acfg, TRUE, ji);
9702 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
9703 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9704 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9705 ji->data.name = preinited_jit_icalls [i];
9706 get_got_offset (acfg, FALSE, ji);
9707 get_got_offset (acfg, TRUE, ji);
9710 acfg->nshared_got_entries = acfg->got_offset;
9714 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9716 MonoImage *image = ass->image;
9719 MonoAotCompile *acfg;
9720 char *outfile_name, *tmp_outfile_name, *p;
9721 char llvm_stats_msg [256];
9725 acfg = acfg_create (ass, opts);
9727 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9728 acfg->aot_opts.write_symbols = TRUE;
9729 acfg->aot_opts.ntrampolines = 1024;
9730 acfg->aot_opts.nrgctx_trampolines = 1024;
9731 acfg->aot_opts.nimt_trampolines = 128;
9732 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9733 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9734 acfg->aot_opts.llvm_path = g_strdup ("");
9735 acfg->aot_opts.temp_path = g_strdup ("");
9737 acfg->aot_opts.use_trampolines_page = TRUE;
9740 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9742 if (acfg->aot_opts.logfile) {
9743 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9746 if (acfg->aot_opts.data_outfile) {
9747 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
9748 if (!acfg->data_outfile) {
9749 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
9752 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
9755 //acfg->aot_opts.print_skipped_methods = TRUE;
9757 #if !defined(ENABLE_GSHAREDVT)
9758 if (opts & MONO_OPT_GSHAREDVT) {
9759 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9764 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
9765 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
9766 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9771 #if defined(ENABLE_GSHAREDVT)
9772 if (acfg->aot_opts.llvm_only) {
9773 acfg->opts |= MONO_OPT_GSHAREDVT;
9774 opts |= MONO_OPT_GSHAREDVT;
9778 if (opts & MONO_OPT_GSHAREDVT)
9779 mono_set_generic_sharing_vt_supported (TRUE);
9781 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9783 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9784 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9785 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9790 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9791 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9795 if (acfg->aot_opts.static_link)
9796 acfg->aot_opts.asm_writer = TRUE;
9798 if (acfg->aot_opts.soft_debug) {
9799 MonoDebugOptions *opt = mini_get_debug_options ();
9801 opt->mdb_optimizations = TRUE;
9802 opt->gen_sdb_seq_points = TRUE;
9804 if (!mono_debug_enabled ()) {
9805 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9808 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
9811 if (mono_use_llvm || acfg->aot_opts.llvm) {
9813 acfg->aot_opts.asm_writer = TRUE;
9814 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
9816 if (acfg->aot_opts.soft_debug) {
9817 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9823 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9824 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9829 * Emit all LLVM code into a separate assembly/object file and link with it
9832 if (!acfg->aot_opts.asm_only) {
9833 acfg->llvm_owriter = TRUE;
9834 } else if (acfg->aot_opts.llvm_outfile) {
9835 int len = strlen (acfg->aot_opts.llvm_outfile);
9837 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9838 acfg->llvm_owriter = TRUE;
9842 if (mono_aot_mode_is_full (&acfg->aot_opts))
9843 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
9845 if (mono_threads_is_coop_enabled ())
9846 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
9848 if (acfg->aot_opts.instances_logfile_path) {
9849 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9850 if (!acfg->instances_logfile) {
9851 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9856 load_profile_files (acfg);
9858 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9859 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9860 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9862 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9863 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9864 if (acfg->opts & MONO_OPT_GSHAREDVT)
9865 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9868 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9872 if (acfg->llvm && acfg->thumb_mixed)
9873 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
9874 if (acfg->aot_opts.llvm_only)
9875 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
9877 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9878 /* Get rid of characters which cannot occur in symbols */
9879 for (p = acfg->assembly_name_sym; *p; ++p) {
9880 if (!(isalnum (*p) || *p == '_'))
9884 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9885 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9886 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9888 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9889 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9892 acfg->method_index = 1;
9894 if (mono_aot_mode_is_full (&acfg->aot_opts))
9895 mono_set_partial_sharing_supported (TRUE);
9897 res = collect_methods (acfg);
9901 acfg->cfgs_size = acfg->methods->len + 32;
9902 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9904 /* PLT offset 0 is reserved for the PLT trampoline */
9905 acfg->plt_offset = 1;
9906 add_preinit_got_slots (acfg);
9911 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
9917 compile_methods (acfg);
9921 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9927 if (acfg->aot_opts.asm_only) {
9928 if (acfg->aot_opts.outfile) {
9929 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9930 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9932 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9933 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9935 g_assert (acfg->aot_opts.llvm_outfile);
9936 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9937 if (acfg->llvm_owriter)
9938 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9940 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9942 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9943 g_strdup_printf ("%s", "temp") :
9944 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9946 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9947 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9948 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9953 if (acfg->aot_opts.asm_only) {
9954 if (acfg->aot_opts.outfile)
9955 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9957 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9958 acfg->fp = fopen (acfg->tmpfname, "w+");
9960 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9961 acfg->fp = fdopen (i, "w+");
9963 if (acfg->fp == 0) {
9964 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9967 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9969 tmp_outfile_name = NULL;
9970 outfile_name = NULL;
9972 /* Compute symbols for methods */
9973 for (i = 0; i < acfg->nmethods; ++i) {
9974 if (acfg->cfgs [i]) {
9975 MonoCompile *cfg = acfg->cfgs [i];
9976 int method_index = get_method_index (acfg, cfg->orig_method);
9978 if (COMPILE_LLVM (cfg))
9979 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9980 else if (acfg->global_symbols || acfg->llvm)
9981 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9983 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9984 cfg->asm_debug_symbol = cfg->asm_symbol;
9988 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9990 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9991 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9994 //acfg->gas_line_numbers = TRUE;
9997 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9998 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9999 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10002 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10005 mono_img_writer_emit_start (acfg->w);
10008 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10014 emit_extra_methods (acfg);
10016 emit_trampolines (acfg);
10018 emit_class_name_table (acfg);
10020 emit_got_info (acfg, FALSE);
10022 emit_got_info (acfg, TRUE);
10024 emit_exception_info (acfg);
10026 emit_unwind_info (acfg);
10028 emit_class_info (acfg);
10032 emit_image_table (acfg);
10038 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10041 const char *gc_name = mono_gc_get_gc_name ();
10042 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10047 emit_objc_selectors (acfg);
10049 emit_globals (acfg);
10051 emit_file_info (acfg);
10054 emit_dwarf_info (acfg);
10055 mono_dwarf_writer_close (acfg->dwarf);
10058 emit_mem_end (acfg);
10060 if (acfg->need_pt_gnu_stack) {
10061 /* This is required so the .so doesn't have an executable stack */
10062 /* The bin writer already emits this */
10063 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10066 if (acfg->aot_opts.data_outfile)
10067 fclose (acfg->data_outfile);
10073 res = emit_llvm_file (acfg);
10081 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10084 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10086 strcpy (llvm_stats_msg, "");
10088 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;
10090 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",
10091 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10092 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10093 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10094 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10095 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10096 acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
10097 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10098 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10099 (int)(acfg->got_offset * sizeof (gpointer)));
10100 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10101 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10103 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10104 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10105 if (acfg->stats.genericcount)
10106 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10107 if (acfg->stats.abscount)
10108 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10109 if (acfg->stats.lmfcount)
10110 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10111 if (acfg->stats.ocount)
10112 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10115 res = mono_img_writer_emit_writeout (acfg->w);
10120 res = compile_asm (acfg);
10126 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10128 if (acfg->aot_opts.stats) {
10131 aot_printf (acfg, "GOT slot distribution:\n");
10132 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10133 if (acfg->stats.got_slot_types [i])
10134 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]);
10137 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);
10139 if (acfg->aot_opts.dump_json)
10152 mono_aot_readonly_field_override (MonoClassField *field)
10158 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10164 mono_aot_is_shared_got_offset (int offset)