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/reflection-internals.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/gc-internals.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internals.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
55 #include "aot-compiler.h"
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
60 #include "mini-llvm.h"
62 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
64 #if defined(__linux__) || defined(__native_client_codegen__)
65 #define RODATA_SECT ".rodata"
66 #elif defined(TARGET_MACH)
67 #define RODATA_SECT ".section __TEXT, __const"
69 #define RODATA_SECT ".text"
72 #define TV_DECLARE(name) gint64 name
73 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
74 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
77 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
78 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
80 /* predefined values for static readonly fields without needed to run the .cctor */
81 typedef struct _ReadOnlyValue ReadOnlyValue;
82 struct _ReadOnlyValue {
85 int type; /* to be used later for typechecking to prevent user errors */
94 static ReadOnlyValue *readonly_values;
96 typedef struct MonoAotOptions {
101 gboolean write_symbols;
102 gboolean metadata_only;
103 gboolean bind_to_runtime_version;
106 gboolean static_link;
110 gboolean dwarf_debug;
112 gboolean log_generics;
113 gboolean log_instances;
114 gboolean gen_seq_points_file;
115 char *gen_seq_points_file_path;
116 gboolean direct_pinvoke;
117 gboolean direct_icalls;
118 gboolean no_direct_calls;
119 gboolean use_trampolines_page;
120 gboolean no_instances;
126 int nrgctx_trampolines;
127 int nimt_trampolines;
128 int ngsharedvt_arg_trampolines;
129 int nrgctx_fetch_trampolines;
130 gboolean print_skipped_methods;
137 char *instances_logfile_path;
144 METHOD_CAT_GSHAREDVT,
150 typedef struct MonoAotStats {
151 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
152 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
153 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
154 int got_slots, offsets_size;
155 int method_categories [METHOD_CAT_NUM];
156 int got_slot_types [MONO_PATCH_INFO_NONE];
157 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
158 int jit_time, gen_time, link_time;
161 typedef struct GotInfo {
162 GHashTable *patch_to_got_offset;
163 GHashTable **patch_to_got_offset_by_type;
164 GPtrArray *got_patches;
167 typedef struct MonoAotCompile {
170 GHashTable *method_indexes;
171 GHashTable *method_depth;
174 GHashTable **patch_to_plt_entry;
175 GHashTable *plt_offset_to_entry;
176 //GHashTable *patch_to_got_offset;
177 //GHashTable **patch_to_got_offset_by_type;
178 //GPtrArray *got_patches;
179 GotInfo got_info, llvm_got_info;
180 GHashTable *image_hash;
181 GHashTable *method_to_cfg;
182 GHashTable *token_info_hash;
183 GHashTable *method_to_pinvoke_import;
184 GPtrArray *extra_methods;
185 GPtrArray *image_table;
187 GPtrArray *method_order;
188 GHashTable *export_names;
189 /* Maps MonoClass* -> blob offset */
190 GHashTable *klass_blob_hash;
191 /* Maps MonoMethod* -> blob offset */
192 GHashTable *method_blob_hash;
193 GHashTable *gsharedvt_in_signatures;
194 GHashTable *gsharedvt_out_signatures;
195 guint32 *plt_got_info_offsets;
196 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
197 /* Number of GOT entries reserved for trampolines */
198 guint32 num_trampoline_got_entries;
199 guint32 tramp_page_size;
201 guint32 table_offsets [MONO_AOT_TABLE_NUM];
202 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
203 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
204 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
205 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
207 MonoAotOptions aot_opts;
211 MonoMemPool *mempool;
214 char *static_linking_symbol;
216 gboolean gas_line_numbers;
217 /* Whenever to emit an object file directly from llc */
218 gboolean llvm_owriter;
220 MonoDwarfWriter *dwarf;
227 GHashTable *unwind_info_offsets;
228 GPtrArray *unwind_ops;
229 guint32 unwind_info_offset;
232 char *llvm_got_symbol;
234 char *llvm_eh_frame_symbol;
235 GHashTable *method_label_hash;
236 const char *temp_prefix;
237 const char *user_symbol_prefix;
238 const char *llvm_label_prefix;
239 const char *inst_directive;
241 guint32 label_generator;
243 gboolean has_jitted_code;
244 MonoAotFileFlags flags;
245 MonoDynamicStream blob;
246 gboolean blob_closed;
247 MonoClass **typespec_classes;
250 char *assembly_name_sym;
251 GHashTable *plt_entry_debug_sym_cache;
252 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
253 GHashTable *ginst_hash;
254 GHashTable *dwarf_ln_filenames;
255 gboolean global_symbols;
256 int objc_selector_index, objc_selector_index_2;
257 GPtrArray *objc_selectors;
258 GHashTable *objc_selector_to_index;
260 FILE *instances_logfile;
268 char *symbol, *llvm_symbol, *debug_sym;
270 gboolean jit_used, llvm_used;
273 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
274 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
276 /* This points to the current acfg in LLVM mode */
277 static MonoAotCompile *llvm_acfg;
279 #ifdef HAVE_ARRAY_ELEM_INIT
280 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
281 #define MSGSTRFIELD1(line) str##line
282 static const struct msgstr_t {
283 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
284 #include "patch-info.h"
287 #define PATCH_INFO(a,b) b,
288 #include "patch-info.h"
291 static const gint16 opidx [] = {
292 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
293 #include "patch-info.h"
297 static G_GNUC_UNUSED const char*
298 get_patch_name (int info)
300 return (const char*)&opstr + opidx [info];
304 #define PATCH_INFO(a,b) b,
305 static const char* const
306 patch_types [MONO_PATCH_INFO_NUM + 1] = {
307 #include "patch-info.h"
311 static G_GNUC_UNUSED const char*
312 get_patch_name (int info)
314 return patch_types [info];
320 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
323 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
326 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
332 output = acfg->logfile;
336 va_start (args, format);
337 vfprintf (output, format, args);
342 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
348 output = acfg->logfile;
352 va_start (args, format);
353 vfprintf (output, format, args);
358 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
363 if (mono_error_ok (error))
367 output = acfg->logfile;
371 va_start (args, format);
372 vfprintf (output, format, args);
374 mono_error_cleanup (error);
376 g_error ("FullAOT cannot continue if there are loader errors");
379 /* Wrappers around the image writer functions */
382 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
384 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
388 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
390 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
394 emit_label (MonoAotCompile *acfg, const char *name)
396 mono_img_writer_emit_label (acfg->w, name);
400 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
402 mono_img_writer_emit_bytes (acfg->w, buf, size);
406 emit_string (MonoAotCompile *acfg, const char *value)
408 mono_img_writer_emit_string (acfg->w, value);
412 emit_line (MonoAotCompile *acfg)
414 mono_img_writer_emit_line (acfg->w);
418 emit_alignment (MonoAotCompile *acfg, int size)
420 mono_img_writer_emit_alignment (acfg->w, size);
424 emit_alignment_code (MonoAotCompile *acfg, int size)
426 if (acfg->align_pad_value)
427 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
429 mono_img_writer_emit_alignment (acfg->w, size);
433 emit_padding (MonoAotCompile *acfg, int size)
438 if (acfg->align_pad_value) {
439 for (i = 0; i < 16; ++i)
440 buf [i] = acfg->align_pad_value;
442 memset (buf, 0, sizeof (buf));
445 for (i = 0; i < size; i += 16) {
447 emit_bytes (acfg, buf, size - i);
449 emit_bytes (acfg, buf, 16);
454 emit_pointer (MonoAotCompile *acfg, const char *target)
456 mono_img_writer_emit_pointer (acfg->w, target);
460 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
462 if (prefix [0] != '\0') {
463 char *s = g_strdup_printf ("%s%s", prefix, target);
464 mono_img_writer_emit_pointer (acfg->w, s);
467 mono_img_writer_emit_pointer (acfg->w, target);
472 emit_int16 (MonoAotCompile *acfg, int value)
474 mono_img_writer_emit_int16 (acfg->w, value);
478 emit_int32 (MonoAotCompile *acfg, int value)
480 mono_img_writer_emit_int32 (acfg->w, value);
484 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
486 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
490 emit_zero_bytes (MonoAotCompile *acfg, int num)
492 mono_img_writer_emit_zero_bytes (acfg->w, num);
496 emit_byte (MonoAotCompile *acfg, guint8 val)
498 mono_img_writer_emit_byte (acfg->w, val);
501 #ifdef __native_client_codegen__
503 emit_nacl_call_alignment (MonoAotCompile *acfg)
505 mono_img_writer_emit_nacl_call_alignment (acfg->w);
509 static G_GNUC_UNUSED void
510 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
512 mono_img_writer_emit_global (acfg->w, name, func);
516 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
518 if (acfg->aot_opts.no_dlsym) {
519 g_ptr_array_add (acfg->globals, g_strdup (name));
520 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
522 mono_img_writer_emit_global (acfg->w, name, func);
527 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
529 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
532 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
534 emit_info_symbol (MonoAotCompile *acfg, const char *name)
539 emit_label (acfg, name);
540 /* LLVM generated code references this */
541 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
542 emit_label (acfg, symbol);
543 emit_global_inner (acfg, symbol, FALSE);
545 emit_label (acfg, name);
550 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
553 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
557 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
559 /* On apple, all symbols need to be aligned to avoid warnings from ld */
560 emit_alignment (acfg, 4);
562 mono_img_writer_emit_label (acfg->w, name);
563 mono_img_writer_emit_string (acfg->w, value);
566 static G_GNUC_UNUSED void
567 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
570 guint8 b = value & 0x7f;
572 if (value != 0) /* more bytes to come */
578 static G_GNUC_UNUSED void
579 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
582 gboolean negative = (value < 0);
589 /* the following is unnecessary if the
590 * implementation of >>= uses an arithmetic rather
591 * than logical shift for a signed left operand
595 value |= - ((gint64)1 <<(size - 7));
596 /* sign bit of byte is second high order bit (0x40) */
597 if ((value == 0 && !(byte & 0x40)) ||
598 (value == -1 && (byte & 0x40)))
602 emit_byte (acfg, byte);
606 static G_GNUC_UNUSED void
607 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
612 guint8 b = value & 0x7f;
614 if (value != 0) /* more bytes to come */
622 static G_GNUC_UNUSED void
623 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
626 gboolean negative = (value < 0);
634 /* the following is unnecessary if the
635 * implementation of >>= uses an arithmetic rather
636 * than logical shift for a signed left operand
640 value |= - (1 <<(size - 7));
641 /* sign bit of byte is second high order bit (0x40) */
642 if ((value == 0 && !(byte & 0x40)) ||
643 (value == -1 && (byte & 0x40)))
654 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
657 buf [0] = (val >> 0) & 0xff;
658 buf [1] = (val >> 8) & 0xff;
659 buf [2] = (val >> 16) & 0xff;
660 buf [3] = (val >> 24) & 0xff;
666 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
668 buf [0] = (val >> 0) & 0xff;
669 buf [1] = (val >> 8) & 0xff;
675 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
677 int len = strlen (s);
679 memcpy (buf, s, len + 1);
680 *endbuf = buf + len + 1;
684 emit_unset_mode (MonoAotCompile *acfg)
686 mono_img_writer_emit_unset_mode (acfg->w);
689 static G_GNUC_UNUSED void
690 emit_set_thumb_mode (MonoAotCompile *acfg)
692 emit_unset_mode (acfg);
693 fprintf (acfg->fp, ".code 16\n");
696 static G_GNUC_UNUSED void
697 emit_set_arm_mode (MonoAotCompile *acfg)
699 emit_unset_mode (acfg);
700 fprintf (acfg->fp, ".code 32\n");
704 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
709 g_assert (size % 4 == 0);
710 emit_unset_mode (acfg);
711 for (i = 0; i < size; i += 4)
712 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
714 emit_bytes (acfg, buf, size);
718 /* ARCHITECTURE SPECIFIC CODE */
720 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
721 #define EMIT_DWARF_INFO 1
724 #if defined(TARGET_ARM)
725 #define AOT_FUNC_ALIGNMENT 4
727 #define AOT_FUNC_ALIGNMENT 16
729 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
730 #undef AOT_FUNC_ALIGNMENT
731 #define AOT_FUNC_ALIGNMENT 32
734 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
735 #define PPC_LD_OP "ld"
736 #define PPC_LDX_OP "ldx"
738 #define PPC_LD_OP "lwz"
739 #define PPC_LDX_OP "lwzx"
743 #define AOT_TARGET_STR "AMD64"
748 #define AOT_TARGET_STR "ARM (MACH)"
750 #define AOT_TARGET_STR "ARM (!MACH)"
756 #define AOT_TARGET_STR "ARM64 (MACH)"
758 #define AOT_TARGET_STR "ARM64 (!MACH)"
762 #ifdef TARGET_POWERPC64
763 #ifdef __mono_ilp32__
764 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
766 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
769 #ifdef TARGET_POWERPC
770 #ifdef __mono_ilp32__
771 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
773 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
780 #define AOT_TARGET_STR "X86 (WIN32)"
781 #elif defined(__native_client_codegen__)
782 #define AOT_TARGET_STR "X86 (native client codegen)"
784 #define AOT_TARGET_STR "X86 (!native client codegen)"
788 #ifndef AOT_TARGET_STR
789 #define AOT_TARGET_STR ""
793 arch_init (MonoAotCompile *acfg)
795 acfg->llc_args = g_string_new ("");
796 acfg->as_args = g_string_new ("");
799 * The prefix LLVM likes to put in front of symbol names on darwin.
800 * The mach-os specs require this for globals, but LLVM puts them in front of all
801 * symbols. We need to handle this, since we need to refer to LLVM generated
804 acfg->llvm_label_prefix = "";
805 acfg->user_symbol_prefix = "";
807 #if defined(TARGET_X86)
808 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
811 #if defined(TARGET_AMD64)
812 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
814 acfg->align_pad_value = 0x90;
818 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
819 g_string_append (acfg->llc_args, "-mattr=+v6");
822 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
823 g_string_append (acfg->as_args, " -mfpu=vfp3");
825 g_string_append (acfg->llc_args, " -soft-float");
828 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
829 acfg->thumb_mixed = TRUE;
831 if (acfg->aot_opts.mtriple)
832 mono_arch_set_target (acfg->aot_opts.mtriple);
836 acfg->inst_directive = ".inst";
837 if (acfg->aot_opts.mtriple)
838 mono_arch_set_target (acfg->aot_opts.mtriple);
842 acfg->user_symbol_prefix = "_";
843 acfg->llvm_label_prefix = "_";
844 acfg->inst_directive = ".word";
845 acfg->need_no_dead_strip = TRUE;
846 acfg->aot_opts.gnu_asm = TRUE;
849 #if defined(__linux__) && !defined(TARGET_ARM)
850 acfg->need_pt_gnu_stack = TRUE;
854 acfg->global_symbols = TRUE;
860 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
864 #ifdef MONO_ARCH_AOT_SUPPORTED
866 * arch_emit_direct_call:
868 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
872 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
874 #if defined(TARGET_X86) || defined(TARGET_AMD64)
875 /* Need to make sure this is exactly 5 bytes long */
876 emit_unset_mode (acfg);
877 fprintf (acfg->fp, "call %s\n", target);
879 #elif defined(TARGET_ARM)
880 emit_unset_mode (acfg);
882 fprintf (acfg->fp, "blx %s\n", target);
884 fprintf (acfg->fp, "bl %s\n", target);
886 #elif defined(TARGET_ARM64)
887 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
888 #elif defined(TARGET_POWERPC)
889 emit_unset_mode (acfg);
890 fprintf (acfg->fp, "bl %s\n", target);
893 g_assert_not_reached ();
900 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
902 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
903 * in in the 2. slot of every GOT, and require every method to place the GOT
904 * address in r30, even when it doesn't access the GOT otherwise. This way,
905 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
910 * PPC64 uses function descriptors which greatly complicate all code, since
911 * these are used very inconsistently in the runtime. Some functions like
912 * mono_compile_method () return ftn descriptors, while others like the
913 * trampoline creation functions do not.
914 * We assume that all GOT slots contain function descriptors, and create
915 * descriptors in aot-runtime.c when needed.
916 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
917 * from function descriptors, we could do the same, but it would require
918 * rewriting all the ppc/aot code to handle function descriptors properly.
919 * So instead, we use the same approach as on PPC32.
920 * This is a horrible mess, but fixing it would probably lead to an even bigger
926 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
929 #ifdef MONO_ARCH_AOT_SUPPORTED
931 * arch_emit_got_offset:
933 * The memory pointed to by CODE should hold native code for computing the GOT
934 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
935 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
938 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
940 #if defined(TARGET_POWERPC64)
941 emit_unset_mode (acfg);
943 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
944 * unsupported relocations. So we store the got address into the .Lgot_addr
945 * symbol which is in the text segment, compute its address, and load it.
947 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
948 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
949 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
950 fprintf (acfg->fp, "add 30, 30, 0\n");
951 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
952 acfg->label_generator ++;
954 #elif defined(TARGET_POWERPC)
955 emit_unset_mode (acfg);
956 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
957 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
958 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
959 acfg->label_generator ++;
962 guint32 offset = mono_arch_get_patch_offset (code);
963 emit_bytes (acfg, code, offset);
964 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
966 *code_size = offset + 4;
971 * arch_emit_got_access:
973 * The memory pointed to by CODE should hold native code for loading a GOT
974 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
975 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
978 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
981 /* mov reg, got+offset(%rip) */
983 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
987 /* Decode reg, see amd64_mov_reg_membase () */
988 rex_r = code [0] & AMD64_REX_R;
989 g_assert (code [0] == 0x49 + rex_r);
990 g_assert (code [1] == 0x8b);
991 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
993 emit_unset_mode (acfg);
994 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
997 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
998 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
999 *code_size = mono_arch_get_patch_offset (code) + 4;
1001 #elif defined(TARGET_X86)
1002 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1003 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1004 *code_size = mono_arch_get_patch_offset (code) + 4;
1005 #elif defined(TARGET_ARM)
1006 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1007 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1008 *code_size = mono_arch_get_patch_offset (code) + 4;
1009 #elif defined(TARGET_ARM64)
1010 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1011 arm64_emit_got_access (acfg, code, got_slot, code_size);
1012 #elif defined(TARGET_POWERPC)
1017 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1019 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1020 g_assert (code - buf == 8);
1021 emit_bytes (acfg, buf, code - buf);
1022 *code_size = code - buf;
1025 g_assert_not_reached ();
1031 #ifdef MONO_ARCH_AOT_SUPPORTED
1033 * arch_emit_objc_selector_ref:
1035 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1038 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1040 #if defined(TARGET_ARM)
1043 int lindex = acfg->objc_selector_index_2 ++;
1045 /* Emit ldr.imm/b */
1046 emit_bytes (acfg, code, 8);
1048 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1049 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1051 emit_label (acfg, symbol1);
1052 mono_img_writer_emit_unset_mode (acfg->w);
1053 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1056 #elif defined(TARGET_ARM64)
1057 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1059 g_assert_not_reached ();
1065 * arch_emit_plt_entry:
1067 * Emit code for the PLT entry.
1068 * The plt entry should look like this:
1069 * <indirect jump to GOT_SYMBOL + OFFSET>
1070 * <INFO_OFFSET embedded into the instruction stream>
1073 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1075 #if defined(TARGET_X86)
1076 #if defined(__default_codegen__)
1077 /* jmp *<offset>(%ebx) */
1078 emit_byte (acfg, 0xff);
1079 emit_byte (acfg, 0xa3);
1080 emit_int32 (acfg, offset);
1081 /* Used by mono_aot_get_plt_info_offset */
1082 emit_int32 (acfg, info_offset);
1083 #elif defined(__native_client_codegen__)
1084 const guint8 kSizeOfNaClJmp = 11;
1085 guint8 bytes[kSizeOfNaClJmp];
1086 guint8 *pbytes = &bytes[0];
1088 x86_jump_membase32 (pbytes, X86_EBX, offset);
1089 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1090 /* four bytes of data, used by mono_arch_patch_plt_entry */
1091 /* For Native Client, make this work with data embedded in push. */
1092 emit_byte (acfg, 0x68); /* hide data in a push */
1093 emit_int32 (acfg, info_offset);
1094 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1095 #endif /*__native_client_codegen__*/
1096 #elif defined(TARGET_AMD64)
1097 #if defined(__default_codegen__)
1098 emit_unset_mode (acfg);
1099 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1100 /* Used by mono_aot_get_plt_info_offset */
1101 emit_int32 (acfg, info_offset);
1102 acfg->stats.plt_size += 10;
1103 #elif defined(__native_client_codegen__)
1105 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1106 guint8 *code = buf_aligned;
1108 /* mov <OFFSET>(%rip), %r11d */
1109 emit_byte (acfg, '\x45');
1110 emit_byte (acfg, '\x8b');
1111 emit_byte (acfg, '\x1d');
1112 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1114 amd64_jump_reg (code, AMD64_R11);
1115 /* This should be constant for the plt patch */
1116 g_assert ((size_t)(code-buf_aligned) == 10);
1117 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1119 /* Hide data in a push imm32 so it passes validation */
1120 emit_byte (acfg, 0x68); /* push */
1121 emit_int32 (acfg, info_offset);
1122 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1123 #endif /*__native_client_codegen__*/
1124 #elif defined(TARGET_ARM)
1129 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1130 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1131 emit_bytes (acfg, buf, code - buf);
1132 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1133 /* Used by mono_aot_get_plt_info_offset */
1134 emit_int32 (acfg, info_offset);
1135 #elif defined(TARGET_ARM64)
1136 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1137 #elif defined(TARGET_POWERPC)
1138 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1139 emit_unset_mode (acfg);
1140 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1141 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1142 fprintf (acfg->fp, "add 11, 11, 30\n");
1143 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1144 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1145 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1146 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1148 fprintf (acfg->fp, "mtctr 11\n");
1149 fprintf (acfg->fp, "bctr\n");
1150 emit_int32 (acfg, info_offset);
1152 g_assert_not_reached ();
1157 * arch_emit_llvm_plt_entry:
1159 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1160 * This is only needed on arm to handle thumb interop.
1163 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1165 #if defined(TARGET_ARM)
1166 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1167 /* The caller already transitioned to thumb */
1168 /* The code below should be 12 bytes long */
1169 /* clang has trouble encoding these instructions, so emit the binary */
1171 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1172 /* thumb can't encode ld pc, [pc, ip] */
1173 fprintf (acfg->fp, "add ip, pc, ip\n");
1174 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1175 fprintf (acfg->fp, "bx ip\n");
1177 emit_set_thumb_mode (acfg);
1178 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1179 fprintf (acfg->fp, ".2byte 0x44fc\n");
1180 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1181 fprintf (acfg->fp, ".2byte 0x4760\n");
1182 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1183 emit_int32 (acfg, info_offset);
1184 emit_unset_mode (acfg);
1185 emit_set_arm_mode (acfg);
1187 g_assert_not_reached ();
1191 /* Save unwind_info in the module and emit the offset to the information at symbol */
1192 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1194 guint32 uw_offset, encoded_len;
1197 emit_section_change (acfg, RODATA_SECT, 0);
1198 emit_global (acfg, symbol, FALSE);
1199 emit_label (acfg, symbol);
1201 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1202 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1204 emit_int32 (acfg, uw_offset);
1208 * arch_emit_specific_trampoline_pages:
1210 * Emits a page full of trampolines: each trampoline uses its own address to
1211 * lookup both the generic trampoline code and the data argument.
1212 * This page can be remapped in process multiple times so we can get an
1213 * unlimited number of trampolines.
1214 * Specifically this implementation uses the following trick: two memory pages
1215 * are allocated, with the first containing the data and the second containing the trampolines.
1216 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1217 * implementation does all the lifting.
1218 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1219 * on the arm 32 bit system.
1222 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1224 #if defined(TARGET_ARM)
1227 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1229 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1230 GSList *unwind_ops = NULL;
1231 #define COMMON_TRAMP_SIZE 16
1232 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1233 int imm8, rot_amount;
1236 if (!acfg->aot_opts.use_trampolines_page)
1239 acfg->tramp_page_size = pagesize;
1241 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1242 emit_alignment (acfg, pagesize);
1243 emit_global (acfg, symbol, TRUE);
1244 emit_label (acfg, symbol);
1246 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1248 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1249 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1250 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1251 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1253 g_assert (code - buf == COMMON_TRAMP_SIZE);
1256 emit_bytes (acfg, buf, code - buf);
1258 for (i = 0; i < count; ++i) {
1260 ARM_PUSH (code, 0x5fff);
1262 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1263 g_assert (code - buf == 8);
1264 emit_bytes (acfg, buf, code - buf);
1267 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1268 * the instruction pointer address, so the generic trampoline at the start of the page
1269 * subtracts 4096 to get to the data page and loads the values
1270 * We again fit the generic trampiline in 16 bytes.
1272 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1273 emit_global (acfg, symbol, TRUE);
1274 emit_label (acfg, symbol);
1276 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1277 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1278 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1279 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1281 g_assert (code - buf == COMMON_TRAMP_SIZE);
1284 emit_bytes (acfg, buf, code - buf);
1286 for (i = 0; i < count; ++i) {
1288 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1290 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1291 g_assert (code - buf == 8);
1292 emit_bytes (acfg, buf, code - buf);
1296 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1298 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1299 emit_global (acfg, symbol, TRUE);
1300 emit_label (acfg, symbol);
1302 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1303 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1304 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1305 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1306 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1307 g_assert (code - buf == COMMON_TRAMP_SIZE);
1309 emit_bytes (acfg, buf, code - buf);
1311 for (i = 0; i < count; ++i) {
1313 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1315 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1316 g_assert (code - buf == 8);
1317 emit_bytes (acfg, buf, code - buf);
1320 /* now the imt trampolines: each specific trampolines puts in the ip register
1321 * the instruction pointer address, so the generic trampoline at the start of the page
1322 * subtracts 4096 to get to the data page and loads the values
1324 #define IMT_TRAMP_SIZE 72
1325 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1326 emit_global (acfg, symbol, TRUE);
1327 emit_label (acfg, symbol);
1329 /* Need at least two free registers, plus a slot for storing the pc */
1330 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1332 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1333 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1334 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1336 /* The IMT method is in v5, r0 has the imt array address */
1339 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1340 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1341 imt_found_check = code;
1342 ARM_B_COND (code, ARMCOND_EQ, 0);
1344 /* End-of-loop check */
1345 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1346 loop_end_check = code;
1347 ARM_B_COND (code, ARMCOND_EQ, 0);
1350 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1351 loop_branch_back = code;
1353 arm_patch (loop_branch_back, loop_start);
1356 arm_patch (imt_found_check, code);
1357 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1358 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1359 /* Save it to the third stack slot */
1360 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1361 /* Restore the registers and branch */
1362 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1365 arm_patch (loop_end_check, code);
1366 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1367 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1368 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1372 g_assert (code - buf == IMT_TRAMP_SIZE);
1373 emit_bytes (acfg, buf, code - buf);
1375 for (i = 0; i < count; ++i) {
1377 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1379 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1380 g_assert (code - buf == 8);
1381 emit_bytes (acfg, buf, code - buf);
1384 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1385 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1386 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1387 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1389 /* Unwind info for specifc trampolines */
1390 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1391 /* We unwind to the original caller, from the stack, since lr is clobbered */
1392 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1393 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1394 save_unwind_info (acfg, symbol, unwind_ops);
1395 mono_free_unwind_info (unwind_ops);
1397 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1398 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1399 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1400 save_unwind_info (acfg, symbol, unwind_ops);
1401 mono_free_unwind_info (unwind_ops);
1403 /* Unwind info for rgctx trampolines */
1404 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1405 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1406 save_unwind_info (acfg, symbol, unwind_ops);
1408 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1409 save_unwind_info (acfg, symbol, unwind_ops);
1410 mono_free_unwind_info (unwind_ops);
1412 /* Unwind info for gsharedvt trampolines */
1413 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1414 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1415 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1416 save_unwind_info (acfg, symbol, unwind_ops);
1417 mono_free_unwind_info (unwind_ops);
1419 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1420 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1421 save_unwind_info (acfg, symbol, unwind_ops);
1422 mono_free_unwind_info (unwind_ops);
1424 /* Unwind info for imt trampolines */
1425 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1426 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1427 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1428 save_unwind_info (acfg, symbol, unwind_ops);
1429 mono_free_unwind_info (unwind_ops);
1431 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1432 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1433 save_unwind_info (acfg, symbol, unwind_ops);
1434 mono_free_unwind_info (unwind_ops);
1435 #elif defined(TARGET_ARM64)
1436 arm64_emit_specific_trampoline_pages (acfg);
1441 * arch_emit_specific_trampoline:
1443 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1444 * two GOT slots which contain the generic trampoline address and the trampoline
1445 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1448 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1451 * The trampolines created here are variations of the specific
1452 * trampolines created in mono_arch_create_specific_trampoline (). The
1454 * - the generic trampoline address is taken from a got slot.
1455 * - the offset of the got slot where the trampoline argument is stored
1456 * is embedded in the instruction stream, and the generic trampoline
1457 * can load the argument by loading the offset, adding it to the
1458 * address of the trampoline to get the address of the got slot, and
1459 * loading the argument from there.
1460 * - all the trampolines should be of the same length.
1462 #if defined(TARGET_AMD64)
1463 #if defined(__default_codegen__)
1464 /* This should be exactly 8 bytes long */
1466 /* call *<offset>(%rip) */
1468 emit_unset_mode (acfg);
1469 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1470 emit_zero_bytes (acfg, 2);
1472 emit_byte (acfg, '\x41');
1473 emit_byte (acfg, '\xff');
1474 emit_byte (acfg, '\x15');
1475 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1476 emit_zero_bytes (acfg, 1);
1478 #elif defined(__native_client_codegen__)
1480 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1481 guint8 *code = buf_aligned;
1486 /* Emit this call in 'code' so we can find out how long it is. */
1487 amd64_call_reg (code, AMD64_R11);
1488 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1489 call_len = code - call_start;
1491 /* The tramp_size is twice the NaCl alignment because it starts with */
1492 /* a call which needs to be aligned to the end of the boundary. */
1493 *tramp_size = kNaClAlignment*2;
1495 /* Emit nops to align call site below which is 7 bytes plus */
1496 /* the length of the call sequence emitted above. */
1497 /* Note: this requires the specific trampoline starts on a */
1498 /* kNaclAlignedment aligned address, which it does because */
1499 /* it's its own function that is aligned. */
1500 guint8 nop_buf[256];
1501 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1502 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1503 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1505 /* The trampoline is stored at the offset'th pointer, the -4 is */
1506 /* present because RIP relative addressing starts at the end of */
1507 /* the current instruction, while the label "." is relative to */
1508 /* the beginning of the current asm location, which in this case */
1509 /* is not the mov instruction, but the offset itself, due to the */
1510 /* way the bytes and ints are emitted here. */
1511 got_offset = (offset * sizeof(gpointer)) - 4;
1513 /* mov <OFFSET>(%rip), %r11d */
1514 emit_byte (acfg, '\x45');
1515 emit_byte (acfg, '\x8b');
1516 emit_byte (acfg, '\x1d');
1517 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1520 emit_bytes (acfg, call_start, call_len);
1522 /* The arg is stored at the offset+1 pointer, relative to beginning */
1523 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1524 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1526 /* We can't emit this data directly, hide in a "push imm32" */
1527 emit_byte (acfg, '\x68'); /* push */
1528 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1529 emit_alignment (acfg, kNaClAlignment);
1530 #endif /*__native_client_codegen__*/
1531 #elif defined(TARGET_ARM)
1535 /* This should be exactly 20 bytes long */
1538 ARM_PUSH (code, 0x5fff);
1539 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1540 /* Load the value from the GOT */
1541 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1543 ARM_BLX_REG (code, ARMREG_R1);
1545 g_assert (code - buf == 16);
1548 emit_bytes (acfg, buf, code - buf);
1550 * Only one offset is needed, since the second one would be equal to the
1553 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1554 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1555 #elif defined(TARGET_ARM64)
1556 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1557 #elif defined(TARGET_POWERPC)
1565 * PPC has no ip relative addressing, so we need to compute the address
1566 * of the mscorlib got. That is slow and complex, so instead, we store it
1567 * in the second got slot of every aot image. The caller already computed
1568 * the address of its got and placed it into r30.
1570 emit_unset_mode (acfg);
1571 /* Load mscorlib got address */
1572 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1573 /* Load generic trampoline address */
1574 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1575 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1576 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1577 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1578 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1580 fprintf (acfg->fp, "mtctr 11\n");
1581 /* Load trampoline argument */
1582 /* On ppc, we pass it normally to the generic trampoline */
1583 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1584 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1585 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1586 /* Branch to generic trampoline */
1587 fprintf (acfg->fp, "bctr\n");
1589 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1590 *tramp_size = 10 * 4;
1592 *tramp_size = 9 * 4;
1594 #elif defined(TARGET_X86)
1598 /* Similar to the PPC code above */
1600 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1603 /* Load mscorlib got address */
1604 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1605 /* Push trampoline argument */
1606 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1607 /* Load generic trampoline address */
1608 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1609 /* Branch to generic trampoline */
1610 x86_jump_reg (code, X86_ECX);
1612 #ifdef __native_client_codegen__
1614 /* emit nops to next 32 byte alignment */
1615 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1616 while (code < (buf + a)) x86_nop(code);
1619 emit_bytes (acfg, buf, code - buf);
1621 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1622 g_assert (code - buf == *tramp_size);
1624 g_assert_not_reached ();
1629 * arch_emit_unbox_trampoline:
1631 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1632 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1635 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1637 #if defined(TARGET_AMD64)
1642 this_reg = mono_arch_get_this_arg_reg (NULL);
1644 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1646 emit_bytes (acfg, buf, code - buf);
1649 emit_unset_mode (acfg);
1650 fprintf (acfg->fp, "jmp %s\n", call_target);
1652 emit_byte (acfg, '\xe9');
1653 emit_symbol_diff (acfg, call_target, ".", -4);
1655 #elif defined(TARGET_X86)
1662 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1664 emit_bytes (acfg, buf, code - buf);
1667 emit_byte (acfg, '\xe9');
1668 emit_symbol_diff (acfg, call_target, ".", -4);
1669 #elif defined(TARGET_ARM)
1673 if (acfg->thumb_mixed && cfg->compile_llvm) {
1674 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1675 fprintf (acfg->fp, "b %s\n", call_target);
1676 fprintf (acfg->fp, ".arm\n");
1677 fprintf (acfg->fp, ".align 2\n");
1683 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1685 emit_bytes (acfg, buf, code - buf);
1686 /* jump to method */
1687 if (acfg->thumb_mixed && cfg->compile_llvm)
1688 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1690 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1691 #elif defined(TARGET_ARM64)
1692 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1693 #elif defined(TARGET_POWERPC)
1696 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1697 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1699 g_assert_not_reached ();
1704 * arch_emit_static_rgctx_trampoline:
1706 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1707 * two GOT slots which contain the rgctx argument, and the method to jump to.
1708 * TRAMP_SIZE is set to the size of the emitted trampoline.
1709 * These kinds of trampolines cannot be enumerated statically, since there could
1710 * be one trampoline per method instantiation, so we emit the same code for all
1711 * trampolines, and parameterize them using two GOT slots.
1714 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1716 #if defined(TARGET_AMD64)
1717 #if defined(__default_codegen__)
1718 /* This should be exactly 13 bytes long */
1722 emit_unset_mode (acfg);
1723 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1724 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1726 /* mov <OFFSET>(%rip), %r10 */
1727 emit_byte (acfg, '\x4d');
1728 emit_byte (acfg, '\x8b');
1729 emit_byte (acfg, '\x15');
1730 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1732 /* jmp *<offset>(%rip) */
1733 emit_byte (acfg, '\xff');
1734 emit_byte (acfg, '\x25');
1735 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1737 #elif defined(__native_client_codegen__)
1739 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1740 guint8 *code = buf_aligned;
1742 /* mov <OFFSET>(%rip), %r10d */
1743 emit_byte (acfg, '\x45');
1744 emit_byte (acfg, '\x8b');
1745 emit_byte (acfg, '\x15');
1746 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1748 /* mov <OFFSET>(%rip), %r11d */
1749 emit_byte (acfg, '\x45');
1750 emit_byte (acfg, '\x8b');
1751 emit_byte (acfg, '\x1d');
1752 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1755 amd64_jump_reg (code, AMD64_R11);
1756 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1758 emit_alignment (acfg, kNaClAlignment);
1759 *tramp_size = kNaClAlignment;
1760 #endif /*__native_client_codegen__*/
1762 #elif defined(TARGET_ARM)
1766 /* This should be exactly 24 bytes long */
1769 /* Load rgctx value */
1770 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1771 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1772 /* Load branch addr + branch */
1773 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1774 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1776 g_assert (code - buf == 16);
1779 emit_bytes (acfg, buf, code - buf);
1780 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1781 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1782 #elif defined(TARGET_ARM64)
1783 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1784 #elif defined(TARGET_POWERPC)
1792 * PPC has no ip relative addressing, so we need to compute the address
1793 * of the mscorlib got. That is slow and complex, so instead, we store it
1794 * in the second got slot of every aot image. The caller already computed
1795 * the address of its got and placed it into r30.
1797 emit_unset_mode (acfg);
1798 /* Load mscorlib got address */
1799 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1801 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1802 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1803 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1804 /* Load target address */
1805 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1806 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1807 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1808 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1809 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1810 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1812 fprintf (acfg->fp, "mtctr 11\n");
1813 /* Branch to the target address */
1814 fprintf (acfg->fp, "bctr\n");
1816 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1817 *tramp_size = 11 * 4;
1819 *tramp_size = 9 * 4;
1822 #elif defined(TARGET_X86)
1826 /* Similar to the PPC code above */
1828 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1831 /* Load mscorlib got address */
1832 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1834 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1835 /* Branch to the target address */
1836 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1838 #ifdef __native_client_codegen__
1840 /* emit nops to next 32 byte alignment */
1841 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1842 while (code < (buf + a)) x86_nop(code);
1846 emit_bytes (acfg, buf, code - buf);
1848 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1849 g_assert (code - buf == *tramp_size);
1851 g_assert_not_reached ();
1856 * arch_emit_imt_thunk:
1858 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1859 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1860 * key is the IMT key, and ptr holds the address of a memory location holding
1861 * the address to branch to if the IMT arg matches the key. The array is
1862 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1864 * TRAMP_SIZE is set to the size of the emitted trampoline.
1867 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1869 #if defined(TARGET_AMD64)
1871 #if defined(__native_client_codegen__)
1874 guint8 *labels [16];
1876 guint8 *mov_buf_ptr = mov_buf;
1878 const int kSizeOfMove = 7;
1879 #if defined(__default_codegen__)
1880 code = buf = (guint8 *)g_malloc (256);
1881 #elif defined(__native_client_codegen__)
1882 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1883 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1884 /* The RIP relative move below is emitted first */
1889 /* FIXME: Optimize this, i.e. use binary search etc. */
1890 /* Maybe move the body into a separate function (slower, but much smaller) */
1892 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1895 emit_unset_mode (acfg);
1896 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1900 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1902 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1905 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1907 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1910 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1911 amd64_jump_code (code, labels [0]);
1914 mono_amd64_patch (labels [2], code);
1915 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1916 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1919 mono_amd64_patch (labels [1], code);
1920 /* Load fail tramp */
1921 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1922 /* Check if there is a fail tramp */
1923 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1925 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1926 /* Jump to fail tramp */
1927 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1930 mono_amd64_patch (labels [3], code);
1931 x86_breakpoint (code);
1934 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1935 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1936 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1937 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1938 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1939 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1941 emit_bytes (acfg, buf, code - buf);
1943 *tramp_size = code - buf + kSizeOfMove;
1944 #if defined(__native_client_codegen__)
1945 /* The tramp will be padded to the next kNaClAlignment bundle. */
1946 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1949 #if defined(__default_codegen__)
1951 #elif defined(__native_client_codegen__)
1955 #elif defined(TARGET_X86)
1957 #ifdef __native_client_codegen__
1960 guint8 *labels [16];
1962 #if defined(__default_codegen__)
1963 code = buf = g_malloc (256);
1964 #elif defined(__native_client_codegen__)
1965 buf_alloc = g_malloc (256 + kNaClAlignment);
1966 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1969 /* Allocate a temporary stack slot */
1970 x86_push_reg (code, X86_EAX);
1972 x86_push_reg (code, X86_EAX);
1974 /* Load mscorlib got address */
1975 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1977 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1980 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1982 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1985 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1987 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1990 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1991 x86_jump_code (code, labels [0]);
1994 mono_x86_patch (labels [2], code);
1995 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1996 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1997 /* Save the target address to the temporary stack location */
1998 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2000 x86_pop_reg (code, X86_EAX);
2001 /* Jump to the target address */
2005 mono_x86_patch (labels [1], code);
2006 /* Load fail tramp */
2007 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2008 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2010 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2011 /* Jump to fail tramp */
2012 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2013 x86_pop_reg (code, X86_EAX);
2017 mono_x86_patch (labels [3], code);
2018 x86_breakpoint (code);
2020 #ifdef __native_client_codegen__
2022 /* emit nops to next 32 byte alignment */
2023 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2024 while (code < (buf + a)) x86_nop(code);
2027 emit_bytes (acfg, buf, code - buf);
2029 *tramp_size = code - buf;
2031 #if defined(__default_codegen__)
2033 #elif defined(__native_client_codegen__)
2037 #elif defined(TARGET_ARM)
2039 guint8 *code, *code2, *labels [16];
2043 /* The IMT method is in v5 */
2045 /* Need at least two free registers, plus a slot for storing the pc */
2046 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2048 /* Load the parameter from the GOT */
2049 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2050 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2053 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2054 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2056 ARM_B_COND (code, ARMCOND_EQ, 0);
2058 /* End-of-loop check */
2059 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2061 ARM_B_COND (code, ARMCOND_EQ, 0);
2064 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2067 arm_patch (labels [4], labels [1]);
2070 arm_patch (labels [2], code);
2071 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2072 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2073 /* Save it to the third stack slot */
2074 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2075 /* Restore the registers and branch */
2076 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2079 arm_patch (labels [3], code);
2080 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2081 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2082 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2086 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2088 emit_bytes (acfg, buf, code - buf);
2089 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2091 *tramp_size = code - buf + 4;
2092 #elif defined(TARGET_ARM64)
2093 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2094 #elif defined(TARGET_POWERPC)
2096 guint8 *code, *labels [16];
2100 /* Load the mscorlib got address */
2101 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2102 /* Load the parameter from the GOT */
2103 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2104 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2106 /* Load and check key */
2108 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2109 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2111 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2113 /* End-of-loop check */
2114 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2116 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2119 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2122 mono_ppc_patch (labels [4], labels [1]);
2125 mono_ppc_patch (labels [2], code);
2126 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2127 /* r12 now contains the value of the vtable slot */
2128 /* this is not a function descriptor on ppc64 */
2129 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2130 ppc_mtctr (code, ppc_r12);
2131 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2134 mono_ppc_patch (labels [3], code);
2138 *tramp_size = code - buf;
2140 emit_bytes (acfg, buf, code - buf);
2142 g_assert_not_reached ();
2147 #if defined (TARGET_AMD64)
2150 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2153 g_assert (acfg->fp);
2154 emit_unset_mode (acfg);
2156 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2163 * arch_emit_gsharedvt_arg_trampoline:
2165 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2166 * two GOT slots which contain the argument, and the code to jump to.
2167 * TRAMP_SIZE is set to the size of the emitted trampoline.
2168 * These kinds of trampolines cannot be enumerated statically, since there could
2169 * be one trampoline per method instantiation, so we emit the same code for all
2170 * trampolines, and parameterize them using two GOT slots.
2173 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2175 #if defined(TARGET_X86)
2179 /* Similar to the PPC code above */
2181 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2184 /* Load mscorlib got address */
2185 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2187 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2188 /* Branch to the target address */
2189 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2191 #ifdef __native_client_codegen__
2193 /* emit nops to next 32 byte alignment */
2194 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2195 while (code < (buf + a)) x86_nop(code);
2199 emit_bytes (acfg, buf, code - buf);
2201 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2202 g_assert (code - buf == *tramp_size);
2203 #elif defined(TARGET_ARM)
2207 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2208 /* Similar to arch_emit_specific_trampoline () */
2211 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2212 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2213 /* Load the arg value from the GOT */
2214 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2215 /* Load the addr from the GOT */
2216 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2218 ARM_BX (code, ARMREG_R1);
2220 g_assert (code - buf == 20);
2223 emit_bytes (acfg, buf, code - buf);
2224 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2225 #elif defined(TARGET_ARM64)
2226 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2227 #elif defined (TARGET_AMD64)
2229 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2230 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2231 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2232 fprintf (acfg->fp, "jmp *%%r11\n");
2236 g_assert_not_reached ();
2240 /* END OF ARCH SPECIFIC CODE */
2243 mono_get_field_token (MonoClassField *field)
2245 MonoClass *klass = field->parent;
2248 for (i = 0; i < klass->field.count; ++i) {
2249 if (field == &klass->fields [i])
2250 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2253 g_assert_not_reached ();
2258 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2262 //printf ("ENCODE: %d 0x%x.\n", value, value);
2265 * Same encoding as the one used in the metadata, extended to handle values
2266 * greater than 0x1fffffff.
2268 if ((value >= 0) && (value <= 127))
2270 else if ((value >= 0) && (value <= 16383)) {
2271 p [0] = 0x80 | (value >> 8);
2272 p [1] = value & 0xff;
2274 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2275 p [0] = (value >> 24) | 0xc0;
2276 p [1] = (value >> 16) & 0xff;
2277 p [2] = (value >> 8) & 0xff;
2278 p [3] = value & 0xff;
2283 p [1] = (value >> 24) & 0xff;
2284 p [2] = (value >> 16) & 0xff;
2285 p [3] = (value >> 8) & 0xff;
2286 p [4] = value & 0xff;
2294 stream_init (MonoDynamicStream *sh)
2297 sh->alloc_size = 4096;
2298 sh->data = (char *)g_malloc (4096);
2300 /* So offsets are > 0 */
2306 make_room_in_stream (MonoDynamicStream *stream, int size)
2308 if (size <= stream->alloc_size)
2311 while (stream->alloc_size <= size) {
2312 if (stream->alloc_size < 4096)
2313 stream->alloc_size = 4096;
2315 stream->alloc_size *= 2;
2318 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2322 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2326 make_room_in_stream (stream, stream->index + len);
2327 memcpy (stream->data + stream->index, data, len);
2328 idx = stream->index;
2329 stream->index += len;
2336 * Add data to the binary blob inside the aot image. Returns the offset inside the
2337 * blob where the data was stored.
2340 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2342 g_assert (!acfg->blob_closed);
2344 if (acfg->blob.alloc_size == 0)
2345 stream_init (&acfg->blob);
2347 return add_stream_data (&acfg->blob, (char*)data, data_len);
2351 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2356 if (acfg->blob.alloc_size == 0)
2357 stream_init (&acfg->blob);
2359 count = acfg->blob.index % align;
2361 /* we assume the stream data will be aligned */
2363 add_stream_data (&acfg->blob, buf, 4 - count);
2365 return add_stream_data (&acfg->blob, (char*)data, data_len);
2368 /* Emit a table of data into the aot image */
2370 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2372 if (acfg->data_outfile) {
2373 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2374 fwrite (data,1, size, acfg->data_outfile);
2375 acfg->datafile_offset += size;
2376 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2377 int align = 8 - size % 8;
2378 acfg->datafile_offset += align;
2379 guint8 align_buf [16];
2380 memset (&align_buf, 0, sizeof (align_buf));
2381 fwrite (align_buf, align, 1, acfg->data_outfile);
2382 } else if (acfg->llvm) {
2383 mono_llvm_emit_aot_data (symbol, data, size);
2385 emit_section_change (acfg, RODATA_SECT, 0);
2386 emit_alignment (acfg, 8);
2387 emit_label (acfg, symbol);
2388 emit_bytes (acfg, data, size);
2393 * emit_offset_table:
2395 * Emit a table of increasing offsets in a compact form using differential encoding.
2396 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2397 * group size, the more compact the table becomes, but the slower it becomes to compute
2398 * a given entry. Returns the size of the table.
2401 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2403 gint32 current_offset;
2404 int i, buf_size, ngroups, index_entry_size;
2406 guint8 *data_p, *data_buf;
2407 guint32 *index_offsets;
2409 ngroups = (noffsets + (group_size - 1)) / group_size;
2411 index_offsets = g_new0 (guint32, ngroups);
2413 buf_size = noffsets * 4;
2414 p = buf = (guint8 *)g_malloc0 (buf_size);
2417 for (i = 0; i < noffsets; ++i) {
2418 //printf ("D: %d -> %d\n", i, offsets [i]);
2419 if ((i % group_size) == 0) {
2420 index_offsets [i / group_size] = p - buf;
2421 /* Emit the full value for these entries */
2422 encode_value (offsets [i], p, &p);
2424 /* The offsets are allowed to be non-increasing */
2425 //g_assert (offsets [i] >= current_offset);
2426 encode_value (offsets [i] - current_offset, p, &p);
2428 current_offset = offsets [i];
2433 if (ngroups && index_offsets [ngroups - 1] < 65000)
2434 index_entry_size = 2;
2436 index_entry_size = 4;
2438 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2439 p = buf = (guint8 *)g_malloc0 (buf_size);
2441 /* Emit the header */
2442 encode_int (noffsets, p, &p);
2443 encode_int (group_size, p, &p);
2444 encode_int (ngroups, p, &p);
2445 encode_int (index_entry_size, p, &p);
2447 /* Emit the index */
2448 for (i = 0; i < ngroups; ++i) {
2449 if (index_entry_size == 2)
2450 encode_int16 (index_offsets [i], p, &p);
2452 encode_int (index_offsets [i], p, &p);
2455 memcpy (p, data_buf, data_p - data_buf);
2456 p += data_p - data_buf;
2458 g_assert (p - buf <= buf_size);
2460 emit_aot_data (acfg, table, symbol, buf, p - buf);
2465 return (int)(p - buf);
2469 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2473 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2477 index = g_hash_table_size (cfg->image_hash);
2478 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2479 g_ptr_array_add (cfg->image_table, image);
2485 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2488 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2490 /* FIXME: Search referenced images as well */
2491 if (!acfg->typespec_classes) {
2492 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2493 for (i = 0; i < len; ++i) {
2495 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2496 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2499 for (i = 0; i < len; ++i) {
2500 if (acfg->typespec_classes [i] == klass)
2505 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2511 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2514 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2517 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2520 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2523 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2528 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2532 if (klass->generic_class) {
2534 g_assert (klass->type_token);
2536 /* Find a typespec for a class if possible */
2537 token = find_typespec_for_class (acfg, klass);
2539 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2540 encode_value (token, p, &p);
2542 MonoClass *gclass = klass->generic_class->container_class;
2543 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2544 static int count = 0;
2547 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2548 encode_klass_ref (acfg, gclass, p, &p);
2549 encode_ginst (acfg, inst, p, &p);
2553 } else if (klass->type_token) {
2554 int iindex = get_image_index (acfg, klass->image);
2556 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2558 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2559 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2561 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2562 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2563 encode_value (get_image_index (acfg, klass->image), p, &p);
2565 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2566 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2567 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2569 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2571 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2572 if (par->gshared_constraint) {
2573 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2574 encode_type (acfg, par->gshared_constraint, p, &p);
2575 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2577 encode_value (klass->byval_arg.type, p, &p);
2578 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2580 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2582 if (!container->is_anonymous) {
2583 encode_value (container->is_method, p, &p);
2584 if (container->is_method)
2585 encode_method_ref (acfg, container->owner.method, p, &p);
2587 encode_klass_ref (acfg, container->owner.klass, p, &p);
2590 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2591 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2592 encode_type (acfg, &klass->byval_arg, p, &p);
2595 g_assert (klass->rank > 0);
2596 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2597 encode_value (klass->rank, p, &p);
2598 encode_klass_ref (acfg, klass->element_class, p, &p);
2606 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2607 * standard metadata encoding.
2610 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2612 gboolean shared = FALSE;
2615 * The encoding of generic instances is large so emit them only once.
2617 if (klass->generic_class) {
2619 g_assert (klass->type_token);
2621 /* Find a typespec for a class if possible */
2622 token = find_typespec_for_class (acfg, klass);
2625 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2630 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2634 buf2 = (guint8 *)g_malloc (1024);
2637 encode_klass_ref_inner (acfg, klass, p, &p);
2638 g_assert (p - buf2 < 1024);
2640 offset = add_to_blob (acfg, buf2, p - buf2);
2643 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2649 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2650 encode_value (offset, p, &p);
2655 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2659 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2661 guint32 token = mono_get_field_token (field);
2664 encode_klass_ref (cfg, field->parent, p, &p);
2665 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2666 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2671 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2676 encode_value (inst->type_argc, p, &p);
2677 for (i = 0; i < inst->type_argc; ++i)
2678 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2683 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2686 MonoGenericInst *inst;
2688 inst = context->class_inst;
2690 g_assert (inst->type_argc);
2691 encode_ginst (acfg, inst, p, &p);
2693 encode_value (0, p, &p);
2695 inst = context->method_inst;
2697 g_assert (inst->type_argc);
2698 encode_ginst (acfg, inst, p, &p);
2700 encode_value (0, p, &p);
2706 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2710 g_assert (t->num_mods == 0);
2711 /* t->attrs can be ignored */
2712 //g_assert (t->attrs == 0);
2715 *p = MONO_TYPE_PINNED;
2719 *p = MONO_TYPE_BYREF;
2727 case MONO_TYPE_VOID:
2728 case MONO_TYPE_BOOLEAN:
2729 case MONO_TYPE_CHAR:
2742 case MONO_TYPE_STRING:
2743 case MONO_TYPE_OBJECT:
2744 case MONO_TYPE_TYPEDBYREF:
2746 case MONO_TYPE_VALUETYPE:
2747 case MONO_TYPE_CLASS:
2748 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2750 case MONO_TYPE_SZARRAY:
2751 encode_klass_ref (acfg, t->data.klass, p, &p);
2754 encode_type (acfg, t->data.type, p, &p);
2756 case MONO_TYPE_GENERICINST: {
2757 MonoClass *gclass = t->data.generic_class->container_class;
2758 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2760 encode_klass_ref (acfg, gclass, p, &p);
2761 encode_ginst (acfg, inst, p, &p);
2764 case MONO_TYPE_ARRAY: {
2765 MonoArrayType *array = t->data.array;
2768 encode_klass_ref (acfg, array->eklass, p, &p);
2769 encode_value (array->rank, p, &p);
2770 encode_value (array->numsizes, p, &p);
2771 for (i = 0; i < array->numsizes; ++i)
2772 encode_value (array->sizes [i], p, &p);
2773 encode_value (array->numlobounds, p, &p);
2774 for (i = 0; i < array->numlobounds; ++i)
2775 encode_value (array->lobounds [i], p, &p);
2779 case MONO_TYPE_MVAR:
2780 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2783 g_assert_not_reached ();
2790 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2796 /* Similar to the metadata encoding */
2797 if (sig->generic_param_count)
2801 if (sig->explicit_this)
2803 flags |= (sig->call_convention & 0x0F);
2807 if (sig->generic_param_count)
2808 encode_value (sig->generic_param_count, p, &p);
2809 encode_value (sig->param_count, p, &p);
2811 encode_type (acfg, sig->ret, p, &p);
2812 for (i = 0; i < sig->param_count; ++i) {
2813 if (sig->sentinelpos == i) {
2814 *p = MONO_TYPE_SENTINEL;
2817 encode_type (acfg, sig->params [i], p, &p);
2823 #define MAX_IMAGE_INDEX 250
2826 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2828 guint32 image_index = get_image_index (acfg, method->klass->image);
2829 guint32 token = method->token;
2830 MonoJumpInfoToken *ji;
2834 * The encoding for most methods is as follows:
2835 * - image index encoded as a leb128
2836 * - token index encoded as a leb128
2837 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2838 * types of method encodings.
2841 /* Mark methods which can't use aot trampolines because they need the further
2842 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2844 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2845 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2846 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2848 if (method->wrapper_type) {
2849 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2851 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2853 encode_value (method->wrapper_type, p, &p);
2855 switch (method->wrapper_type) {
2856 case MONO_WRAPPER_REMOTING_INVOKE:
2857 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2858 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2861 m = mono_marshal_method_from_wrapper (method);
2863 encode_method_ref (acfg, m, p, &p);
2866 case MONO_WRAPPER_PROXY_ISINST:
2867 case MONO_WRAPPER_LDFLD:
2868 case MONO_WRAPPER_LDFLDA:
2869 case MONO_WRAPPER_STFLD:
2870 case MONO_WRAPPER_ISINST: {
2872 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2875 case MONO_WRAPPER_LDFLD_REMOTE:
2876 case MONO_WRAPPER_STFLD_REMOTE:
2878 case MONO_WRAPPER_ALLOC: {
2879 /* The GC name is saved once in MonoAotFileInfo */
2880 g_assert (info->d.alloc.alloc_type != -1);
2881 encode_value (info->d.alloc.alloc_type, p, &p);
2884 case MONO_WRAPPER_WRITE_BARRIER: {
2888 case MONO_WRAPPER_STELEMREF: {
2890 encode_value (info->subtype, p, &p);
2891 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2892 encode_value (info->d.virtual_stelemref.kind, p, &p);
2895 case MONO_WRAPPER_UNKNOWN: {
2897 encode_value (info->subtype, p, &p);
2898 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2899 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2900 encode_klass_ref (acfg, method->klass, p, &p);
2901 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2902 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2903 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2904 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2905 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2906 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2907 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2908 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2911 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2913 encode_value (info->subtype, p, &p);
2914 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2915 strcpy ((char*)p, method->name);
2916 p += strlen (method->name) + 1;
2917 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2918 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2920 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2921 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2925 case MONO_WRAPPER_SYNCHRONIZED: {
2928 m = mono_marshal_method_from_wrapper (method);
2930 g_assert (m != method);
2931 encode_method_ref (acfg, m, p, &p);
2934 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2936 encode_value (info->subtype, p, &p);
2938 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2939 encode_value (info->d.element_addr.rank, p, &p);
2940 encode_value (info->d.element_addr.elem_size, p, &p);
2941 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2942 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2944 g_assert_not_reached ();
2948 case MONO_WRAPPER_CASTCLASS: {
2950 encode_value (info->subtype, p, &p);
2953 case MONO_WRAPPER_RUNTIME_INVOKE: {
2955 encode_value (info->subtype, p, &p);
2956 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2957 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2958 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2959 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2962 case MONO_WRAPPER_DELEGATE_INVOKE:
2963 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2964 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2965 if (method->is_inflated) {
2966 /* These wrappers are identified by their class */
2967 encode_value (1, p, &p);
2968 encode_klass_ref (acfg, method->klass, p, &p);
2970 MonoMethodSignature *sig = mono_method_signature (method);
2971 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2973 encode_value (0, p, &p);
2974 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2975 encode_value (info ? info->subtype : 0, p, &p);
2976 encode_signature (acfg, sig, p, &p);
2980 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2982 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2983 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2987 g_assert_not_reached ();
2989 } else if (mono_method_signature (method)->is_inflated) {
2991 * This is a generic method, find the original token which referenced it and
2993 * Obtain the token from information recorded by the JIT.
2995 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2997 image_index = get_image_index (acfg, ji->image);
2998 g_assert (image_index < MAX_IMAGE_INDEX);
3001 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3002 encode_value (image_index, p, &p);
3003 encode_value (token, p, &p);
3005 MonoMethod *declaring;
3006 MonoGenericContext *context = mono_method_get_context (method);
3008 g_assert (method->is_inflated);
3009 declaring = ((MonoMethodInflated*)method)->declaring;
3012 * This might be a non-generic method of a generic instance, which
3013 * doesn't have a token since the reference is generated by the JIT
3014 * like Nullable:Box/Unbox, or by generic sharing.
3016 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3017 /* Encode the klass */
3018 encode_klass_ref (acfg, method->klass, p, &p);
3019 /* Encode the method */
3020 image_index = get_image_index (acfg, method->klass->image);
3021 g_assert (image_index < MAX_IMAGE_INDEX);
3022 g_assert (declaring->token);
3023 token = declaring->token;
3024 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3025 encode_value (image_index, p, &p);
3026 encode_value (token, p, &p);
3027 encode_generic_context (acfg, context, p, &p);
3029 } else if (token == 0) {
3030 /* This might be a method of a constructed type like int[,].Set */
3031 /* Obtain the token from information recorded by the JIT */
3032 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3034 image_index = get_image_index (acfg, ji->image);
3035 g_assert (image_index < MAX_IMAGE_INDEX);
3038 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3039 encode_value (image_index, p, &p);
3040 encode_value (token, p, &p);
3043 g_assert (method->klass->rank);
3045 /* Encode directly */
3046 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3047 encode_klass_ref (acfg, method->klass, p, &p);
3048 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3049 encode_value (0, p, &p);
3050 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3051 encode_value (1, p, &p);
3052 else if (!strcmp (method->name, "Get"))
3053 encode_value (2, p, &p);
3054 else if (!strcmp (method->name, "Address"))
3055 encode_value (3, p, &p);
3056 else if (!strcmp (method->name, "Set"))
3057 encode_value (4, p, &p);
3059 g_assert_not_reached ();
3062 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3064 if (image_index >= MONO_AOT_METHODREF_MIN) {
3065 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3066 encode_value (image_index, p, &p);
3067 encode_value (mono_metadata_token_index (token), p, &p);
3069 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3076 compare_patches (gconstpointer a, gconstpointer b)
3080 i = (*(MonoJumpInfo**)a)->ip.i;
3081 j = (*(MonoJumpInfo**)b)->ip.i;
3092 static G_GNUC_UNUSED char*
3093 patch_to_string (MonoJumpInfo *patch_info)
3097 str = g_string_new ("");
3099 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3101 switch (patch_info->type) {
3102 case MONO_PATCH_INFO_VTABLE:
3103 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3108 g_string_append_printf (str, ")");
3109 return g_string_free (str, FALSE);
3115 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3118 static inline gboolean
3119 is_plt_patch (MonoJumpInfo *patch_info)
3121 switch (patch_info->type) {
3122 case MONO_PATCH_INFO_METHOD:
3123 case MONO_PATCH_INFO_INTERNAL_METHOD:
3124 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3125 case MONO_PATCH_INFO_ICALL_ADDR:
3126 case MONO_PATCH_INFO_RGCTX_FETCH:
3136 * Return the symbol identifying the plt entry PLT_OFFSET.
3139 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3143 * The Apple linker reorganizes object files, so it doesn't like branches to local
3144 * labels, since those have no relocations.
3146 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3148 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3155 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3157 static MonoPltEntry*
3158 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3161 gboolean synchronized = FALSE;
3162 static int synchronized_symbol_idx;
3164 if (!is_plt_patch (patch_info))
3167 if (!acfg->patch_to_plt_entry [patch_info->type])
3168 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3169 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3171 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3173 * Allocate a separate PLT slot for each such patch, since some plt
3174 * entries will refer to the method itself, and some will refer to the
3178 synchronized = TRUE;
3182 MonoJumpInfo *new_ji;
3184 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3186 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3187 res->plt_offset = acfg->plt_offset;
3189 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3190 if (acfg->aot_opts.write_symbols)
3191 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3193 /* Avoid duplicate symbols because we don't cache */
3194 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3196 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3197 synchronized_symbol_idx ++;
3200 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3202 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3204 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3206 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3208 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3209 //mono_print_ji (patch_info); printf ("\n");
3210 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3212 acfg->plt_offset ++;
3221 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3222 * JI could be found if it exists, otherwise allocates a new one.
3225 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3228 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3230 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3232 return got_offset - 1;
3235 got_offset = acfg->llvm_got_offset;
3236 acfg->llvm_got_offset ++;
3238 got_offset = acfg->got_offset;
3239 acfg->got_offset ++;
3242 acfg->stats.got_slots ++;
3243 acfg->stats.got_slot_types [ji->type] ++;
3245 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3246 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3247 g_ptr_array_add (info->got_patches, ji);
3252 /* Add a method to the list of methods which need to be emitted */
3254 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3257 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3258 g_ptr_array_add (acfg->methods, method);
3259 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3260 acfg->nmethods = acfg->methods->len + 1;
3263 if (method->wrapper_type || extra)
3264 g_ptr_array_add (acfg->extra_methods, method);
3268 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3270 /* One instantiation with valuetypes is generated for each async method */
3271 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3278 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3280 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3288 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3292 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3296 index = acfg->method_index;
3297 add_method_with_index (acfg, method, index, extra);
3299 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3301 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3303 acfg->method_index ++;
3309 add_method (MonoAotCompile *acfg, MonoMethod *method)
3311 return add_method_full (acfg, method, FALSE, 0);
3315 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3317 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3318 method = mini_get_shared_method (method);
3319 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3320 /* Use the gsharedvt version */
3321 method = mini_get_shared_method_full (method, TRUE, TRUE);
3323 if (acfg->aot_opts.log_generics)
3324 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3326 add_method_full (acfg, method, TRUE, depth);
3330 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3332 add_extra_method_with_depth (acfg, method, 0);
3336 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3338 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3339 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3340 MonoMethod *wrapper;
3346 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3347 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3350 add_method (acfg, wrapper);
3354 get_runtime_invoke_sig (MonoMethodSignature *sig)
3356 MonoMethodBuilder *mb;
3359 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3360 m = mono_mb_create_method (mb, sig, 16);
3361 return mono_marshal_get_runtime_invoke (m, FALSE);
3365 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3367 return mono_marshal_get_runtime_invoke (method, virtual_);
3371 can_marshal_struct (MonoClass *klass)
3373 MonoClassField *field;
3374 gboolean can_marshal = TRUE;
3375 gpointer iter = NULL;
3376 MonoMarshalType *info;
3379 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3382 info = mono_marshal_load_type_info (klass);
3384 /* Only allow a few field types to avoid asserts in the marshalling code */
3385 while ((field = mono_class_get_fields (klass, &iter))) {
3386 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3389 switch (field->type->type) {
3394 case MONO_TYPE_BOOLEAN:
3397 case MONO_TYPE_CHAR:
3405 case MONO_TYPE_STRING:
3407 case MONO_TYPE_VALUETYPE:
3408 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3409 can_marshal = FALSE;
3411 case MONO_TYPE_SZARRAY: {
3412 gboolean has_mspec = FALSE;
3415 for (i = 0; i < info->num_fields; ++i) {
3416 if (info->fields [i].field == field && info->fields [i].mspec)
3421 can_marshal = FALSE;
3425 can_marshal = FALSE;
3431 /* Its hard to compute whenever these can be marshalled or not */
3432 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3439 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3441 /* Create a vtype instantiation */
3442 MonoGenericContext shared_context;
3444 MonoGenericInst *inst;
3445 MonoGenericContainer *container;
3446 MonoClass **constraints;
3449 memset (ctx, 0, sizeof (MonoGenericContext));
3451 if (method->klass->generic_container) {
3452 shared_context = method->klass->generic_container->context;
3453 inst = shared_context.class_inst;
3455 args = g_new0 (MonoType*, inst->type_argc);
3456 for (i = 0; i < inst->type_argc; ++i) {
3457 args [i] = &mono_defaults.int_class->byval_arg;
3459 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3461 if (method->is_generic) {
3462 container = mono_method_get_generic_container (method);
3463 shared_context = container->context;
3464 inst = shared_context.method_inst;
3466 args = g_new0 (MonoType*, inst->type_argc);
3467 for (i = 0; i < container->type_argc; ++i) {
3468 MonoGenericParamInfo *info = &container->type_params [i].info;
3469 gboolean ref_only = FALSE;
3471 if (info && info->constraints) {
3472 constraints = info->constraints;
3474 while (*constraints) {
3475 MonoClass *cklass = *constraints;
3476 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3477 /* Inflaring the method with our vtype would not be valid */
3484 args [i] = &mono_defaults.object_class->byval_arg;
3486 args [i] = &mono_defaults.int_class->byval_arg;
3488 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3493 add_wrappers (MonoAotCompile *acfg)
3495 MonoMethod *method, *m;
3497 MonoMethodSignature *sig, *csig;
3501 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3502 * so there is only one wrapper of a given type, or inlining their contents into their
3505 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3508 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3509 gboolean skip = FALSE;
3511 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3512 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3514 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3515 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3516 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3519 /* Skip methods which can not be handled by get_runtime_invoke () */
3520 sig = mono_method_signature (method);
3523 if ((sig->ret->type == MONO_TYPE_PTR) ||
3524 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3526 if (mono_class_is_open_constructed_type (sig->ret))
3529 for (j = 0; j < sig->param_count; j++) {
3530 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3532 if (mono_class_is_open_constructed_type (sig->params [j]))
3536 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3537 if (!mono_class_is_contextbound (method->klass)) {
3538 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3539 gboolean has_nullable = FALSE;
3541 for (j = 0; j < sig->param_count; j++) {
3542 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3543 has_nullable = TRUE;
3546 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3547 /* Supported by the dynamic runtime-invoke wrapper */
3551 mono_arch_dyn_call_free (info);
3555 if (acfg->aot_opts.llvm_only)
3556 /* Supported by the gsharedvt based runtime-invoke wrapper */
3560 //printf ("%s\n", mono_method_full_name (method, TRUE));
3561 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3565 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3568 /* Runtime invoke wrappers */
3570 /* void runtime-invoke () [.cctor] */
3571 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3572 csig->ret = &mono_defaults.void_class->byval_arg;
3573 add_method (acfg, get_runtime_invoke_sig (csig));
3575 /* void runtime-invoke () [Finalize] */
3576 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3578 csig->ret = &mono_defaults.void_class->byval_arg;
3579 add_method (acfg, get_runtime_invoke_sig (csig));
3581 /* void runtime-invoke (string) [exception ctor] */
3582 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3584 csig->ret = &mono_defaults.void_class->byval_arg;
3585 csig->params [0] = &mono_defaults.string_class->byval_arg;
3586 add_method (acfg, get_runtime_invoke_sig (csig));
3588 /* void runtime-invoke (string, string) [exception ctor] */
3589 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3591 csig->ret = &mono_defaults.void_class->byval_arg;
3592 csig->params [0] = &mono_defaults.string_class->byval_arg;
3593 csig->params [1] = &mono_defaults.string_class->byval_arg;
3594 add_method (acfg, get_runtime_invoke_sig (csig));
3596 /* string runtime-invoke () [Exception.ToString ()] */
3597 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3599 csig->ret = &mono_defaults.string_class->byval_arg;
3600 add_method (acfg, get_runtime_invoke_sig (csig));
3602 /* void runtime-invoke (string, Exception) [exception ctor] */
3603 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3605 csig->ret = &mono_defaults.void_class->byval_arg;
3606 csig->params [0] = &mono_defaults.string_class->byval_arg;
3607 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3608 add_method (acfg, get_runtime_invoke_sig (csig));
3610 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3611 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3613 csig->ret = &(mono_class_load_from_name (
3614 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3615 csig->params [0] = &mono_defaults.string_class->byval_arg;
3616 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3617 add_method (acfg, get_runtime_invoke_sig (csig));
3619 /* runtime-invoke used by finalizers */
3620 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3622 /* This is used by mono_runtime_capture_context () */
3623 method = mono_get_context_capture_method ();
3625 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3627 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3628 if (!acfg->aot_opts.llvm_only)
3629 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3632 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3633 if (acfg->aot_opts.llvm_only) {
3636 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3637 for (variants = 0; variants < 4; ++variants) {
3638 for (i = 0; i < 16; ++i) {
3639 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3640 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3648 add_method (acfg, mono_marshal_get_stelemref ());
3650 if (MONO_ARCH_HAVE_TLS_GET) {
3651 /* Managed Allocators */
3652 nallocators = mono_gc_get_managed_allocator_types ();
3653 for (i = 0; i < nallocators; ++i) {
3654 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3656 add_method (acfg, m);
3658 for (i = 0; i < nallocators; ++i) {
3659 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3661 add_method (acfg, m);
3665 /* write barriers */
3666 if (mono_gc_is_moving ()) {
3667 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3668 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3671 /* Stelemref wrappers */
3673 MonoMethod **wrappers;
3676 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3677 for (i = 0; i < nwrappers; ++i)
3678 add_method (acfg, wrappers [i]);
3682 /* castclass_with_check wrapper */
3683 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3684 /* isinst_with_check wrapper */
3685 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3687 /* JIT icall wrappers */
3688 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3689 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3693 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3694 * we use the original method instead at runtime.
3695 * Since full-aot doesn't support remoting, this is not a problem.
3698 /* remoting-invoke wrappers */
3699 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3701 MonoMethodSignature *sig;
3703 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3704 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3705 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3707 sig = mono_method_signature (method);
3709 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3710 m = mono_marshal_get_remoting_invoke_with_check (method);
3712 add_method (acfg, m);
3717 /* delegate-invoke wrappers */
3718 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3721 MonoCustomAttrInfo *cattr;
3723 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3724 klass = mono_class_get_checked (acfg->image, token, &error);
3727 mono_error_cleanup (&error);
3731 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3734 if (!klass->generic_container) {
3735 method = mono_get_delegate_invoke (klass);
3737 m = mono_marshal_get_delegate_invoke (method, NULL);
3739 add_method (acfg, m);
3741 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3743 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3745 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3747 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3749 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3750 if (!is_ok (&error)) {
3751 mono_error_cleanup (&error);
3758 for (j = 0; j < cattr->num_attrs; ++j)
3759 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3761 if (j < cattr->num_attrs) {
3763 MonoMethod *wrapper;
3764 MonoMethod *del_invoke;
3766 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3767 invoke = mono_get_delegate_invoke (klass);
3768 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3769 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3770 add_method (acfg, wrapper);
3771 add_method (acfg, del_invoke);
3774 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3776 MonoGenericContext ctx;
3777 MonoMethod *inst, *gshared;
3780 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3783 method = mono_get_delegate_invoke (klass);
3784 create_gsharedvt_inst (acfg, method, &ctx);
3786 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3787 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3789 m = mono_marshal_get_delegate_invoke (inst, NULL);
3790 g_assert (m->is_inflated);
3792 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3793 add_extra_method (acfg, gshared);
3796 method = mono_get_delegate_begin_invoke (klass);
3797 create_gsharedvt_inst (acfg, method, &ctx);
3799 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3800 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3802 m = mono_marshal_get_delegate_begin_invoke (inst);
3803 g_assert (m->is_inflated);
3805 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3806 add_extra_method (acfg, gshared);
3809 method = mono_get_delegate_end_invoke (klass);
3810 create_gsharedvt_inst (acfg, method, &ctx);
3812 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3813 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3815 m = mono_marshal_get_delegate_end_invoke (inst);
3816 g_assert (m->is_inflated);
3818 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3819 add_extra_method (acfg, gshared);
3824 /* array access wrappers */
3825 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3829 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3830 klass = mono_class_get_checked (acfg->image, token, &error);
3833 mono_error_cleanup (&error);
3837 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3838 MonoMethod *m, *wrapper;
3840 /* Add runtime-invoke wrappers too */
3842 m = mono_class_get_method_from_name (klass, "Get", -1);
3844 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3845 add_extra_method (acfg, wrapper);
3846 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3848 m = mono_class_get_method_from_name (klass, "Set", -1);
3850 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3851 add_extra_method (acfg, wrapper);
3852 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3856 /* Synchronized wrappers */
3857 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3859 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3860 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3861 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3863 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3864 if (method->is_generic) {
3866 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3868 MonoGenericContext ctx;
3869 MonoMethod *inst, *gshared, *m;
3872 * Create a generic wrapper for a generic instance, and AOT that.
3874 create_gsharedvt_inst (acfg, method, &ctx);
3875 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3876 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3877 m = mono_marshal_get_synchronized_wrapper (inst);
3878 g_assert (m->is_inflated);
3879 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3880 add_method (acfg, gshared);
3882 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3887 /* pinvoke wrappers */
3888 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3891 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3893 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3894 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3896 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3897 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3898 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3902 /* native-to-managed wrappers */
3903 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3906 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3907 MonoCustomAttrInfo *cattr;
3910 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3911 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3914 * Only generate native-to-managed wrappers for methods which have an
3915 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3916 * name to avoid defining a new assembly to contain it.
3918 cattr = mono_custom_attrs_from_method_checked (method, &error);
3919 if (!is_ok (&error)) {
3920 char *name = mono_method_get_full_name (method);
3921 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
3926 for (j = 0; j < cattr->num_attrs; ++j)
3927 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3929 if (j < cattr->num_attrs) {
3930 MonoCustomAttrEntry *e = &cattr->attrs [j];
3931 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3932 const char *p = (const char*)e->data;
3934 int slen, num_named, named_type;
3938 char *export_name = NULL;
3939 MonoMethod *wrapper;
3941 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3942 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3943 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3944 mono_method_full_name (method, TRUE));
3948 g_assert (sig->param_count == 1);
3949 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3952 * Decode the cattr manually since we can't create objects
3953 * during aot compilation.
3959 /* From load_cattr_value () in reflection.c */
3960 slen = mono_metadata_decode_value (p, &p);
3961 n = (char *)g_memdup (p, slen + 1);
3963 t = mono_reflection_type_from_name (n, acfg->image);
3967 klass = mono_class_from_mono_type (t);
3968 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3972 num_named = read16 (p);
3975 g_assert (num_named < 2);
3976 if (num_named == 1) {
3980 /* parse ExportSymbol attribute */
3982 named_type = *named;
3984 /* data_type = *named; */
3987 name_len = mono_metadata_decode_blob_size (named, &named);
3988 name = (char *)g_malloc (name_len + 1);
3989 memcpy (name, named, name_len);
3990 name [name_len] = 0;
3993 g_assert (named_type == 0x54);
3994 g_assert (!strcmp (name, "ExportSymbol"));
3996 /* load_cattr_value (), string case */
3997 g_assert (*named != (char)0xff);
3998 slen = mono_metadata_decode_value (named, &named);
3999 export_name = (char *)g_malloc (slen + 1);
4000 memcpy (export_name, named, slen);
4001 export_name [slen] = 0;
4005 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4006 add_method (acfg, wrapper);
4008 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4012 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4013 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4014 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4018 /* StructureToPtr/PtrToStructure wrappers */
4019 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4023 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4024 klass = mono_class_get_checked (acfg->image, token, &error);
4027 mono_error_cleanup (&error);
4031 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4032 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4033 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4034 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4040 has_type_vars (MonoClass *klass)
4042 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4045 return has_type_vars (klass->element_class);
4046 if (klass->generic_class) {
4047 MonoGenericContext *context = &klass->generic_class->context;
4048 if (context->class_inst) {
4051 for (i = 0; i < context->class_inst->type_argc; ++i)
4052 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4056 if (klass->generic_container)
4062 is_vt_inst (MonoGenericInst *inst)
4066 for (i = 0; i < inst->type_argc; ++i) {
4067 MonoType *t = inst->type_argv [i];
4068 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4075 method_has_type_vars (MonoMethod *method)
4077 if (has_type_vars (method->klass))
4080 if (method->is_inflated) {
4081 MonoGenericContext *context = mono_method_get_context (method);
4082 if (context->method_inst) {
4085 for (i = 0; i < context->method_inst->type_argc; ++i)
4086 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4094 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4096 return opts->mode == MONO_AOT_MODE_FULL;
4099 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4102 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4104 /* This might lead to a huge code blowup so only do it if neccesary */
4105 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4108 add_generic_class_with_depth (acfg, klass, 0, ref);
4112 check_type_depth (MonoType *t, int depth)
4120 case MONO_TYPE_GENERICINST: {
4121 MonoGenericClass *gklass = t->data.generic_class;
4122 MonoGenericInst *ginst = gklass->context.class_inst;
4125 for (i = 0; i < ginst->type_argc; ++i) {
4126 if (check_type_depth (ginst->type_argv [i], depth + 1))
4140 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4143 * add_generic_class:
4145 * Add all methods of a generic class.
4148 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4151 MonoClassField *field;
4153 gboolean use_gsharedvt = FALSE;
4155 if (!acfg->ginst_hash)
4156 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4158 mono_class_init (klass);
4160 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4163 if (has_type_vars (klass))
4166 if (!klass->generic_class && !klass->rank)
4169 if (mono_class_has_failure (klass))
4172 if (!acfg->ginst_hash)
4173 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4175 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4178 if (check_type_depth (&klass->byval_arg, 0))
4181 if (acfg->aot_opts.log_generics)
4182 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4184 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4187 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4188 * Enable this only for some classes since gsharedvt might not support all methods.
4190 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) &&
4191 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4192 use_gsharedvt = TRUE;
4195 while ((method = mono_class_get_methods (klass, &iter))) {
4196 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4198 * This is partial sharing, and we can't handle it yet
4203 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4205 add_types_from_method_header (acfg, method);
4209 if (method->is_generic)
4214 * FIXME: Instances which are referenced by these methods are not added,
4215 * for example Array.Resize<int> for List<int>.Add ().
4217 add_extra_method_with_depth (acfg, method, depth + 1);
4221 while ((field = mono_class_get_fields (klass, &iter))) {
4222 if (field->type->type == MONO_TYPE_GENERICINST)
4223 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4226 if (klass->delegate) {
4227 method = mono_get_delegate_invoke (klass);
4229 method = mono_marshal_get_delegate_invoke (method, NULL);
4231 if (acfg->aot_opts.log_generics)
4232 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4234 add_method (acfg, method);
4237 /* Add superclasses */
4239 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4242 * For ICollection<T>, add instances of the helper methods
4243 * in Array, since a T[] could be cast to ICollection<T>.
4245 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4246 (!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"))) {
4247 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4248 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4252 if (!strcmp (klass->name, "IEnumerator`1"))
4253 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4255 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4257 /* Add the T[]/InternalEnumerator class */
4258 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4263 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4264 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4268 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4269 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4270 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4274 while ((method = mono_class_get_methods (array_class, &iter))) {
4275 if (strstr (method->name, name_prefix)) {
4276 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4278 add_extra_method_with_depth (acfg, m, depth);
4282 g_free (name_prefix);
4285 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4286 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4288 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4289 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4290 MonoGenericContext ctx;
4291 MonoType *args [16];
4293 memset (&ctx, 0, sizeof (ctx));
4295 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4297 args [0] = &tclass->byval_arg;
4298 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4300 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4301 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4303 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4304 MonoClass *gcomparer_inst;
4305 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4306 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4307 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4309 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4313 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4314 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4316 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4317 MonoClass *iface, *gcomparer, *iface_inst;
4318 MonoGenericContext ctx;
4319 MonoType *args [16];
4321 memset (&ctx, 0, sizeof (ctx));
4323 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4325 args [0] = &tclass->byval_arg;
4326 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4328 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4329 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4331 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4332 MonoClass *gcomparer_inst;
4335 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4336 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4337 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4338 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4342 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4343 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4344 MonoClass *enum_comparer;
4345 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4346 MonoGenericContext ctx;
4347 MonoType *args [16];
4349 if (mono_class_is_enum (tclass)) {
4350 MonoClass *enum_comparer_inst;
4353 memset (&ctx, 0, sizeof (ctx));
4354 args [0] = &tclass->byval_arg;
4355 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4357 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4358 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4359 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4360 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4364 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4365 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4366 MonoClass *comparer;
4367 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4368 MonoGenericContext ctx;
4369 MonoType *args [16];
4371 if (mono_class_is_enum (tclass)) {
4372 MonoClass *comparer_inst;
4375 memset (&ctx, 0, sizeof (ctx));
4376 args [0] = &tclass->byval_arg;
4377 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4379 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4380 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4381 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4382 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4388 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4391 MonoGenericContext ctx;
4392 MonoType *args [16];
4394 if (acfg->aot_opts.no_instances)
4397 memset (&ctx, 0, sizeof (ctx));
4399 for (i = 0; i < ninsts; ++i) {
4401 MonoClass *generic_inst;
4402 args [0] = insts [i];
4403 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4404 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4405 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4406 add_generic_class (acfg, generic_inst, force, "");
4411 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4414 MonoMethodHeader *header;
4415 MonoMethodSignature *sig;
4418 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4420 sig = mono_method_signature (method);
4423 for (j = 0; j < sig->param_count; ++j)
4424 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4425 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4428 header = mono_method_get_header_checked (method, &error);
4431 for (j = 0; j < header->num_locals; ++j)
4432 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4433 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4435 mono_error_cleanup (&error); /* FIXME report the error */
4440 * add_generic_instances:
4442 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4445 add_generic_instances (MonoAotCompile *acfg)
4450 MonoGenericContext *context;
4452 if (acfg->aot_opts.no_instances)
4455 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4457 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4458 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4461 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4462 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4463 mono_error_cleanup (&error);
4467 if (method->klass->image != acfg->image)
4470 context = mono_method_get_context (method);
4472 if (context && ((context->class_inst && context->class_inst->is_open)))
4476 * For open methods, create an instantiation which can be passed to the JIT.
4477 * FIXME: Handle class_inst as well.
4479 if (context && context->method_inst && context->method_inst->is_open) {
4481 MonoGenericContext shared_context;
4482 MonoGenericInst *inst;
4483 MonoType **type_argv;
4485 MonoMethod *declaring_method;
4486 gboolean supported = TRUE;
4488 /* Check that the context doesn't contain open constructed types */
4489 if (context->class_inst) {
4490 inst = context->class_inst;
4491 for (i = 0; i < inst->type_argc; ++i) {
4492 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)
4494 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4498 if (context->method_inst) {
4499 inst = context->method_inst;
4500 for (i = 0; i < inst->type_argc; ++i) {
4501 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)
4503 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4511 memset (&shared_context, 0, sizeof (MonoGenericContext));
4513 inst = context->class_inst;
4515 type_argv = g_new0 (MonoType*, inst->type_argc);
4516 for (i = 0; i < inst->type_argc; ++i) {
4517 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)
4518 type_argv [i] = &mono_defaults.object_class->byval_arg;
4520 type_argv [i] = inst->type_argv [i];
4523 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4527 inst = context->method_inst;
4529 type_argv = g_new0 (MonoType*, inst->type_argc);
4530 for (i = 0; i < inst->type_argc; ++i) {
4531 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)
4532 type_argv [i] = &mono_defaults.object_class->byval_arg;
4534 type_argv [i] = inst->type_argv [i];
4537 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4541 if (method->is_generic || method->klass->generic_container)
4542 declaring_method = method;
4544 declaring_method = mono_method_get_declaring_generic_method (method);
4546 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4547 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4551 * If the method is fully sharable, it was already added in place of its
4552 * generic definition.
4554 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4558 * FIXME: Partially shared methods are not shared here, so we end up with
4559 * many identical methods.
4561 add_extra_method (acfg, method);
4564 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4568 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4570 klass = mono_class_get_checked (acfg->image, token, &error);
4571 if (!klass || klass->rank) {
4572 mono_error_cleanup (&error);
4576 add_generic_class (acfg, klass, FALSE, "typespec");
4579 /* Add types of args/locals */
4580 for (i = 0; i < acfg->methods->len; ++i) {
4581 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4582 add_types_from_method_header (acfg, method);
4585 if (acfg->image == mono_defaults.corlib) {
4587 MonoType *insts [256];
4590 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4591 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4592 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4593 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4594 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4595 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4596 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4597 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4598 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4599 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4600 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4601 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4603 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4604 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4606 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4607 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4609 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4611 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4613 MonoClass *enum_comparer;
4614 MonoType *insts [16];
4618 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4619 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4620 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4621 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4622 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4623 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4626 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4627 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4628 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4631 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4632 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4633 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4635 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4637 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4638 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4639 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4642 /* Add instances of the array generic interfaces for primitive types */
4643 /* This will add instances of the InternalArray_ helper methods in Array too */
4644 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4646 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4648 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4650 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4652 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4654 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4657 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4658 * used for all instances of GetGenericValueImpl by the AOT runtime.
4661 MonoGenericContext ctx;
4662 MonoType *args [16];
4663 MonoMethod *get_method;
4664 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4666 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4670 memset (&ctx, 0, sizeof (ctx));
4671 args [0] = &mono_defaults.object_class->byval_arg;
4672 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4673 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4674 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4678 /* Same for CompareExchange<T>/Exchange<T> */
4680 MonoGenericContext ctx;
4681 MonoType *args [16];
4683 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4684 gpointer iter = NULL;
4686 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4687 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4689 memset (&ctx, 0, sizeof (ctx));
4690 args [0] = &mono_defaults.object_class->byval_arg;
4691 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4692 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4693 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4698 /* Same for Volatile.Read/Write<T> */
4700 MonoGenericContext ctx;
4701 MonoType *args [16];
4703 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4704 gpointer iter = NULL;
4706 if (volatile_klass) {
4707 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4708 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4710 memset (&ctx, 0, sizeof (ctx));
4711 args [0] = &mono_defaults.object_class->byval_arg;
4712 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4713 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4714 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4720 /* object[] accessor wrappers. */
4722 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4725 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4728 m = mono_marshal_get_array_accessor_wrapper (m);
4729 add_extra_method (acfg, m);
4731 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4734 m = mono_marshal_get_array_accessor_wrapper (m);
4735 add_extra_method (acfg, m);
4737 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4740 m = mono_marshal_get_array_accessor_wrapper (m);
4741 add_extra_method (acfg, m);
4747 * is_direct_callable:
4749 * Return whenever the method identified by JI is directly callable without
4750 * going through the PLT.
4753 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4755 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4756 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4758 gboolean direct_callable = TRUE;
4760 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4761 direct_callable = FALSE;
4762 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4763 // FIXME: Maybe call the wrapper directly ?
4764 direct_callable = FALSE;
4766 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4767 /* Disable this so all calls go through load_method (), see the
4768 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4769 * mono_debugger_agent_init ().
4771 direct_callable = FALSE;
4774 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4775 /* sgen does some initialization when the allocator method is created */
4776 direct_callable = FALSE;
4777 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4778 /* we don't know at compile time whether sgen is concurrent or not */
4779 direct_callable = FALSE;
4781 if (direct_callable)
4784 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4785 if (acfg->aot_opts.direct_pinvoke)
4787 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4788 if (acfg->aot_opts.direct_icalls)
4796 #ifdef MONO_ARCH_AOT_SUPPORTED
4798 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4800 MonoImage *image = method->klass->image;
4801 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4802 MonoTableInfo *tables = image->tables;
4803 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4804 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4805 guint32 im_cols [MONO_IMPLMAP_SIZE];
4808 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4812 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4815 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4817 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4820 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4822 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4828 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4835 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4837 if (a->native_offset == b->native_offset)
4838 return a->il_offset - b->il_offset;
4840 return a->native_offset - b->native_offset;
4844 * compute_line_numbers:
4846 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4849 static MonoDebugSourceLocation**
4850 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4852 MonoDebugMethodInfo *minfo;
4853 MonoDebugLineNumberEntry *ln_array;
4854 MonoDebugSourceLocation *loc;
4855 int i, prev_line, prev_il_offset;
4856 int *native_to_il_offset = NULL;
4857 MonoDebugSourceLocation **res;
4860 minfo = mono_debug_lookup_method (method);
4863 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4864 if (debug_info->code_size != code_size)
4867 g_assert (code_size);
4869 /* Compute the native->IL offset mapping */
4871 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4872 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4874 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4876 native_to_il_offset = g_new0 (int, code_size + 1);
4878 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4880 MonoDebugLineNumberEntry *lne = &ln_array [i];
4883 for (j = 0; j < lne->native_offset; ++j)
4884 native_to_il_offset [j] = -1;
4887 if (i < debug_info->num_line_numbers - 1) {
4888 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4890 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4891 native_to_il_offset [j] = lne->il_offset;
4893 for (j = lne->native_offset; j < code_size; ++j)
4894 native_to_il_offset [j] = lne->il_offset;
4899 /* Compute the native->line number mapping */
4900 res = g_new0 (MonoDebugSourceLocation*, code_size);
4901 prev_il_offset = -1;
4904 for (i = 0; i < code_size; ++i) {
4905 int il_offset = native_to_il_offset [i];
4907 if (il_offset == -1 || il_offset == prev_il_offset)
4909 prev_il_offset = il_offset;
4910 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4911 if (!(loc && loc->source_file))
4913 if (loc->row == prev_line) {
4914 mono_debug_symfile_free_location (loc);
4917 prev_line = loc->row;
4918 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4920 /* This will cover the prolog too */
4930 get_file_index (MonoAotCompile *acfg, const char *source_file)
4934 // FIXME: Free these
4935 if (!acfg->dwarf_ln_filenames)
4936 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4937 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4939 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4940 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4941 emit_unset_mode (acfg);
4942 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4954 * emit_and_reloc_code:
4956 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4957 * is true, calls are made through the GOT too. This is used for emitting trampolines
4958 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4959 * since trampolines are needed to make PTL work.
4962 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4964 int i, pindex, start_index;
4966 MonoJumpInfo *patch_info;
4967 MonoDebugSourceLocation **locs = NULL;
4969 #ifdef MONO_ARCH_AOT_SUPPORTED
4970 gboolean direct_call, external_call;
4972 const char *direct_call_target = 0;
4973 const char *direct_pinvoke;
4976 if (acfg->gas_line_numbers && method && debug_info) {
4977 locs = compute_line_numbers (method, code_len, debug_info);
4979 int findex = get_file_index (acfg, "<unknown>");
4980 emit_unset_mode (acfg);
4981 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4985 /* Collect and sort relocations */
4986 patches = g_ptr_array_new ();
4987 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4988 g_ptr_array_add (patches, patch_info);
4989 g_ptr_array_sort (patches, compare_patches);
4992 for (i = 0; i < code_len; i += INST_LEN) {
4994 for (pindex = start_index; pindex < patches->len; ++pindex) {
4995 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4996 if (patch_info->ip.i >= i)
5000 if (locs && locs [i]) {
5001 MonoDebugSourceLocation *loc = locs [i];
5004 findex = get_file_index (acfg, loc->source_file);
5005 emit_unset_mode (acfg);
5006 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
5007 mono_debug_symfile_free_location (loc);
5011 #ifdef MONO_ARCH_AOT_SUPPORTED
5012 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5013 start_index = pindex;
5015 switch (patch_info->type) {
5016 case MONO_PATCH_INFO_NONE:
5018 case MONO_PATCH_INFO_GOT_OFFSET: {
5021 arch_emit_got_offset (acfg, code + i, &code_size);
5022 i += code_size - INST_LEN;
5024 patch_info->type = MONO_PATCH_INFO_NONE;
5027 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5028 int code_size, index;
5029 char *selector = (char *)patch_info->data.target;
5031 if (!acfg->objc_selector_to_index)
5032 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5033 if (!acfg->objc_selectors)
5034 acfg->objc_selectors = g_ptr_array_new ();
5035 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5039 index = acfg->objc_selector_index;
5040 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5041 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5042 acfg->objc_selector_index ++;
5045 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5046 i += code_size - INST_LEN;
5048 patch_info->type = MONO_PATCH_INFO_NONE;
5053 * If this patch is a call, try emitting a direct call instead of
5054 * through a PLT entry. This is possible if the called method is in
5055 * the same assembly and requires no initialization.
5057 direct_call = FALSE;
5058 external_call = FALSE;
5059 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5060 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5061 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5062 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5064 direct_call_target = callee_cfg->asm_symbol;
5065 patch_info->type = MONO_PATCH_INFO_NONE;
5066 acfg->stats.direct_calls ++;
5069 acfg->stats.all_calls ++;
5070 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
5071 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5072 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5073 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5075 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5076 if (direct_pinvoke) {
5078 g_assert (strlen (direct_pinvoke) < 1000);
5079 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5082 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5083 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5084 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5085 /* Call to a C function implementing a jit icall */
5087 external_call = TRUE;
5088 g_assert (strlen (sym) < 1000);
5089 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5091 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5092 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5093 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5094 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5095 /* Call to a jit icall without a wrapper */
5097 external_call = TRUE;
5098 g_assert (strlen (sym) < 1000);
5099 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5104 patch_info->type = MONO_PATCH_INFO_NONE;
5105 acfg->stats.direct_calls ++;
5108 if (!got_only && !direct_call) {
5109 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5111 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5113 direct_call_target = plt_entry->symbol;
5115 /* Nullify the patch */
5116 patch_info->type = MONO_PATCH_INFO_NONE;
5117 plt_entry->jit_used = TRUE;
5124 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5125 i += call_size - INST_LEN;
5129 got_slot = get_got_offset (acfg, FALSE, patch_info);
5131 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5132 i += code_size - INST_LEN;
5138 #endif /* MONO_ARCH_AOT_SUPPORTED */
5141 /* Find next patch */
5143 for (pindex = start_index; pindex < patches->len; ++pindex) {
5144 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5145 if (patch_info->ip.i >= i)
5149 /* Try to emit multiple bytes at once */
5150 if (pindex < patches->len && patch_info->ip.i > i) {
5153 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5154 if (locs && locs [limit])
5158 emit_code_bytes (acfg, code + i, limit - i);
5159 i = limit - INST_LEN;
5161 emit_code_bytes (acfg, code + i, INST_LEN);
5172 * Return a modified version of S which only includes characters permissible in symbols.
5175 sanitize_symbol (MonoAotCompile *acfg, char *s)
5177 gboolean process = FALSE;
5186 for (i = 0; i < len; ++i)
5187 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5192 gs = g_string_sized_new (len);
5193 for (i = 0; i < len; ++i) {
5195 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5196 g_string_append_c (gs, c);
5197 } else if (c > 0x7f) {
5198 /* multi-byte utf8 */
5199 g_string_append_printf (gs, "_0x%x", c);
5202 while (c >> 6 == 0x2) {
5203 g_string_append_printf (gs, "%x", c);
5207 g_string_append_printf (gs, "_");
5210 g_string_append_c (gs, '_');
5214 res = mono_mempool_strdup (acfg->mempool, gs->str);
5215 g_string_free (gs, TRUE);
5220 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5222 char *name1, *name2, *cached;
5223 int i, j, len, count;
5224 MonoMethod *cached_method;
5226 name1 = mono_method_full_name (method, TRUE);
5229 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5230 if ((!prefix || !*prefix) && name1 [0] == 'L')
5234 len = strlen (name1);
5235 name2 = (char *)malloc (strlen (prefix) + len + 16);
5236 memcpy (name2, prefix, strlen (prefix));
5237 j = strlen (prefix);
5238 for (i = 0; i < len; ++i) {
5239 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5241 } else if (isalnum (name1 [i])) {
5242 name2 [j ++] = name1 [i];
5243 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5245 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5248 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5258 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5259 if (!(cached_method && cached_method != method))
5261 sprintf (name2 + j, "_%d", count);
5265 cached = g_strdup (name2);
5266 g_hash_table_insert (cache, cached, method);
5272 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5277 char *debug_sym = NULL;
5278 char *symbol = NULL;
5279 int func_alignment = AOT_FUNC_ALIGNMENT;
5282 method = cfg->orig_method;
5283 code = cfg->native_code;
5285 method_index = get_method_index (acfg, method);
5286 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5288 /* Make the labels local */
5289 emit_section_change (acfg, ".text", 0);
5290 emit_alignment_code (acfg, func_alignment);
5292 if (acfg->global_symbols && acfg->need_no_dead_strip)
5293 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5295 emit_label (acfg, cfg->asm_symbol);
5297 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5299 * Write a C style symbol for every method, this has two uses:
5300 * - it works on platforms where the dwarf debugging info is not
5302 * - it allows the setting of breakpoints of aot-ed methods.
5304 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5305 cfg->asm_debug_symbol = g_strdup (debug_sym);
5307 if (acfg->need_no_dead_strip)
5308 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5309 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5310 emit_label (acfg, debug_sym);
5313 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5315 /* Emit a global symbol for the method */
5316 emit_global_inner (acfg, export_name, TRUE);
5317 emit_label (acfg, export_name);
5320 if (cfg->verbose_level > 0)
5321 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5323 acfg->stats.code_size += cfg->code_len;
5325 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5327 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 ()));
5331 if (acfg->aot_opts.write_symbols) {
5333 emit_symbol_size (acfg, debug_sym, ".");
5335 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5339 emit_label (acfg, symbol);
5346 * Encode PATCH_INFO into its disk representation.
5349 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5353 switch (patch_info->type) {
5354 case MONO_PATCH_INFO_NONE:
5356 case MONO_PATCH_INFO_IMAGE:
5357 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5359 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5360 case MONO_PATCH_INFO_JIT_TLS_ID:
5361 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5362 case MONO_PATCH_INFO_GC_NURSERY_START:
5363 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5365 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5366 encode_value (patch_info->data.index, p, &p);
5368 case MONO_PATCH_INFO_METHOD_REL:
5369 encode_value ((gint)patch_info->data.offset, p, &p);
5371 case MONO_PATCH_INFO_SWITCH: {
5372 gpointer *table = (gpointer *)patch_info->data.table->table;
5375 encode_value (patch_info->data.table->table_size, p, &p);
5376 for (k = 0; k < patch_info->data.table->table_size; k++)
5377 encode_value ((int)(gssize)table [k], p, &p);
5380 case MONO_PATCH_INFO_METHODCONST:
5381 case MONO_PATCH_INFO_METHOD:
5382 case MONO_PATCH_INFO_METHOD_JUMP:
5383 case MONO_PATCH_INFO_ICALL_ADDR:
5384 case MONO_PATCH_INFO_METHOD_RGCTX:
5385 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5386 encode_method_ref (acfg, patch_info->data.method, p, &p);
5388 case MONO_PATCH_INFO_AOT_JIT_INFO:
5389 encode_value (patch_info->data.index, p, &p);
5391 case MONO_PATCH_INFO_INTERNAL_METHOD:
5392 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5393 guint32 len = strlen (patch_info->data.name);
5395 encode_value (len, p, &p);
5397 memcpy (p, patch_info->data.name, len);
5402 case MONO_PATCH_INFO_LDSTR: {
5403 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5404 guint32 token = patch_info->data.token->token;
5405 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5406 encode_value (image_index, p, &p);
5407 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5410 case MONO_PATCH_INFO_RVA:
5411 case MONO_PATCH_INFO_DECLSEC:
5412 case MONO_PATCH_INFO_LDTOKEN:
5413 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5414 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5415 encode_value (patch_info->data.token->token, p, &p);
5416 encode_value (patch_info->data.token->has_context, p, &p);
5417 if (patch_info->data.token->has_context)
5418 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5420 case MONO_PATCH_INFO_EXC_NAME: {
5421 MonoClass *ex_class;
5424 mono_class_load_from_name (mono_defaults.exception_class->image,
5425 "System", (const char *)patch_info->data.target);
5426 encode_klass_ref (acfg, ex_class, p, &p);
5429 case MONO_PATCH_INFO_R4:
5430 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5432 case MONO_PATCH_INFO_R8:
5433 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5434 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5436 case MONO_PATCH_INFO_VTABLE:
5437 case MONO_PATCH_INFO_CLASS:
5438 case MONO_PATCH_INFO_IID:
5439 case MONO_PATCH_INFO_ADJUSTED_IID:
5440 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5442 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5443 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5444 if (patch_info->data.del_tramp->method) {
5445 encode_value (1, p, &p);
5446 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5448 encode_value (0, p, &p);
5450 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5452 case MONO_PATCH_INFO_FIELD:
5453 case MONO_PATCH_INFO_SFLDA:
5454 encode_field_info (acfg, patch_info->data.field, p, &p);
5456 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5458 case MONO_PATCH_INFO_RGCTX_FETCH:
5459 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5460 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5465 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5466 * reference the same method, so encode the method only once.
5468 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5470 buf2 = (guint8 *)g_malloc (1024);
5473 encode_method_ref (acfg, entry->method, p2, &p2);
5474 g_assert (p2 - buf2 < 1024);
5476 offset = add_to_blob (acfg, buf2, p2 - buf2);
5479 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5484 encode_value (offset, p, &p);
5485 g_assert ((int)entry->info_type < 256);
5486 g_assert (entry->data->type < 256);
5487 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5488 encode_patch (acfg, entry->data, p, &p);
5491 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5492 case MONO_PATCH_INFO_AOT_MODULE:
5494 case MONO_PATCH_INFO_SIGNATURE:
5495 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5496 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5498 case MONO_PATCH_INFO_TLS_OFFSET:
5499 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5501 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5502 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5503 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5505 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5506 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5509 encode_method_ref (acfg, info->method, p, &p);
5510 encode_value (info->num_entries, p, &p);
5511 for (i = 0; i < info->num_entries; ++i) {
5512 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5514 encode_value (template_->info_type, p, &p);
5515 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5516 case MONO_PATCH_INFO_CLASS:
5517 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5519 case MONO_PATCH_INFO_FIELD:
5520 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5523 g_assert_not_reached ();
5529 case MONO_PATCH_INFO_LDSTR_LIT: {
5530 const char *s = (const char *)patch_info->data.target;
5531 int len = strlen (s);
5533 encode_value (len, p, &p);
5534 memcpy (p, s, len + 1);
5538 case MONO_PATCH_INFO_VIRT_METHOD:
5539 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5540 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5542 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5545 g_warning ("unable to handle jump info %d", patch_info->type);
5546 g_assert_not_reached ();
5553 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5556 guint32 pindex, offset;
5557 MonoJumpInfo *patch_info;
5559 encode_value (n_patches, p, &p);
5561 for (pindex = 0; pindex < patches->len; ++pindex) {
5562 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5564 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5568 offset = get_got_offset (acfg, llvm, patch_info);
5569 encode_value (offset, p, &p);
5576 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5579 int pindex, buf_size, n_patches;
5581 MonoJumpInfo *patch_info;
5582 guint32 method_index;
5584 guint32 first_got_offset;
5586 method = cfg->orig_method;
5588 method_index = get_method_index (acfg, method);
5590 /* Sort relocations */
5591 patches = g_ptr_array_new ();
5592 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5593 g_ptr_array_add (patches, patch_info);
5594 g_ptr_array_sort (patches, compare_patches);
5596 first_got_offset = acfg->cfgs [method_index]->got_offset;
5598 /**********************/
5599 /* Encode method info */
5600 /**********************/
5602 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5603 p = buf = (guint8 *)g_malloc (buf_size);
5605 if (mono_class_get_cctor (method->klass)) {
5606 encode_value (1, p, &p);
5607 encode_klass_ref (acfg, method->klass, p, &p);
5609 /* Not needed when loading the method */
5610 encode_value (0, p, &p);
5613 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5616 for (pindex = 0; pindex < patches->len; ++pindex) {
5617 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5619 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5620 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5621 patch_info->type = MONO_PATCH_INFO_NONE;
5626 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5627 /* Stored in a GOT slot initialized at module load time */
5628 patch_info->type = MONO_PATCH_INFO_NONE;
5632 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5633 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5634 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5635 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5636 /* Stored in a GOT slot initialized at module load time */
5637 patch_info->type = MONO_PATCH_INFO_NONE;
5641 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5642 /* Calls are made through the PLT */
5643 patch_info->type = MONO_PATCH_INFO_NONE;
5651 g_assert (cfg->has_got_slots);
5653 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5655 acfg->stats.info_size += p - buf;
5657 g_assert (p - buf < buf_size);
5659 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5664 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5666 guint32 cache_index;
5669 /* Reuse the unwind module to canonize and store unwind info entries */
5670 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5672 /* Use +/- 1 to distinguish 0s from missing entries */
5673 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5681 * It would be easier to use assembler symbols, but the caller needs an
5684 offset = acfg->unwind_info_offset;
5685 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5686 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5689 encode_value (encoded_len, p, &p);
5691 acfg->unwind_info_offset += encoded_len + (p - buf);
5697 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5700 guint32 debug_info_size, seq_points_size;
5702 MonoMethodHeader *header;
5703 guint8 *p, *buf, *debug_info;
5704 MonoJitInfo *jinfo = cfg->jit_info;
5706 gboolean use_unwind_ops = FALSE;
5707 MonoSeqPointInfo *seq_points;
5709 code = cfg->native_code;
5710 header = cfg->header;
5712 if (!acfg->aot_opts.nodebug) {
5713 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5716 debug_info_size = 0;
5719 seq_points = cfg->seq_point_info;
5720 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5722 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5724 p = buf = (guint8 *)g_malloc (buf_size);
5726 use_unwind_ops = cfg->unwind_ops != NULL;
5728 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);
5730 encode_value (flags, p, &p);
5732 if (use_unwind_ops) {
5733 guint32 encoded_len;
5735 guint32 unwind_desc;
5737 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5739 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5740 encode_value (unwind_desc, p, &p);
5742 encode_value (jinfo->unwind_info, p, &p);
5745 /*Encode the number of holes before the number of clauses to make decoding easier*/
5746 if (jinfo->has_try_block_holes) {
5747 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5748 encode_value (table->num_holes, p, &p);
5751 if (jinfo->has_arch_eh_info) {
5753 * In AOT mode, the code length is calculated from the address of the previous method,
5754 * which could include alignment padding, so calculating the start of the epilog as
5755 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5757 encode_value (jinfo->code_size, p, &p);
5760 /* Exception table */
5761 if (cfg->compile_llvm) {
5763 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5764 * since the information is only available to llc. Instead, we let llc save the data
5765 * into the LSDA, and read it from there at runtime.
5767 /* The assembly might be CIL stripped so emit the data ourselves */
5768 if (header->num_clauses)
5769 encode_value (header->num_clauses, p, &p);
5771 for (k = 0; k < header->num_clauses; ++k) {
5772 MonoExceptionClause *clause;
5774 clause = &header->clauses [k];
5776 encode_value (clause->flags, p, &p);
5777 if (clause->data.catch_class) {
5778 encode_value (1, p, &p);
5779 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5781 encode_value (0, p, &p);
5784 /* Emit the IL ranges too, since they might not be available at runtime */
5785 encode_value (clause->try_offset, p, &p);
5786 encode_value (clause->try_len, p, &p);
5787 encode_value (clause->handler_offset, p, &p);
5788 encode_value (clause->handler_len, p, &p);
5790 /* Emit a list of nesting clauses */
5791 for (i = 0; i < header->num_clauses; ++i) {
5793 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5795 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5797 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5798 encode_value (i, p, &p);
5800 encode_value (-1, p, &p);
5803 if (jinfo->num_clauses)
5804 encode_value (jinfo->num_clauses, p, &p);
5806 for (k = 0; k < jinfo->num_clauses; ++k) {
5807 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5809 encode_value (ei->flags, p, &p);
5810 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5811 /* Not used for catch clauses */
5812 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5813 encode_value (ei->exvar_offset, p, &p);
5815 encode_value (ei->exvar_offset, p, &p);
5818 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5819 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5821 if (ei->data.catch_class) {
5825 buf2 = (guint8 *)g_malloc (4096);
5827 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5829 g_assert (len < 4096);
5830 encode_value (len, p, &p);
5831 memcpy (p, buf2, len);
5835 encode_value (0, p, &p);
5839 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5840 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5841 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5845 if (jinfo->has_try_block_holes) {
5846 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5847 for (i = 0; i < table->num_holes; ++i) {
5848 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5849 encode_value (hole->clause, p, &p);
5850 encode_value (hole->length, p, &p);
5851 encode_value (hole->offset, p, &p);
5855 if (jinfo->has_arch_eh_info) {
5856 MonoArchEHJitInfo *eh_info;
5858 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5859 encode_value (eh_info->stack_size, p, &p);
5860 encode_value (eh_info->epilog_size, p, &p);
5863 if (jinfo->has_generic_jit_info) {
5864 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5865 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5869 encode_value (gi->nlocs, p, &p);
5871 for (i = 0; i < gi->nlocs; ++i) {
5872 MonoDwarfLocListEntry *entry = &gi->locations [i];
5874 encode_value (entry->is_reg ? 1 : 0, p, &p);
5875 encode_value (entry->reg, p, &p);
5877 encode_value (entry->offset, p, &p);
5879 g_assert (entry->from == 0);
5881 encode_value (entry->from, p, &p);
5882 encode_value (entry->to, p, &p);
5885 if (!cfg->compile_llvm) {
5886 encode_value (gi->has_this ? 1 : 0, p, &p);
5887 encode_value (gi->this_reg, p, &p);
5888 encode_value (gi->this_offset, p, &p);
5893 * Need to encode jinfo->method too, since it is not equal to 'method'
5894 * when using generic sharing.
5896 buf2 = (guint8 *)g_malloc (4096);
5898 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5900 g_assert (len < 4096);
5901 encode_value (len, p, &p);
5902 memcpy (p, buf2, len);
5906 if (gsctx && gsctx->is_gsharedvt) {
5907 encode_value (1, p, &p);
5909 encode_value (0, p, &p);
5913 if (seq_points_size)
5914 p += mono_seq_point_info_write (seq_points, p);
5916 g_assert (debug_info_size < buf_size);
5918 encode_value (debug_info_size, p, &p);
5919 if (debug_info_size) {
5920 memcpy (p, debug_info, debug_info_size);
5921 p += debug_info_size;
5922 g_free (debug_info);
5927 encode_value (cfg->gc_map_size, p, &p);
5928 /* The GC map requires 4 bytes of alignment */
5929 while ((gsize)p % 4)
5931 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5932 p += cfg->gc_map_size;
5935 acfg->stats.ex_info_size += p - buf;
5937 g_assert (p - buf < buf_size);
5940 /* The GC Map requires 4 byte alignment */
5941 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5946 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5949 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5951 int i, buf_size, res;
5952 gboolean no_special_static, cant_encode;
5953 gpointer iter = NULL;
5956 mono_error_cleanup (&error);
5960 p = buf = (guint8 *)g_malloc (buf_size);
5962 /* Mark as unusable */
5963 encode_value (-1, p, &p);
5965 res = add_to_blob (acfg, buf, p - buf);
5971 buf_size = 10240 + (klass->vtable_size * 16);
5972 p = buf = (guint8 *)g_malloc (buf_size);
5976 mono_class_init (klass);
5978 mono_class_get_nested_types (klass, &iter);
5979 g_assert (klass->nested_classes_inited);
5981 mono_class_setup_vtable (klass);
5984 * Emit all the information which is required for creating vtables so
5985 * the runtime does not need to create the MonoMethod structures which
5986 * take up a lot of space.
5989 no_special_static = !mono_class_has_special_static_fields (klass);
5991 /* Check whenever we have enough info to encode the vtable */
5992 cant_encode = FALSE;
5993 for (i = 0; i < klass->vtable_size; ++i) {
5994 MonoMethod *cm = klass->vtable [i];
5996 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6000 mono_class_has_finalizer (klass);
6002 if (klass->generic_container || cant_encode) {
6003 encode_value (-1, p, &p);
6005 encode_value (klass->vtable_size, p, &p);
6006 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);
6007 if (klass->has_cctor)
6008 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6009 if (klass->has_finalize)
6010 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6012 encode_value (klass->instance_size, p, &p);
6013 encode_value (mono_class_data_size (klass), p, &p);
6014 encode_value (klass->packing_size, p, &p);
6015 encode_value (klass->min_align, p, &p);
6017 for (i = 0; i < klass->vtable_size; ++i) {
6018 MonoMethod *cm = klass->vtable [i];
6021 encode_method_ref (acfg, cm, p, &p);
6023 encode_value (0, p, &p);
6027 acfg->stats.class_info_size += p - buf;
6029 g_assert (p - buf < buf_size);
6030 res = add_to_blob (acfg, buf, p - buf);
6037 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6039 char *debug_sym = NULL;
6042 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6043 /* Need to add a prefix to create unique symbols */
6044 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6046 prefix = g_strdup ("plt_");
6050 case MONO_PATCH_INFO_METHOD:
6051 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6053 case MONO_PATCH_INFO_INTERNAL_METHOD:
6054 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6056 case MONO_PATCH_INFO_RGCTX_FETCH:
6057 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6059 case MONO_PATCH_INFO_ICALL_ADDR: {
6060 char *s = get_debug_sym (ji->data.method, "", cache);
6062 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6066 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6067 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6075 return sanitize_symbol (acfg, debug_sym);
6079 * Calls made from AOTed code are routed through a table of jumps similar to the
6080 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6081 * control to the AOT runtime through a trampoline.
6084 emit_plt (MonoAotCompile *acfg)
6088 if (acfg->aot_opts.llvm_only) {
6089 g_assert (acfg->plt_offset == 1);
6095 emit_section_change (acfg, ".text", 0);
6096 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6097 emit_info_symbol (acfg, "plt");
6098 emit_label (acfg, acfg->plt_symbol);
6100 for (i = 0; i < acfg->plt_offset; ++i) {
6101 char *debug_sym = NULL;
6102 MonoPltEntry *plt_entry = NULL;
6106 * The first plt entry is unused.
6110 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6112 debug_sym = plt_entry->debug_sym;
6114 if (acfg->thumb_mixed && !plt_entry->jit_used)
6115 /* Emit only a thumb version */
6118 /* Skip plt entries not actually called */
6119 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6122 if (acfg->llvm && !acfg->thumb_mixed) {
6123 emit_label (acfg, plt_entry->llvm_symbol);
6125 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6126 #if defined(TARGET_MACH)
6127 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6133 if (acfg->need_no_dead_strip) {
6134 emit_unset_mode (acfg);
6135 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6137 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6138 emit_label (acfg, debug_sym);
6141 emit_label (acfg, plt_entry->symbol);
6143 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6146 emit_symbol_size (acfg, debug_sym, ".");
6149 if (acfg->thumb_mixed) {
6150 /* Make sure the ARM symbols don't alias the thumb ones */
6151 emit_zero_bytes (acfg, 16);
6154 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6157 for (i = 0; i < acfg->plt_offset; ++i) {
6158 char *debug_sym = NULL;
6159 MonoPltEntry *plt_entry = NULL;
6164 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6166 /* Skip plt entries not actually called by LLVM code */
6167 if (!plt_entry->llvm_used)
6170 if (acfg->aot_opts.write_symbols) {
6171 if (plt_entry->debug_sym)
6172 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6176 #if defined(TARGET_MACH)
6177 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6178 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6180 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6181 emit_label (acfg, debug_sym);
6183 fprintf (acfg->fp, "\n.thumb_func\n");
6185 emit_label (acfg, plt_entry->llvm_symbol);
6188 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6190 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6193 emit_symbol_size (acfg, debug_sym, ".");
6199 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6201 emit_info_symbol (acfg, "plt_end");
6205 * emit_trampoline_full:
6207 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6208 * create_jit_info_for_trampoline ().
6210 static G_GNUC_UNUSED void
6211 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6213 char start_symbol [256];
6214 char end_symbol [256];
6216 guint32 buf_size, info_offset;
6217 MonoJumpInfo *patch_info;
6230 code_size = info->code_size;
6232 unwind_ops = info->unwind_ops;
6234 #ifdef __native_client_codegen__
6235 mono_nacl_fix_patches (code, ji);
6240 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6242 emit_section_change (acfg, ".text", 0);
6243 emit_global (acfg, start_symbol, TRUE);
6244 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6245 emit_label (acfg, start_symbol);
6247 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6248 emit_label (acfg, symbol);
6251 * The code should access everything through the GOT, so we pass
6254 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6256 emit_symbol_size (acfg, start_symbol, ".");
6259 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6260 emit_label (acfg, end_symbol);
6265 /* Sort relocations */
6266 patches = g_ptr_array_new ();
6267 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6268 if (patch_info->type != MONO_PATCH_INFO_NONE)
6269 g_ptr_array_add (patches, patch_info);
6270 g_ptr_array_sort (patches, compare_patches);
6272 buf_size = patches->len * 128 + 128;
6273 buf = (guint8 *)g_malloc (buf_size);
6276 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6277 g_assert (p - buf < buf_size);
6279 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6281 info_offset = add_to_blob (acfg, buf, p - buf);
6283 emit_section_change (acfg, RODATA_SECT, 0);
6284 emit_global (acfg, symbol, FALSE);
6285 emit_label (acfg, symbol);
6287 emit_int32 (acfg, info_offset);
6291 guint32 encoded_len;
6295 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6297 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6298 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6301 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6302 emit_int32 (acfg, uw_offset);
6305 /* Emit debug info */
6309 sprintf (symbol, "%s", name);
6310 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6313 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6317 static G_GNUC_UNUSED void
6318 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6320 emit_trampoline_full (acfg, got_offset, info, TRUE);
6324 emit_trampolines (MonoAotCompile *acfg)
6327 char end_symbol [256];
6328 int i, tramp_got_offset;
6330 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6334 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6337 g_assert (acfg->image->assembly);
6339 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6340 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6341 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6342 MonoTrampInfo *info;
6345 * Emit the generic trampolines.
6347 * We could save some code by treating the generic trampolines as a wrapper
6348 * method, but that approach has its own complexities, so we choose the simpler
6351 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6352 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6353 #ifdef DISABLE_REMOTING
6354 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6357 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6358 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6361 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6362 emit_trampoline (acfg, acfg->got_offset, info);
6365 /* Emit the exception related code pieces */
6366 mono_arch_get_restore_context (&info, TRUE);
6367 emit_trampoline (acfg, acfg->got_offset, info);
6368 mono_arch_get_call_filter (&info, TRUE);
6369 emit_trampoline (acfg, acfg->got_offset, info);
6370 mono_arch_get_throw_exception (&info, TRUE);
6371 emit_trampoline (acfg, acfg->got_offset, info);
6372 mono_arch_get_rethrow_exception (&info, TRUE);
6373 emit_trampoline (acfg, acfg->got_offset, info);
6374 mono_arch_get_throw_corlib_exception (&info, TRUE);
6375 emit_trampoline (acfg, acfg->got_offset, info);
6377 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6378 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6379 emit_trampoline (acfg, acfg->got_offset, info);
6380 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6381 emit_trampoline (acfg, acfg->got_offset, info);
6384 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6385 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6387 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6389 /* Create a separate out trampoline for more information in stack traces */
6390 info->name = g_strdup ("gsharedvt_out_trampoline");
6391 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6395 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6397 GSList *l = mono_arch_get_trampolines (TRUE);
6400 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6402 emit_trampoline (acfg, acfg->got_offset, info);
6408 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6411 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6412 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6413 emit_trampoline (acfg, acfg->got_offset, info);
6415 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6416 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6417 emit_trampoline (acfg, acfg->got_offset, info);
6420 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6421 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6422 emit_trampoline (acfg, acfg->got_offset, info);
6428 /* delegate_invoke_impl trampolines */
6429 l = mono_arch_get_delegate_invoke_impls ();
6431 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6433 emit_trampoline (acfg, acfg->got_offset, info);
6438 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6440 /* Emit trampolines which are numerous */
6443 * These include the following:
6444 * - specific trampolines
6445 * - static rgctx invoke trampolines
6447 * These trampolines have the same code, they are parameterized by GOT
6449 * They are defined in this file, in the arch_... routines instead of
6450 * in tramp-<ARCH>.c, since it is easier to do it this way.
6454 * When running in aot-only mode, we can't create specific trampolines at
6455 * runtime, so we create a few, and save them in the AOT file.
6456 * Normal trampolines embed their argument as a literal inside the
6457 * trampoline code, we can't do that here, so instead we embed an offset
6458 * which needs to be added to the trampoline address to get the address of
6459 * the GOT slot which contains the argument value.
6460 * The generated trampolines jump to the generic trampolines using another
6461 * GOT slot, which will be setup by the AOT loader to point to the
6462 * generic trampoline code of the given type.
6466 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6470 emit_section_change (acfg, ".text", 0);
6472 tramp_got_offset = acfg->got_offset;
6474 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6476 case MONO_AOT_TRAMP_SPECIFIC:
6477 sprintf (symbol, "specific_trampolines");
6479 case MONO_AOT_TRAMP_STATIC_RGCTX:
6480 sprintf (symbol, "static_rgctx_trampolines");
6482 case MONO_AOT_TRAMP_IMT_THUNK:
6483 sprintf (symbol, "imt_thunks");
6485 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6486 sprintf (symbol, "gsharedvt_arg_trampolines");
6489 g_assert_not_reached ();
6492 sprintf (end_symbol, "%s_e", symbol);
6494 if (acfg->aot_opts.write_symbols)
6495 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6497 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6498 emit_info_symbol (acfg, symbol);
6500 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6502 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6506 case MONO_AOT_TRAMP_SPECIFIC:
6507 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6508 tramp_got_offset += 2;
6510 case MONO_AOT_TRAMP_STATIC_RGCTX:
6511 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6512 tramp_got_offset += 2;
6514 case MONO_AOT_TRAMP_IMT_THUNK:
6515 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6516 tramp_got_offset += 1;
6518 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6519 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6520 tramp_got_offset += 2;
6523 g_assert_not_reached ();
6525 #ifdef __native_client_codegen__
6526 /* align to avoid 32-byte boundary crossings */
6527 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6530 if (!acfg->trampoline_size [ntype]) {
6531 g_assert (tramp_size);
6532 acfg->trampoline_size [ntype] = tramp_size;
6536 emit_label (acfg, end_symbol);
6537 emit_int32 (acfg, 0);
6540 arch_emit_specific_trampoline_pages (acfg);
6542 /* Reserve some entries at the end of the GOT for our use */
6543 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6546 acfg->got_offset += acfg->num_trampoline_got_entries;
6550 str_begins_with (const char *str1, const char *str2)
6552 int len = strlen (str2);
6553 return strncmp (str1, str2, len) == 0;
6557 mono_aot_readonly_field_override (MonoClassField *field)
6560 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6561 char *p = rdv->name;
6563 len = strlen (field->parent->name_space);
6564 if (strncmp (p, field->parent->name_space, len))
6569 len = strlen (field->parent->name);
6570 if (strncmp (p, field->parent->name, len))
6575 if (strcmp (p, field->name))
6577 switch (rdv->type) {
6579 return &rdv->value.i1;
6581 return &rdv->value.i2;
6583 return &rdv->value.i4;
6592 add_readonly_value (MonoAotOptions *opts, const char *val)
6597 /* the format of val is:
6598 * namespace.typename.fieldname=type/value
6599 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6601 fval = strrchr (val, '/');
6603 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6606 tval = strrchr (val, '=');
6608 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6611 rdv = g_new0 (ReadOnlyValue, 1);
6612 rdv->name = (char *)g_malloc0 (tval - val + 1);
6613 memcpy (rdv->name, val, tval - val);
6616 if (strncmp (tval, "i1", 2) == 0) {
6617 rdv->value.i1 = atoi (fval);
6618 rdv->type = MONO_TYPE_I1;
6619 } else if (strncmp (tval, "i2", 2) == 0) {
6620 rdv->value.i2 = atoi (fval);
6621 rdv->type = MONO_TYPE_I2;
6622 } else if (strncmp (tval, "i4", 2) == 0) {
6623 rdv->value.i4 = atoi (fval);
6624 rdv->type = MONO_TYPE_I4;
6626 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6629 rdv->next = readonly_values;
6630 readonly_values = rdv;
6634 clean_path (gchar * path)
6639 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6642 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6649 wrap_path (gchar * path)
6655 // If the string contains no spaces, just return the original string.
6656 if (strstr (path, " ") == NULL)
6659 // If the string is already wrapped in quotes, return it.
6660 len = strlen (path);
6661 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6664 // If the string contains spaces, then wrap it in quotes.
6665 gchar *clean = g_strdup_printf ("\"%s\"", path);
6671 mono_aot_split_options (const char *aot_options)
6673 enum MonoAotOptionState {
6674 MONO_AOT_OPTION_STATE_DEFAULT,
6675 MONO_AOT_OPTION_STATE_STRING,
6676 MONO_AOT_OPTION_STATE_ESCAPE,
6679 GPtrArray *args = g_ptr_array_new ();
6680 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6681 gchar const *opt_start = aot_options;
6682 gboolean end_of_string = FALSE;
6685 g_return_val_if_fail (aot_options != NULL, NULL);
6687 while ((cur = *aot_options) != '\0') {
6688 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6693 // If we find a quote, then if we're in the default case then
6694 // it means we've found the start of a string, if not then it
6695 // means we've found the end of the string and should switch
6696 // back to the default case.
6698 case MONO_AOT_OPTION_STATE_DEFAULT:
6699 state = MONO_AOT_OPTION_STATE_STRING;
6701 case MONO_AOT_OPTION_STATE_STRING:
6702 state = MONO_AOT_OPTION_STATE_DEFAULT;
6704 case MONO_AOT_OPTION_STATE_ESCAPE:
6705 g_assert_not_reached ();
6710 // If we've found an escaping operator, then this means we
6711 // should not process the next character if inside a string.
6712 if (state == MONO_AOT_OPTION_STATE_STRING)
6713 state = MONO_AOT_OPTION_STATE_ESCAPE;
6716 // If we're in the default state then this means we've found
6717 // an option, store it for later processing.
6718 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6725 // If the next character is end of string, then process the last option.
6726 if (*(aot_options) == '\0') {
6727 end_of_string = TRUE;
6733 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6734 opt_start = ++aot_options;
6744 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6748 args = mono_aot_split_options (aot_options ? aot_options : "");
6749 for (int i = 0; i < args->len; ++i) {
6750 const char *arg = (const char *)g_ptr_array_index (args, i);
6752 if (str_begins_with (arg, "outfile=")) {
6753 opts->outfile = g_strdup (arg + strlen ("outfile="));
6754 } else if (str_begins_with (arg, "llvm-outfile=")) {
6755 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6756 } else if (str_begins_with (arg, "temp-path=")) {
6757 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6758 } else if (str_begins_with (arg, "save-temps")) {
6759 opts->save_temps = TRUE;
6760 } else if (str_begins_with (arg, "keep-temps")) {
6761 opts->save_temps = TRUE;
6762 } else if (str_begins_with (arg, "write-symbols")) {
6763 opts->write_symbols = TRUE;
6764 } else if (str_begins_with (arg, "no-write-symbols")) {
6765 opts->write_symbols = FALSE;
6766 } else if (str_begins_with (arg, "metadata-only")) {
6767 opts->metadata_only = TRUE;
6768 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6769 opts->bind_to_runtime_version = TRUE;
6770 } else if (str_begins_with (arg, "full")) {
6771 opts->mode = MONO_AOT_MODE_FULL;
6772 } else if (str_begins_with (arg, "hybrid")) {
6773 opts->mode = MONO_AOT_MODE_HYBRID;
6774 } else if (str_begins_with (arg, "threads=")) {
6775 opts->nthreads = atoi (arg + strlen ("threads="));
6776 } else if (str_begins_with (arg, "static")) {
6777 opts->static_link = TRUE;
6778 opts->no_dlsym = TRUE;
6779 } else if (str_begins_with (arg, "asmonly")) {
6780 opts->asm_only = TRUE;
6781 } else if (str_begins_with (arg, "asmwriter")) {
6782 opts->asm_writer = TRUE;
6783 } else if (str_begins_with (arg, "nodebug")) {
6784 opts->nodebug = TRUE;
6785 } else if (str_begins_with (arg, "dwarfdebug")) {
6786 opts->dwarf_debug = TRUE;
6787 } else if (str_begins_with (arg, "nopagetrampolines")) {
6788 opts->use_trampolines_page = FALSE;
6789 } else if (str_begins_with (arg, "ntrampolines=")) {
6790 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6791 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6792 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6793 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6794 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6795 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6796 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6797 } else if (str_begins_with (arg, "tool-prefix=")) {
6798 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6799 } else if (str_begins_with (arg, "ld-flags=")) {
6800 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6801 } else if (str_begins_with (arg, "soft-debug")) {
6802 opts->soft_debug = TRUE;
6803 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
6804 debug_options.gen_seq_points_compact_data = TRUE;
6805 opts->gen_seq_points_file = TRUE;
6806 opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
6807 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6808 debug_options.gen_seq_points_compact_data = TRUE;
6809 opts->gen_seq_points_file = TRUE;
6810 } else if (str_begins_with (arg, "direct-pinvoke")) {
6811 opts->direct_pinvoke = TRUE;
6812 } else if (str_begins_with (arg, "direct-icalls")) {
6813 opts->direct_icalls = TRUE;
6814 } else if (str_begins_with (arg, "no-direct-calls")) {
6815 opts->no_direct_calls = TRUE;
6816 } else if (str_begins_with (arg, "print-skipped")) {
6817 opts->print_skipped_methods = TRUE;
6818 } else if (str_begins_with (arg, "stats")) {
6820 } else if (str_begins_with (arg, "no-instances")) {
6821 opts->no_instances = TRUE;
6822 } else if (str_begins_with (arg, "log-generics")) {
6823 opts->log_generics = TRUE;
6824 } else if (str_begins_with (arg, "log-instances=")) {
6825 opts->log_instances = TRUE;
6826 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6827 } else if (str_begins_with (arg, "log-instances")) {
6828 opts->log_instances = TRUE;
6829 } else if (str_begins_with (arg, "internal-logfile=")) {
6830 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6831 } else if (str_begins_with (arg, "mtriple=")) {
6832 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6833 } else if (str_begins_with (arg, "llvm-path=")) {
6834 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6835 } else if (!strcmp (arg, "llvm")) {
6837 } else if (str_begins_with (arg, "readonly-value=")) {
6838 add_readonly_value (opts, arg + strlen ("readonly-value="));
6839 } else if (str_begins_with (arg, "info")) {
6840 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6842 } else if (str_begins_with (arg, "gc-maps")) {
6843 mini_gc_enable_gc_maps_for_aot ();
6844 } else if (str_begins_with (arg, "dump")) {
6845 opts->dump_json = TRUE;
6846 } else if (str_begins_with (arg, "llvmonly")) {
6847 opts->mode = MONO_AOT_MODE_FULL;
6849 opts->llvm_only = TRUE;
6850 } else if (str_begins_with (arg, "data-outfile=")) {
6851 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6852 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6853 printf ("Supported options for --aot:\n");
6854 printf (" outfile=\n");
6855 printf (" llvm-outfile=\n");
6856 printf (" llvm-path=\n");
6857 printf (" temp-path=\n");
6858 printf (" save-temps\n");
6859 printf (" keep-temps\n");
6860 printf (" write-symbols\n");
6861 printf (" metadata-only\n");
6862 printf (" bind-to-runtime-version\n");
6864 printf (" threads=\n");
6865 printf (" static\n");
6866 printf (" asmonly\n");
6867 printf (" asmwriter\n");
6868 printf (" nodebug\n");
6869 printf (" dwarfdebug\n");
6870 printf (" ntrampolines=\n");
6871 printf (" nrgctx-trampolines=\n");
6872 printf (" nimt-trampolines=\n");
6873 printf (" ngsharedvt-trampolines=\n");
6874 printf (" tool-prefix=\n");
6875 printf (" readonly-value=\n");
6876 printf (" soft-debug\n");
6877 printf (" gen-seq-points-file\n");
6878 printf (" gc-maps\n");
6879 printf (" print-skipped\n");
6880 printf (" no-instances\n");
6881 printf (" stats\n");
6884 printf (" help/?\n");
6887 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6891 g_free ((gpointer) arg);
6894 if (opts->use_trampolines_page) {
6895 opts->ntrampolines = 0;
6896 opts->nrgctx_trampolines = 0;
6897 opts->nimt_trampolines = 0;
6898 opts->ngsharedvt_arg_trampolines = 0;
6901 g_ptr_array_free (args, /*free_seg=*/TRUE);
6905 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6907 MonoMethod *method = (MonoMethod*)key;
6908 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6909 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6910 MonoJumpInfoToken *new_ji;
6912 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6913 new_ji->image = ji->image;
6914 new_ji->token = ji->token;
6915 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6919 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6921 if (klass->type_token)
6923 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6926 return can_encode_class (acfg, klass->element_class);
6931 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6933 if (method->wrapper_type) {
6934 switch (method->wrapper_type) {
6935 case MONO_WRAPPER_NONE:
6936 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6937 case MONO_WRAPPER_XDOMAIN_INVOKE:
6938 case MONO_WRAPPER_STFLD:
6939 case MONO_WRAPPER_LDFLD:
6940 case MONO_WRAPPER_LDFLDA:
6941 case MONO_WRAPPER_LDFLD_REMOTE:
6942 case MONO_WRAPPER_STFLD_REMOTE:
6943 case MONO_WRAPPER_STELEMREF:
6944 case MONO_WRAPPER_ISINST:
6945 case MONO_WRAPPER_PROXY_ISINST:
6946 case MONO_WRAPPER_ALLOC:
6947 case MONO_WRAPPER_REMOTING_INVOKE:
6948 case MONO_WRAPPER_UNKNOWN:
6949 case MONO_WRAPPER_WRITE_BARRIER:
6950 case MONO_WRAPPER_DELEGATE_INVOKE:
6951 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6952 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6953 case MONO_WRAPPER_SYNCHRONIZED:
6955 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6956 case MONO_WRAPPER_CASTCLASS: {
6957 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6966 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6970 if (!method->token) {
6971 /* The method is part of a constructed type like Int[,].Set (). */
6972 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6973 if (method->klass->rank)
6983 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6985 switch (patch_info->type) {
6986 case MONO_PATCH_INFO_METHOD:
6987 case MONO_PATCH_INFO_METHODCONST:
6988 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6989 MonoMethod *method = patch_info->data.method;
6991 return can_encode_method (acfg, method);
6993 case MONO_PATCH_INFO_VTABLE:
6994 case MONO_PATCH_INFO_CLASS:
6995 case MONO_PATCH_INFO_IID:
6996 case MONO_PATCH_INFO_ADJUSTED_IID:
6997 if (!can_encode_class (acfg, patch_info->data.klass)) {
6998 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7002 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7003 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7004 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7009 case MONO_PATCH_INFO_RGCTX_FETCH:
7010 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7011 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7013 if (!can_encode_method (acfg, entry->method))
7015 if (!can_encode_patch (acfg, entry->data))
7027 is_concrete_type (MonoType *t)
7032 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7034 if (t->type == MONO_TYPE_GENERICINST) {
7035 MonoGenericContext *orig_ctx;
7036 MonoGenericInst *inst;
7039 if (!MONO_TYPE_ISSTRUCT (t))
7041 klass = mono_class_from_mono_type (t);
7042 orig_ctx = &klass->generic_class->context;
7044 inst = orig_ctx->class_inst;
7046 for (i = 0; i < inst->type_argc; ++i) {
7047 arg = mini_get_underlying_type (inst->type_argv [i]);
7048 if (!is_concrete_type (arg))
7052 inst = orig_ctx->method_inst;
7054 for (i = 0; i < inst->type_argc; ++i) {
7055 arg = mini_get_underlying_type (inst->type_argv [i]);
7056 if (!is_concrete_type (arg))
7064 /* LOCKING: Assumes the loader lock is held */
7066 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7068 MonoMethod *wrapper;
7069 gboolean concrete = TRUE;
7070 gboolean add_in = gsharedvt_in;
7071 gboolean add_out = gsharedvt_out;
7073 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7075 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7078 if (!add_in && !add_out)
7081 if (mini_is_gsharedvt_variable_signature (sig))
7085 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7087 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7089 if (!sig->has_type_parameters) {
7090 //printf ("%s\n", mono_signature_full_name (sig));
7093 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7094 add_extra_method (acfg, wrapper);
7096 if (gsharedvt_out) {
7097 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7098 add_extra_method (acfg, wrapper);
7101 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7102 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7105 //printf ("%s\n", mono_signature_full_name (sig));
7107 copy->ret = mini_get_underlying_type (sig->ret);
7108 if (!is_concrete_type (copy->ret))
7110 for (i = 0; i < sig->param_count; ++i) {
7111 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7112 if (!is_concrete_type (copy->params [i]))
7116 copy->has_type_parameters = 0;
7119 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7120 add_extra_method (acfg, wrapper);
7123 if (gsharedvt_out) {
7124 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7125 add_extra_method (acfg, wrapper);
7128 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7136 * AOT compile a given method.
7137 * This function might be called by multiple threads, so it must be thread-safe.
7140 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7143 MonoJumpInfo *patch_info;
7146 MonoMethod *wrapped;
7150 if (acfg->aot_opts.metadata_only)
7153 mono_acfg_lock (acfg);
7154 index = get_method_index (acfg, method);
7155 mono_acfg_unlock (acfg);
7157 /* fixme: maybe we can also precompile wrapper methods */
7158 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7159 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7160 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7161 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7165 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7168 wrapped = mono_marshal_method_from_wrapper (method);
7169 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7170 // FIXME: The wrapper should be generic too, but it is not
7173 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7176 InterlockedIncrement (&acfg->stats.mcount);
7179 if (method->is_generic || method->klass->generic_container) {
7180 InterlockedIncrement (&acfg->stats.genericcount);
7185 //acfg->aot_opts.print_skipped_methods = TRUE;
7188 * Since these methods are the only ones which are compiled with
7189 * AOT support, and they are not used by runtime startup/shutdown code,
7190 * the runtime will not see AOT methods during AOT compilation,so it
7191 * does not need to support them by creating a fake GOT etc.
7193 flags = JIT_FLAG_AOT;
7194 if (mono_aot_mode_is_full (&acfg->aot_opts))
7195 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7197 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7198 if (acfg->aot_opts.llvm_only)
7199 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7200 if (acfg->aot_opts.no_direct_calls)
7201 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7203 jit_timer = mono_time_track_start ();
7204 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7205 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7207 mono_loader_clear_error ();
7209 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7210 if (acfg->aot_opts.print_skipped_methods)
7211 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7212 InterlockedIncrement (&acfg->stats.genericcount);
7215 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7216 if (acfg->aot_opts.print_skipped_methods)
7217 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7218 /* Let the exception happen at runtime */
7222 if (cfg->disable_aot) {
7223 if (acfg->aot_opts.print_skipped_methods)
7224 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7225 InterlockedIncrement (&acfg->stats.ocount);
7226 mono_destroy_compile (cfg);
7229 cfg->method_index = index;
7231 /* Nullify patches which need no aot processing */
7232 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7233 switch (patch_info->type) {
7234 case MONO_PATCH_INFO_LABEL:
7235 case MONO_PATCH_INFO_BB:
7236 patch_info->type = MONO_PATCH_INFO_NONE;
7243 /* Collect method->token associations from the cfg */
7244 mono_acfg_lock (acfg);
7245 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7246 mono_acfg_unlock (acfg);
7247 g_hash_table_destroy (cfg->token_info_hash);
7248 cfg->token_info_hash = NULL;
7251 * Check for absolute addresses.
7254 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7255 switch (patch_info->type) {
7256 case MONO_PATCH_INFO_ABS:
7257 /* unable to handle this */
7266 if (acfg->aot_opts.print_skipped_methods)
7267 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7268 InterlockedIncrement (&acfg->stats.abscount);
7269 mono_destroy_compile (cfg);
7273 /* Lock for the rest of the code */
7274 mono_acfg_lock (acfg);
7277 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7278 else if (cfg->gshared)
7279 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7280 else if (cfg->method->wrapper_type)
7281 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7283 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7286 * Check for methods/klasses we can't encode.
7289 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7290 if (!can_encode_patch (acfg, patch_info))
7295 if (acfg->aot_opts.print_skipped_methods)
7296 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7297 acfg->stats.ocount++;
7298 mono_destroy_compile (cfg);
7299 mono_acfg_unlock (acfg);
7303 if (!cfg->compile_llvm)
7304 acfg->has_jitted_code = TRUE;
7306 if (method->is_inflated && acfg->aot_opts.log_instances) {
7307 if (acfg->instances_logfile)
7308 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7310 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7313 /* Adds generic instances referenced by this method */
7315 * The depth is used to avoid infinite loops when generic virtual recursion is
7318 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7319 if (!acfg->aot_opts.no_instances && depth < 32) {
7320 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7321 switch (patch_info->type) {
7322 case MONO_PATCH_INFO_RGCTX_FETCH:
7323 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7324 case MONO_PATCH_INFO_METHOD: {
7325 MonoMethod *m = NULL;
7327 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7328 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7330 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7331 m = e->data->data.method;
7333 m = patch_info->data.method;
7338 if (m->is_inflated) {
7339 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7340 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7341 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7342 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7343 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7344 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7346 add_extra_method_with_depth (acfg, m, depth + 1);
7347 add_types_from_method_header (acfg, m);
7350 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7352 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7353 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7355 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7356 add_extra_method_with_depth (acfg, m, depth + 1);
7360 case MONO_PATCH_INFO_VTABLE: {
7361 MonoClass *klass = patch_info->data.klass;
7363 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7364 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7367 case MONO_PATCH_INFO_SFLDA: {
7368 MonoClass *klass = patch_info->data.field->parent;
7370 /* The .cctor needs to run at runtime. */
7371 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7372 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7381 /* Determine whenever the method has GOT slots */
7382 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7383 switch (patch_info->type) {
7384 case MONO_PATCH_INFO_GOT_OFFSET:
7385 case MONO_PATCH_INFO_NONE:
7386 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7387 case MONO_PATCH_INFO_GC_NURSERY_START:
7388 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7390 case MONO_PATCH_INFO_IMAGE:
7391 /* The assembly is stored in GOT slot 0 */
7392 if (patch_info->data.image != acfg->image)
7393 cfg->has_got_slots = TRUE;
7396 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7397 cfg->has_got_slots = TRUE;
7402 if (!cfg->has_got_slots)
7403 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7405 /* Add gsharedvt wrappers for signatures used by the method */
7406 if (acfg->aot_opts.llvm_only) {
7409 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7410 /* These only need out wrappers */
7411 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7413 for (l = cfg->signatures; l; l = l->next) {
7414 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7416 /* These only need in wrappers */
7417 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7422 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7424 /* Make a copy of the patch info which is in the mempool */
7426 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7428 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7429 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7432 patches = new_patch_info;
7434 patches_end->next = new_patch_info;
7435 patches_end = new_patch_info;
7437 cfg->patch_info = patches;
7439 /* Make a copy of the unwind info */
7441 GSList *l, *unwind_ops;
7445 for (l = cfg->unwind_ops; l; l = l->next) {
7446 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7447 memcpy (op, l->data, sizeof (MonoUnwindOp));
7448 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7450 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7452 /* Make a copy of the argument/local info */
7455 MonoInst **args, **locals;
7456 MonoMethodSignature *sig;
7457 MonoMethodHeader *header;
7460 sig = mono_method_signature (method);
7461 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7462 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7463 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7464 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7468 header = mono_method_get_header_checked (method, &error);
7469 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7470 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7471 for (i = 0; i < header->num_locals; ++i) {
7472 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7473 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7475 cfg->locals = locals;
7478 /* Free some fields used by cfg to conserve memory */
7479 mono_mempool_destroy (cfg->mempool);
7480 cfg->mempool = NULL;
7481 g_free (cfg->varinfo);
7482 cfg->varinfo = NULL;
7486 mono_regstate_free (cfg->rs);
7490 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7492 while (index >= acfg->cfgs_size) {
7493 MonoCompile **new_cfgs;
7496 new_size = acfg->cfgs_size * 2;
7497 new_cfgs = g_new0 (MonoCompile*, new_size);
7498 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7499 g_free (acfg->cfgs);
7500 acfg->cfgs = new_cfgs;
7501 acfg->cfgs_size = new_size;
7503 acfg->cfgs [index] = cfg;
7505 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7507 mono_update_jit_stats (cfg);
7510 if (cfg->orig_method->wrapper_type)
7511 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7514 mono_acfg_unlock (acfg);
7516 InterlockedIncrement (&acfg->stats.ccount);
7520 compile_thread_main (gpointer *user_data)
7522 MonoDomain *domain = (MonoDomain *)user_data [0];
7523 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7524 GPtrArray *methods = (GPtrArray *)user_data [2];
7527 mono_thread_attach (domain);
7529 for (i = 0; i < methods->len; ++i)
7530 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7534 load_profile_files (MonoAotCompile *acfg)
7538 int file_index, res, method_index, i;
7541 GList *unordered, *l;
7546 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7548 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7553 infile = fopen (tmp, "r");
7556 printf ("Using profile data file '%s'\n", tmp);
7561 res = fscanf (infile, "%32s\n", ver);
7562 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7563 printf ("Profile file has wrong version or invalid.\n");
7570 MonoMethodDesc *desc;
7573 if (fgets (name, 1023, infile) == NULL)
7576 /* Kill the newline */
7577 if (strlen (name) > 0)
7578 name [strlen (name) - 1] = '\0';
7580 desc = mono_method_desc_new (name, TRUE);
7582 method = mono_method_desc_search_in_image (desc, acfg->image);
7584 if (method && mono_method_get_token (method)) {
7585 token = mono_method_get_token (method);
7586 method_index = mono_metadata_token_index (token) - 1;
7589 for (i = 0; i < acfg->method_order->len; ++i) {
7590 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7596 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7598 //printf ("No method found matching '%s'.\n", name);
7604 /* Add missing methods */
7606 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7608 for (i = 0; i < acfg->method_order->len; ++i) {
7609 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7615 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7617 unordered = g_list_reverse (unordered);
7618 for (l = unordered; l; l = l->next)
7619 g_ptr_array_add (acfg->method_order, l->data);
7622 /* Used by the LLVM backend */
7624 mono_aot_get_got_offset (MonoJumpInfo *ji)
7626 return get_got_offset (llvm_acfg, TRUE, ji);
7630 * mono_aot_is_shared_got_offset:
7632 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7633 * when the AOT image is loaded.
7636 mono_aot_is_shared_got_offset (int offset)
7638 return offset < llvm_acfg->nshared_got_entries;
7642 mono_aot_get_method_name (MonoCompile *cfg)
7644 if (llvm_acfg->aot_opts.static_link)
7645 /* Include the assembly name too to avoid duplicate symbol errors */
7646 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7648 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7652 * mono_aot_is_linkonce_method:
7654 * Return whenever METHOD should be emitted with linkonce linkage,
7655 * eliminating duplicate copies when compiling in static mode.
7658 mono_aot_is_linkonce_method (MonoMethod *method)
7662 // FIXME: Add more cases
7663 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7665 info = mono_marshal_get_wrapper_info (method);
7666 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7672 append_mangled_type (GString *s, MonoType *t)
7675 g_string_append_printf (s, "b");
7677 case MONO_TYPE_VOID:
7678 g_string_append_printf (s, "void_");
7681 g_string_append_printf (s, "i1");
7684 g_string_append_printf (s, "u1");
7687 g_string_append_printf (s, "i2");
7690 g_string_append_printf (s, "u2");
7693 g_string_append_printf (s, "i4");
7696 g_string_append_printf (s, "u4");
7699 g_string_append_printf (s, "i8");
7702 g_string_append_printf (s, "u8");
7705 g_string_append_printf (s, "ii");
7708 g_string_append_printf (s, "ui");
7711 g_string_append_printf (s, "fl");
7714 g_string_append_printf (s, "do");
7717 char *fullname = mono_type_full_name (t);
7723 * Have to create a mangled name which is:
7727 temp = g_string_new ("");
7728 len = strlen (fullname);
7729 for (i = 0; i < len; ++i) {
7730 char c = fullname [i];
7732 g_string_append_c (temp, c);
7733 } else if (c == '_') {
7734 g_string_append_c (temp, '_');
7735 g_string_append_c (temp, '_');
7737 g_string_append_c (temp, '_');
7738 g_string_append_printf (temp, "%x", (int)c);
7741 temps = g_string_free (temp, FALSE);
7742 /* Include the length to avoid different length type names aliasing each other */
7743 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
7752 append_mangled_signature (GString *s, MonoMethodSignature *sig)
7757 supported = append_mangled_type (s, sig->ret);
7761 g_string_append_printf (s, "this_");
7762 for (i = 0; i < sig->param_count; ++i) {
7763 supported = append_mangled_type (s, sig->params [i]);
7772 * mono_aot_get_mangled_method_name:
7774 * Return a unique mangled name for METHOD, or NULL.
7777 mono_aot_get_mangled_method_name (MonoMethod *method)
7783 // FIXME: Add more cases
7784 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7786 info = mono_marshal_get_wrapper_info (method);
7787 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7790 s = g_string_new ("");
7792 g_string_append_printf (s, "aot_method_w_");
7794 switch (info->subtype) {
7795 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
7796 g_string_append_printf (s, "gsharedvt_in_");
7798 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
7799 g_string_append_printf (s, "gsharedvt_out_");
7802 g_assert_not_reached ();
7806 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
7808 g_string_free (s, TRUE);
7812 return g_string_free (s, FALSE);
7816 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7818 return is_direct_callable (llvm_acfg, NULL, patch_info);
7822 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7824 MonoPltEntry *plt_entry;
7826 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7827 plt_entry->llvm_used = FALSE;
7831 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7833 const char *sym = NULL;
7835 if (llvm_acfg->aot_opts.direct_icalls) {
7836 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7837 /* Call to a C function implementing a jit icall */
7838 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7839 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7840 MonoMethod *method = (MonoMethod *)data;
7841 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7842 sym = mono_lookup_icall_symbol (method);
7843 else if (llvm_acfg->aot_opts.direct_pinvoke)
7844 sym = get_pinvoke_import (llvm_acfg, method);
7847 return g_strdup (sym);
7853 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7855 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7856 MonoPltEntry *plt_entry;
7857 const char *sym = NULL;
7860 ji->data.target = data;
7862 if (!can_encode_patch (llvm_acfg, ji))
7865 if (llvm_acfg->aot_opts.direct_icalls) {
7866 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7867 /* Call to a C function implementing a jit icall */
7868 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7869 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7870 MonoMethod *method = (MonoMethod *)data;
7871 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7872 sym = mono_lookup_icall_symbol (method);
7875 return g_strdup (sym);
7878 plt_entry = get_plt_entry (llvm_acfg, ji);
7879 plt_entry->llvm_used = TRUE;
7881 #if defined(TARGET_MACH)
7882 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7884 return g_strdup_printf (plt_entry->llvm_symbol);
7889 mono_aot_get_method_index (MonoMethod *method)
7891 g_assert (llvm_acfg);
7892 return get_method_index (llvm_acfg, method);
7896 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7900 mono_acfg_lock (llvm_acfg);
7901 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7902 mono_acfg_unlock (llvm_acfg);
7908 execute_system (const char * command)
7913 // We need an extra set of quotes around the whole command to properly handle commands
7914 // with spaces since internally the command is called through "cmd /c.
7915 command = g_strdup_printf ("\"%s\"", command);
7917 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7918 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7919 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7920 status = _wsystem (wstr);
7924 #elif defined (HAVE_SYSTEM)
7925 status = system (command);
7927 g_assert_not_reached ();
7938 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7942 emit_llvm_file (MonoAotCompile *acfg)
7944 char *command, *opts, *tempbc, *optbc, *output_fname;
7946 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7947 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7948 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
7950 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7951 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
7954 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7957 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7958 * a lot of time, and doesn't seem to save much space.
7959 * The following optimizations cannot be enabled:
7961 * - 'jump-threading' changes our blockaddress references to int constants.
7962 * - 'basiccg' fails because it contains:
7963 * if (CS && !isa<IntrinsicInst>(II)) {
7964 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7965 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7966 * The opt list below was produced by taking the output of:
7967 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7968 * then removing tailcallelim + the global opts.
7969 * strip-dead-prototypes deletes unused intrinsics definitions.
7971 /* The dse pass is disabled because of #13734 and #17616 */
7973 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7974 * // If we have no DataLayout information around, then the size of the store
7975 * // is inferrable from the pointee type. If they are the same type, then
7976 * // we know that the store is safe.
7977 * if (AA.getDataLayout() == 0 &&
7978 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7979 * return OverwriteComplete;
7980 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7982 if (acfg->aot_opts.llvm_only)
7983 // FIXME: This doesn't work yet
7984 opts = g_strdup ("");
7986 #if LLVM_API_VERSION > 100
7987 opts = g_strdup ("-O2");
7989 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");
7991 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
7992 aot_printf (acfg, "Executing opt: %s\n", command);
7993 if (execute_system (command) != 0)
7997 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
7998 /* Nothing else to do */
8001 if (acfg->aot_opts.llvm_only) {
8002 /* Use the stock clang from xcode */
8004 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8006 aot_printf (acfg, "Executing clang: %s\n", command);
8007 if (execute_system (command) != 0)
8012 if (!acfg->llc_args)
8013 acfg->llc_args = g_string_new ("");
8015 /* Verbose asm slows down llc greatly */
8016 g_string_append (acfg->llc_args, " -asm-verbose=false");
8018 if (acfg->aot_opts.mtriple)
8019 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8021 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8023 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8025 #if LLVM_API_VERSION > 100
8026 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8029 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8030 /* ios requires PIC code now */
8031 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8033 if (llvm_acfg->aot_opts.static_link)
8034 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8036 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8039 if (acfg->llvm_owriter) {
8040 /* Emit an object file directly */
8041 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8042 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8044 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8046 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8047 g_free (output_fname);
8049 aot_printf (acfg, "Executing llc: %s\n", command);
8051 if (execute_system (command) != 0)
8058 emit_code (MonoAotCompile *acfg)
8060 int oindex, i, prev_index;
8061 gboolean saved_unbox_info = FALSE;
8064 if (acfg->aot_opts.llvm_only)
8067 #if defined(TARGET_POWERPC64)
8068 sprintf (symbol, ".Lgot_addr");
8069 emit_section_change (acfg, ".text", 0);
8070 emit_alignment (acfg, 8);
8071 emit_label (acfg, symbol);
8072 emit_pointer (acfg, acfg->got_symbol);
8076 * This global symbol is used to compute the address of each method using the
8077 * code_offsets array. It is also used to compute the memory ranges occupied by
8078 * AOT code, so it must be equal to the address of the first emitted method.
8080 emit_section_change (acfg, ".text", 0);
8081 emit_alignment_code (acfg, 8);
8082 emit_info_symbol (acfg, "jit_code_start");
8085 * Emit some padding so the local symbol for the first method doesn't have the
8086 * same address as 'methods'.
8088 #if defined(__default_codegen__)
8089 emit_padding (acfg, 16);
8090 #elif defined(__native_client_codegen__)
8092 const int kPaddingSize = 16;
8093 guint8 pad_buffer[kPaddingSize];
8094 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8095 emit_bytes (acfg, pad_buffer, kPaddingSize);
8099 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8103 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8105 cfg = acfg->cfgs [i];
8110 method = cfg->orig_method;
8112 /* Emit unbox trampoline */
8113 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8114 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8116 emit_section_change (acfg, ".text", 0);
8117 #ifdef __native_client_codegen__
8118 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8121 if (acfg->thumb_mixed && cfg->compile_llvm) {
8122 emit_set_thumb_mode (acfg);
8123 fprintf (acfg->fp, "\n.thumb_func\n");
8126 emit_label (acfg, symbol);
8128 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8130 if (acfg->thumb_mixed && cfg->compile_llvm)
8131 emit_set_arm_mode (acfg);
8133 if (!saved_unbox_info) {
8134 char user_symbol [128];
8136 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8138 emit_label (acfg, "ut_end");
8140 unwind_ops = mono_unwind_get_cie_program ();
8141 save_unwind_info (acfg, user_symbol, unwind_ops);
8142 mono_free_unwind_info (unwind_ops);
8144 /* Save the unbox trampoline size */
8145 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8147 saved_unbox_info = TRUE;
8151 if (cfg->compile_llvm)
8152 acfg->stats.llvm_count ++;
8154 emit_method_code (acfg, cfg);
8157 emit_section_change (acfg, ".text", 0);
8158 emit_alignment_code (acfg, 8);
8159 emit_info_symbol (acfg, "jit_code_end");
8161 /* To distinguish it from the next symbol */
8162 emit_padding (acfg, 4);
8165 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8166 * from optimizing them away, since it doesn't see that code_offsets references them.
8167 * JITted methods don't need this since they are referenced using assembler local
8169 * FIXME: This is why write-symbols doesn't work on OSX ?
8171 if (acfg->llvm && acfg->need_no_dead_strip) {
8172 fprintf (acfg->fp, "\n");
8173 for (i = 0; i < acfg->nmethods; ++i) {
8174 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8175 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8180 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8181 * This is PIE code, and the linker can update it if needed.
8183 sprintf (symbol, "method_addresses");
8184 emit_section_change (acfg, ".text", 1);
8185 emit_alignment_code (acfg, 8);
8186 emit_info_symbol (acfg, symbol);
8187 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8188 emit_unset_mode (acfg);
8189 if (acfg->need_no_dead_strip)
8190 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8192 for (i = 0; i < acfg->nmethods; ++i) {
8193 #ifdef MONO_ARCH_AOT_SUPPORTED
8196 if (acfg->cfgs [i]) {
8197 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8198 /* Obtained by calling a generated function in the LLVM image */
8199 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8201 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8203 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8208 sprintf (symbol, "method_addresses_end");
8209 emit_label (acfg, symbol);
8212 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8213 sprintf (symbol, "unbox_trampolines");
8214 emit_section_change (acfg, RODATA_SECT, 0);
8215 emit_alignment (acfg, 8);
8216 emit_info_symbol (acfg, symbol);
8219 for (i = 0; i < acfg->nmethods; ++i) {
8224 cfg = acfg->cfgs [i];
8228 method = cfg->orig_method;
8230 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8231 index = get_method_index (acfg, method);
8233 emit_int32 (acfg, index);
8234 /* Make sure the table is sorted by index */
8235 g_assert (index > prev_index);
8239 sprintf (symbol, "unbox_trampolines_end");
8240 emit_info_symbol (acfg, symbol);
8241 emit_int32 (acfg, 0);
8243 /* Emit a separate table with the trampoline addresses/offsets */
8244 sprintf (symbol, "unbox_trampoline_addresses");
8245 emit_section_change (acfg, ".text", 0);
8246 emit_alignment_code (acfg, 8);
8247 emit_info_symbol (acfg, symbol);
8249 for (i = 0; i < acfg->nmethods; ++i) {
8254 cfg = acfg->cfgs [i];
8258 method = cfg->orig_method;
8260 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8261 #ifdef MONO_ARCH_AOT_SUPPORTED
8264 index = get_method_index (acfg, method);
8265 sprintf (symbol, "ut_%d", index);
8267 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8271 emit_int32 (acfg, 0);
8275 emit_info (MonoAotCompile *acfg)
8280 offsets = g_new0 (gint32, acfg->nmethods);
8282 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8283 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8285 if (acfg->cfgs [i]) {
8286 emit_method_info (acfg, acfg->cfgs [i]);
8287 offsets [i] = acfg->cfgs [i]->method_info_offset;
8293 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8298 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8300 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8301 #define mix(a,b,c) { \
8302 a -= c; a ^= rot(c, 4); c += b; \
8303 b -= a; b ^= rot(a, 6); a += c; \
8304 c -= b; c ^= rot(b, 8); b += a; \
8305 a -= c; a ^= rot(c,16); c += b; \
8306 b -= a; b ^= rot(a,19); a += c; \
8307 c -= b; c ^= rot(b, 4); b += a; \
8309 #define final(a,b,c) { \
8310 c ^= b; c -= rot(b,14); \
8311 a ^= c; a -= rot(c,11); \
8312 b ^= a; b -= rot(a,25); \
8313 c ^= b; c -= rot(b,16); \
8314 a ^= c; a -= rot(c,4); \
8315 b ^= a; b -= rot(a,14); \
8316 c ^= b; c -= rot(b,24); \
8320 mono_aot_type_hash (MonoType *t1)
8322 guint hash = t1->type;
8324 hash |= t1->byref << 6; /* do not collide with t1->type values */
8326 case MONO_TYPE_VALUETYPE:
8327 case MONO_TYPE_CLASS:
8328 case MONO_TYPE_SZARRAY:
8329 /* check if the distribution is good enough */
8330 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8332 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8333 case MONO_TYPE_ARRAY:
8334 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8335 case MONO_TYPE_GENERICINST:
8336 return ((hash << 5) - hash) ^ 0;
8343 * mono_aot_method_hash:
8345 * Return a hash code for methods which only depends on metadata.
8348 mono_aot_method_hash (MonoMethod *method)
8350 MonoMethodSignature *sig;
8354 guint32 *hashes_start, *hashes;
8356 MonoGenericInst *class_ginst = NULL;
8357 MonoGenericInst *ginst = NULL;
8359 /* Similar to the hash in mono_method_get_imt_slot () */
8361 sig = mono_method_signature (method);
8363 if (method->klass->generic_class)
8364 class_ginst = method->klass->generic_class->context.class_inst;
8365 if (method->is_inflated)
8366 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8368 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8369 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8370 hashes = hashes_start;
8372 /* Some wrappers are assigned to random classes */
8373 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8374 klass = method->klass;
8376 klass = mono_defaults.object_class;
8378 if (!method->wrapper_type) {
8381 if (klass->generic_class)
8382 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8384 full_name = mono_type_full_name (&klass->byval_arg);
8386 hashes [0] = mono_metadata_str_hash (full_name);
8390 hashes [0] = mono_metadata_str_hash (klass->name);
8391 hashes [1] = mono_metadata_str_hash (klass->name_space);
8393 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8394 /* The method name includes a stringified pointer */
8397 hashes [2] = mono_metadata_str_hash (method->name);
8398 hashes [3] = method->wrapper_type;
8399 hashes [4] = mono_aot_type_hash (sig->ret);
8401 for (i = 0; i < sig->param_count; i++) {
8402 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8405 for (i = 0; i < class_ginst->type_argc; ++i)
8406 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8409 for (i = 0; i < ginst->type_argc; ++i)
8410 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8412 g_assert (hindex == hashes_count);
8414 /* Setup internal state */
8415 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8417 /* Handle most of the hashes */
8418 while (hashes_count > 3) {
8427 /* Handle the last 3 hashes (all the case statements fall through) */
8428 switch (hashes_count) {
8429 case 3 : c += hashes [2];
8430 case 2 : b += hashes [1];
8431 case 1 : a += hashes [0];
8433 case 0: /* nothing left to add */
8437 free (hashes_start);
8446 * mono_aot_get_array_helper_from_wrapper;
8448 * Get the helper method in Array called by an array wrapper method.
8451 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8455 MonoGenericContext ctx;
8456 MonoType *args [16];
8457 char *mname, *iname, *s, *s2, *helper_name = NULL;
8459 prefix = "System.Collections.Generic";
8460 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8461 s2 = strstr (s, "`1.");
8467 //printf ("X: %s %s\n", iname, mname);
8469 if (!strcmp (iname, "IList"))
8470 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8472 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8473 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8475 g_free (helper_name);
8478 if (m->is_generic) {
8480 memset (&ctx, 0, sizeof (ctx));
8481 args [0] = &method->klass->element_class->byval_arg;
8482 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8483 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8484 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8490 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8492 typedef struct HashEntry {
8493 guint32 key, value, index;
8494 struct HashEntry *next;
8498 * emit_extra_methods:
8500 * Emit methods which are not in the METHOD table, like wrappers.
8503 emit_extra_methods (MonoAotCompile *acfg)
8505 int i, table_size, buf_size;
8507 guint32 *info_offsets;
8510 HashEntry *entry, *new_entry;
8511 int nmethods, max_chain_length;
8514 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8516 /* Emit method info */
8518 for (i = 0; i < acfg->extra_methods->len; ++i) {
8519 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8520 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8526 p = buf = (guint8 *)g_malloc (buf_size);
8530 method = cfg->method_to_register;
8532 encode_method_ref (acfg, method, p, &p);
8534 g_assert ((p - buf) < buf_size);
8536 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8541 * Construct a chained hash table for mapping indexes in extra_method_info to
8544 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8545 table = g_ptr_array_sized_new (table_size);
8546 for (i = 0; i < table_size; ++i)
8547 g_ptr_array_add (table, NULL);
8548 chain_lengths = g_new0 (int, table_size);
8549 max_chain_length = 0;
8550 for (i = 0; i < acfg->extra_methods->len; ++i) {
8551 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8552 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8558 key = info_offsets [i];
8559 value = get_method_index (acfg, method);
8561 hash = mono_aot_method_hash (method) % table_size;
8562 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8564 chain_lengths [hash] ++;
8565 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8567 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8568 new_entry->key = key;
8569 new_entry->value = value;
8571 entry = (HashEntry *)g_ptr_array_index (table, hash);
8572 if (entry == NULL) {
8573 new_entry->index = hash;
8574 g_ptr_array_index (table, hash) = new_entry;
8577 entry = entry->next;
8579 entry->next = new_entry;
8580 new_entry->index = table->len;
8581 g_ptr_array_add (table, new_entry);
8585 //printf ("MAX: %d\n", max_chain_length);
8587 buf_size = table->len * 12 + 4;
8588 p = buf = (guint8 *)g_malloc (buf_size);
8589 encode_int (table_size, p, &p);
8591 for (i = 0; i < table->len; ++i) {
8592 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8594 if (entry == NULL) {
8595 encode_int (0, p, &p);
8596 encode_int (0, p, &p);
8597 encode_int (0, p, &p);
8599 //g_assert (entry->key > 0);
8600 encode_int (entry->key, p, &p);
8601 encode_int (entry->value, p, &p);
8603 encode_int (entry->next->index, p, &p);
8605 encode_int (0, p, &p);
8608 g_assert (p - buf <= buf_size);
8610 /* Emit the table */
8611 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8614 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8615 * This is used by mono_aot_find_jit_info ().
8617 buf_size = acfg->extra_methods->len * 8 + 4;
8618 p = buf = (guint8 *)g_malloc (buf_size);
8619 encode_int (acfg->extra_methods->len, p, &p);
8620 for (i = 0; i < acfg->extra_methods->len; ++i) {
8621 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8623 encode_int (get_method_index (acfg, method), p, &p);
8624 encode_int (info_offsets [i], p, &p);
8626 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8630 emit_exception_info (MonoAotCompile *acfg)
8634 SeqPointData sp_data;
8635 gboolean seq_points_to_file = FALSE;
8637 offsets = g_new0 (gint32, acfg->nmethods);
8638 for (i = 0; i < acfg->nmethods; ++i) {
8639 if (acfg->cfgs [i]) {
8640 MonoCompile *cfg = acfg->cfgs [i];
8642 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8643 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8644 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8645 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8646 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8648 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8649 offsets [i] = cfg->ex_info_offset;
8651 if (method_seq_points_to_file) {
8652 if (!seq_points_to_file) {
8653 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8654 seq_points_to_file = TRUE;
8656 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8663 if (seq_points_to_file) {
8664 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
8665 : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
8666 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8667 mono_seq_point_data_free (&sp_data);
8668 g_free (seq_points_aot_file);
8671 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8676 emit_unwind_info (MonoAotCompile *acfg)
8681 if (acfg->aot_opts.llvm_only) {
8682 g_assert (acfg->unwind_ops->len == 0);
8687 * The unwind info contains a lot of duplicates so we emit each unique
8688 * entry once, and only store the offset from the start of the table in the
8692 sprintf (symbol, "unwind_info");
8693 emit_section_change (acfg, RODATA_SECT, 1);
8694 emit_alignment (acfg, 8);
8695 emit_info_symbol (acfg, symbol);
8697 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8698 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8699 guint8 *unwind_info;
8700 guint32 unwind_info_len;
8704 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8707 encode_value (unwind_info_len, p, &p);
8708 emit_bytes (acfg, buf, p - buf);
8709 emit_bytes (acfg, unwind_info, unwind_info_len);
8711 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8716 emit_class_info (MonoAotCompile *acfg)
8721 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8722 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8723 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8725 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);
8729 typedef struct ClassNameTableEntry {
8730 guint32 token, index;
8731 struct ClassNameTableEntry *next;
8732 } ClassNameTableEntry;
8735 emit_class_name_table (MonoAotCompile *acfg)
8737 int i, table_size, buf_size;
8738 guint32 token, hash;
8743 ClassNameTableEntry *entry, *new_entry;
8746 * Construct a chained hash table for mapping class names to typedef tokens.
8748 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8749 table = g_ptr_array_sized_new (table_size);
8750 for (i = 0; i < table_size; ++i)
8751 g_ptr_array_add (table, NULL);
8752 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8754 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8755 klass = mono_class_get_checked (acfg->image, token, &error);
8757 mono_error_cleanup (&error);
8760 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8761 hash = mono_metadata_str_hash (full_name) % table_size;
8764 /* FIXME: Allocate from the mempool */
8765 new_entry = g_new0 (ClassNameTableEntry, 1);
8766 new_entry->token = token;
8768 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8769 if (entry == NULL) {
8770 new_entry->index = hash;
8771 g_ptr_array_index (table, hash) = new_entry;
8774 entry = entry->next;
8776 entry->next = new_entry;
8777 new_entry->index = table->len;
8778 g_ptr_array_add (table, new_entry);
8782 /* Emit the table */
8783 buf_size = table->len * 4 + 4;
8784 p = buf = (guint8 *)g_malloc0 (buf_size);
8786 /* FIXME: Optimize memory usage */
8787 g_assert (table_size < 65000);
8788 encode_int16 (table_size, p, &p);
8789 g_assert (table->len < 65000);
8790 for (i = 0; i < table->len; ++i) {
8791 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8793 if (entry == NULL) {
8794 encode_int16 (0, p, &p);
8795 encode_int16 (0, p, &p);
8797 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8799 encode_int16 (entry->next->index, p, &p);
8801 encode_int16 (0, p, &p);
8804 g_assert (p - buf <= buf_size);
8806 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8810 emit_image_table (MonoAotCompile *acfg)
8816 * The image table is small but referenced in a lot of places.
8817 * So we emit it at once, and reference its elements by an index.
8819 buf_size = acfg->image_table->len * 28 + 4;
8820 for (i = 0; i < acfg->image_table->len; i++) {
8821 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8822 MonoAssemblyName *aname = &image->assembly->aname;
8824 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8827 buf = p = (guint8 *)g_malloc0 (buf_size);
8828 encode_int (acfg->image_table->len, p, &p);
8829 for (i = 0; i < acfg->image_table->len; i++) {
8830 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8831 MonoAssemblyName *aname = &image->assembly->aname;
8833 /* FIXME: Support multi-module assemblies */
8834 g_assert (image->assembly->image == image);
8836 encode_string (image->assembly_name, p, &p);
8837 encode_string (image->guid, p, &p);
8838 encode_string (aname->culture ? aname->culture : "", p, &p);
8839 encode_string ((const char*)aname->public_key_token, p, &p);
8841 while (GPOINTER_TO_UINT (p) % 8 != 0)
8844 encode_int (aname->flags, p, &p);
8845 encode_int (aname->major, p, &p);
8846 encode_int (aname->minor, p, &p);
8847 encode_int (aname->build, p, &p);
8848 encode_int (aname->revision, p, &p);
8850 g_assert (p - buf <= buf_size);
8852 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8858 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8860 int i, first_plt_got_patch = 0, buf_size;
8862 guint32 *got_info_offsets;
8863 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8865 /* Add the patches needed by the PLT to the GOT */
8867 acfg->plt_got_offset_base = acfg->got_offset;
8868 first_plt_got_patch = info->got_patches->len;
8869 for (i = 1; i < acfg->plt_offset; ++i) {
8870 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8872 g_ptr_array_add (info->got_patches, plt_entry->ji);
8874 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8877 acfg->got_offset += acfg->plt_offset;
8882 * - optimize offsets table.
8883 * - reduce number of exported symbols.
8884 * - emit info for a klass only once.
8885 * - determine when a method uses a GOT slot which is guaranteed to be already
8887 * - clean up and document the code.
8888 * - use String.Empty in class libs.
8891 /* Encode info required to decode shared GOT entries */
8892 buf_size = info->got_patches->len * 128;
8893 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8894 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8896 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8898 if (acfg->plt_offset)
8899 acfg->plt_got_info_offsets [0] = 0;
8901 for (i = 0; i < info->got_patches->len; ++i) {
8902 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8907 encode_value (ji->type, p, &p);
8909 encode_patch (acfg, ji, p, &p);
8910 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8911 g_assert (p - buf <= buf_size);
8912 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8914 if (!llvm && i >= first_plt_got_patch)
8915 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8916 acfg->stats.got_info_size += p - buf;
8919 /* Emit got_info_offsets table */
8921 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8922 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);
8926 emit_got (MonoAotCompile *acfg)
8930 if (acfg->aot_opts.llvm_only)
8933 /* Don't make GOT global so accesses to it don't need relocations */
8934 sprintf (symbol, "%s", acfg->got_symbol);
8937 emit_unset_mode (acfg);
8938 fprintf (acfg->fp, ".section __DATA, __bss\n");
8939 emit_alignment (acfg, 8);
8941 emit_info_symbol (acfg, "jit_got");
8942 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8944 emit_section_change (acfg, ".bss", 0);
8945 emit_alignment (acfg, 8);
8946 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8947 emit_label (acfg, symbol);
8949 emit_info_symbol (acfg, "jit_got");
8950 if (acfg->got_offset > 0)
8951 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8954 sprintf (symbol, "got_end");
8955 emit_label (acfg, symbol);
8958 typedef struct GlobalsTableEntry {
8959 guint32 value, index;
8960 struct GlobalsTableEntry *next;
8961 } GlobalsTableEntry;
8964 emit_globals (MonoAotCompile *acfg)
8970 GlobalsTableEntry *entry, *new_entry;
8972 if (!acfg->aot_opts.static_link)
8974 if (acfg->aot_opts.llvm_only) {
8975 g_assert (acfg->globals->len == 0);
8980 * When static linking, we emit a table containing our globals.
8984 * Construct a chained hash table for mapping global names to their index in
8985 * the globals table.
8987 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8988 table = g_ptr_array_sized_new (table_size);
8989 for (i = 0; i < table_size; ++i)
8990 g_ptr_array_add (table, NULL);
8991 for (i = 0; i < acfg->globals->len; ++i) {
8992 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8994 hash = mono_metadata_str_hash (name) % table_size;
8996 /* FIXME: Allocate from the mempool */
8997 new_entry = g_new0 (GlobalsTableEntry, 1);
8998 new_entry->value = i;
9000 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9001 if (entry == NULL) {
9002 new_entry->index = hash;
9003 g_ptr_array_index (table, hash) = new_entry;
9006 entry = entry->next;
9008 entry->next = new_entry;
9009 new_entry->index = table->len;
9010 g_ptr_array_add (table, new_entry);
9014 /* Emit the table */
9015 sprintf (symbol, ".Lglobals_hash");
9016 emit_section_change (acfg, RODATA_SECT, 0);
9017 emit_alignment (acfg, 8);
9018 emit_label (acfg, symbol);
9020 /* FIXME: Optimize memory usage */
9021 g_assert (table_size < 65000);
9022 emit_int16 (acfg, table_size);
9023 for (i = 0; i < table->len; ++i) {
9024 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9026 if (entry == NULL) {
9027 emit_int16 (acfg, 0);
9028 emit_int16 (acfg, 0);
9030 emit_int16 (acfg, entry->value + 1);
9032 emit_int16 (acfg, entry->next->index);
9034 emit_int16 (acfg, 0);
9038 /* Emit the names */
9039 for (i = 0; i < acfg->globals->len; ++i) {
9040 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9042 sprintf (symbol, "name_%d", i);
9043 emit_section_change (acfg, RODATA_SECT, 1);
9045 emit_alignment (acfg, 4);
9047 emit_label (acfg, symbol);
9048 emit_string (acfg, name);
9051 /* Emit the globals table */
9052 sprintf (symbol, "globals");
9053 emit_section_change (acfg, ".data", 0);
9054 /* This is not a global, since it is accessed by the init function */
9055 emit_alignment (acfg, 8);
9056 emit_info_symbol (acfg, symbol);
9058 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9059 emit_pointer (acfg, symbol);
9061 for (i = 0; i < acfg->globals->len; ++i) {
9062 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9064 sprintf (symbol, "name_%d", i);
9065 emit_pointer (acfg, symbol);
9067 g_assert (strlen (name) < sizeof (symbol));
9068 sprintf (symbol, "%s", name);
9069 emit_pointer (acfg, symbol);
9071 /* Null terminate the table */
9072 emit_int32 (acfg, 0);
9073 emit_int32 (acfg, 0);
9077 emit_mem_end (MonoAotCompile *acfg)
9081 if (acfg->aot_opts.llvm_only)
9084 sprintf (symbol, "mem_end");
9085 emit_section_change (acfg, ".text", 1);
9086 emit_alignment_code (acfg, 8);
9087 emit_label (acfg, symbol);
9091 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9095 info->version = MONO_AOT_FILE_VERSION;
9096 info->plt_got_offset_base = acfg->plt_got_offset_base;
9097 info->got_size = acfg->got_offset * sizeof (gpointer);
9098 info->plt_size = acfg->plt_offset;
9099 info->nmethods = acfg->nmethods;
9100 info->flags = acfg->flags;
9101 info->opts = acfg->opts;
9102 info->simd_opts = acfg->simd_opts;
9103 info->gc_name_index = acfg->gc_name_offset;
9104 info->datafile_size = acfg->datafile_offset;
9105 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9106 info->table_offsets [i] = acfg->table_offsets [i];
9107 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9108 info->num_trampolines [i] = acfg->num_trampolines [i];
9109 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9110 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9111 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9112 info->trampoline_size [i] = acfg->trampoline_size [i];
9113 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9115 info->double_align = MONO_ABI_ALIGNOF (double);
9116 info->long_align = MONO_ABI_ALIGNOF (gint64);
9117 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9118 info->tramp_page_size = acfg->tramp_page_size;
9119 info->nshared_got_entries = acfg->nshared_got_entries;
9120 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9121 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9125 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9129 const char **symbols;
9131 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9133 symbols [sindex ++] = acfg->got_symbol;
9135 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9136 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9138 symbols [sindex ++] = NULL;
9139 symbols [sindex ++] = NULL;
9141 /* llvm_get_method */
9142 symbols [sindex ++] = NULL;
9143 /* llvm_get_unbox_tramp */
9144 symbols [sindex ++] = NULL;
9145 if (!acfg->aot_opts.llvm_only) {
9146 symbols [sindex ++] = "jit_code_start";
9147 symbols [sindex ++] = "jit_code_end";
9148 symbols [sindex ++] = "method_addresses";
9150 symbols [sindex ++] = NULL;
9151 symbols [sindex ++] = NULL;
9152 symbols [sindex ++] = NULL;
9154 if (acfg->data_outfile) {
9155 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9156 symbols [sindex ++] = NULL;
9158 symbols [sindex ++] = "blob";
9159 symbols [sindex ++] = "class_name_table";
9160 symbols [sindex ++] = "class_info_offsets";
9161 symbols [sindex ++] = "method_info_offsets";
9162 symbols [sindex ++] = "ex_info_offsets";
9163 symbols [sindex ++] = "extra_method_info_offsets";
9164 symbols [sindex ++] = "extra_method_table";
9165 symbols [sindex ++] = "got_info_offsets";
9167 symbols [sindex ++] = "llvm_got_info_offsets";
9169 symbols [sindex ++] = NULL;
9170 symbols [sindex ++] = "image_table";
9172 symbols [sindex ++] = "mem_end";
9173 symbols [sindex ++] = "assembly_guid";
9174 symbols [sindex ++] = "runtime_version";
9175 if (acfg->num_trampoline_got_entries) {
9176 symbols [sindex ++] = "specific_trampolines";
9177 symbols [sindex ++] = "static_rgctx_trampolines";
9178 symbols [sindex ++] = "imt_thunks";
9179 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9181 symbols [sindex ++] = NULL;
9182 symbols [sindex ++] = NULL;
9183 symbols [sindex ++] = NULL;
9184 symbols [sindex ++] = NULL;
9186 if (acfg->aot_opts.static_link) {
9187 symbols [sindex ++] = "globals";
9189 symbols [sindex ++] = NULL;
9191 symbols [sindex ++] = "assembly_name";
9192 symbols [sindex ++] = "plt";
9193 symbols [sindex ++] = "plt_end";
9194 symbols [sindex ++] = "unwind_info";
9195 if (!acfg->aot_opts.llvm_only) {
9196 symbols [sindex ++] = "unbox_trampolines";
9197 symbols [sindex ++] = "unbox_trampolines_end";
9198 symbols [sindex ++] = "unbox_trampoline_addresses";
9200 symbols [sindex ++] = NULL;
9201 symbols [sindex ++] = NULL;
9202 symbols [sindex ++] = NULL;
9205 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9207 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9208 emit_section_change (acfg, ".data", 0);
9209 emit_alignment (acfg, 8);
9210 emit_label (acfg, symbol);
9211 if (!acfg->aot_opts.static_link)
9212 emit_global (acfg, symbol, FALSE);
9214 /* The data emitted here must match MonoAotFileInfo. */
9216 emit_int32 (acfg, info->version);
9217 emit_int32 (acfg, info->dummy);
9220 * We emit pointers to our data structures instead of emitting global symbols which
9221 * point to them, to reduce the number of globals, and because using globals leads to
9222 * various problems (i.e. arm/thumb).
9224 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9225 emit_pointer (acfg, symbols [i]);
9227 emit_int32 (acfg, info->plt_got_offset_base);
9228 emit_int32 (acfg, info->got_size);
9229 emit_int32 (acfg, info->plt_size);
9230 emit_int32 (acfg, info->nmethods);
9231 emit_int32 (acfg, info->flags);
9232 emit_int32 (acfg, info->opts);
9233 emit_int32 (acfg, info->simd_opts);
9234 emit_int32 (acfg, info->gc_name_index);
9235 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9236 emit_int32 (acfg, info->double_align);
9237 emit_int32 (acfg, info->long_align);
9238 emit_int32 (acfg, info->generic_tramp_num);
9239 emit_int32 (acfg, info->tramp_page_size);
9240 emit_int32 (acfg, info->nshared_got_entries);
9241 emit_int32 (acfg, info->datafile_size);
9243 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9244 emit_int32 (acfg, info->table_offsets [i]);
9245 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9246 emit_int32 (acfg, info->num_trampolines [i]);
9247 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9248 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9249 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9250 emit_int32 (acfg, info->trampoline_size [i]);
9251 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9252 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9254 if (acfg->aot_opts.static_link) {
9255 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9256 emit_alignment (acfg, sizeof (gpointer));
9257 emit_label (acfg, acfg->static_linking_symbol);
9258 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9263 * Emit a structure containing all the information not stored elsewhere.
9266 emit_file_info (MonoAotCompile *acfg)
9269 MonoAotFileInfo *info;
9271 if (acfg->aot_opts.bind_to_runtime_version) {
9272 build_info = mono_get_runtime_build_info ();
9273 emit_string_symbol (acfg, "runtime_version", build_info);
9274 g_free (build_info);
9276 emit_string_symbol (acfg, "runtime_version", "");
9279 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9281 /* Emit a string holding the assembly name */
9282 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9284 info = g_new0 (MonoAotFileInfo, 1);
9285 init_aot_file_info (acfg, info);
9287 if (acfg->aot_opts.static_link) {
9292 * Emit a global symbol which can be passed by an embedding app to
9293 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9296 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9298 /* Get rid of characters which cannot occur in symbols */
9300 for (p = symbol; *p; ++p) {
9301 if (!(isalnum (*p) || *p == '_'))
9304 acfg->static_linking_symbol = g_strdup (symbol);
9308 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9310 emit_aot_file_info (acfg, info);
9314 emit_blob (MonoAotCompile *acfg)
9316 acfg->blob_closed = TRUE;
9318 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9322 emit_objc_selectors (MonoAotCompile *acfg)
9327 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9332 * cat > foo.m << EOF
9335 * return @selector(print:);
9340 mono_img_writer_emit_unset_mode (acfg->w);
9341 g_assert (acfg->fp);
9342 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9343 fprintf (acfg->fp, ".align 3\n");
9344 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9345 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9346 emit_label (acfg, symbol);
9347 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9348 emit_pointer (acfg, symbol);
9351 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9352 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9353 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9354 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9357 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9358 fprintf (acfg->fp, ".align 3\n");
9359 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9360 fprintf (acfg->fp, ".long 0\n");
9361 fprintf (acfg->fp, ".long 16\n");
9365 emit_dwarf_info (MonoAotCompile *acfg)
9367 #ifdef EMIT_DWARF_INFO
9371 /* DIEs for methods */
9372 for (i = 0; i < acfg->nmethods; ++i) {
9373 MonoCompile *cfg = acfg->cfgs [i];
9378 // FIXME: LLVM doesn't define .Lme_...
9379 if (cfg->compile_llvm)
9382 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9384 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 ()));
9390 collect_methods (MonoAotCompile *acfg)
9393 MonoImage *image = acfg->image;
9395 /* Collect methods */
9396 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9399 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9401 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9404 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9405 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9406 mono_error_cleanup (&error);
9410 /* Load all methods eagerly to skip the slower lazy loading code */
9411 mono_class_setup_methods (method->klass);
9413 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9414 /* Compile the wrapper instead */
9415 /* We do this here instead of add_wrappers () because it is easy to do it here */
9416 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9420 /* FIXME: Some mscorlib methods don't have debug info */
9422 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9423 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9424 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9425 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9426 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9427 if (!mono_debug_lookup_method (method)) {
9428 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9435 if (method->is_generic || method->klass->generic_container)
9436 /* Compile the ref shared version instead */
9437 method = mini_get_shared_method (method);
9439 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9440 add_method_with_index (acfg, method, i, FALSE);
9441 acfg->method_index ++;
9444 /* gsharedvt methods */
9445 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9448 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9450 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9453 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9454 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9456 if (method->is_generic || method->klass->generic_container) {
9457 MonoMethod *gshared;
9459 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9460 add_extra_method (acfg, gshared);
9464 add_generic_instances (acfg);
9466 if (mono_aot_mode_is_full (&acfg->aot_opts))
9467 add_wrappers (acfg);
9472 compile_methods (MonoAotCompile *acfg)
9476 if (acfg->aot_opts.nthreads > 0) {
9481 gpointer *user_data;
9482 MonoMethod **methods;
9484 methods_len = acfg->methods->len;
9486 len = acfg->methods->len / acfg->aot_opts.nthreads;
9489 * Partition the list of methods into fragments, and hand it to threads to
9492 threads = g_ptr_array_new ();
9493 /* Make a copy since acfg->methods is modified by compile_method () */
9494 methods = g_new0 (MonoMethod*, methods_len);
9495 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9496 for (i = 0; i < methods_len; ++i)
9497 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9499 while (i < methods_len) {
9500 frag = g_ptr_array_new ();
9501 for (j = 0; j < len; ++j) {
9502 if (i < methods_len) {
9503 g_ptr_array_add (frag, methods [i]);
9508 user_data = g_new0 (gpointer, 3);
9509 user_data [0] = mono_domain_get ();
9510 user_data [1] = acfg;
9511 user_data [2] = frag;
9513 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9514 g_ptr_array_add (threads, handle);
9518 for (i = 0; i < threads->len; ++i) {
9519 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9525 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9526 for (i = methods_len; i < acfg->methods->len; ++i) {
9527 /* This can new methods to acfg->methods */
9528 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9533 compile_asm (MonoAotCompile *acfg)
9535 char *command, *objfile;
9536 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9537 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9538 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9540 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9541 #define AS_OPTIONS "--64"
9542 #elif defined(TARGET_POWERPC64)
9543 #define AS_OPTIONS "-a64 -mppc64"
9544 #define LD_OPTIONS "-m elf64ppc"
9545 #elif defined(sparc) && SIZEOF_VOID_P == 8
9546 #define AS_OPTIONS "-xarch=v9"
9547 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9548 #define AS_OPTIONS "-arch i386"
9550 #define AS_OPTIONS ""
9553 #ifdef __native_client_codegen__
9554 #if defined(TARGET_AMD64)
9555 #define AS_NAME "nacl64-as"
9557 #define AS_NAME "nacl-as"
9559 #elif defined(TARGET_OSX)
9560 #define AS_NAME "clang"
9562 #define AS_NAME "as"
9566 #define LD_OPTIONS ""
9570 #define LD_NAME "ld -shared -G"
9571 #elif defined(__ppc__) && defined(TARGET_MACH)
9572 #define LD_NAME "gcc -dynamiclib"
9573 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9574 #define LD_NAME "clang --shared"
9575 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9576 #define LD_NAME "gcc -shared --dll"
9577 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9578 #define LD_NAME "clang -m32 -dynamiclib"
9579 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9580 #define LD_NAME "gcc --shared"
9583 if (acfg->aot_opts.asm_only) {
9584 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9585 if (acfg->aot_opts.static_link)
9586 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9588 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9592 if (acfg->aot_opts.static_link) {
9593 if (acfg->aot_opts.outfile)
9594 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9596 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9598 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9602 g_string_append (acfg->as_args, "-c -x assembler");
9605 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9606 acfg->as_args ? acfg->as_args->str : "",
9607 wrap_path (objfile), wrap_path (acfg->tmpfname));
9608 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9609 if (execute_system (command) != 0) {
9615 if (acfg->llvm && !acfg->llvm_owriter) {
9616 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9617 acfg->as_args ? acfg->as_args->str : "",
9618 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9619 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9620 if (execute_system (command) != 0) {
9629 if (acfg->aot_opts.static_link) {
9630 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9631 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9636 if (acfg->aot_opts.outfile)
9637 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9639 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9641 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9644 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9646 llvm_ofile = g_strdup ("");
9649 /* replace the ; flags separators with spaces */
9650 g_strdelimit (ld_flags, ";", ' ');
9652 if (acfg->aot_opts.llvm_only)
9653 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9656 command = g_strdup_printf ("%s -o %s %s %s %s", LD_NAME,
9657 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9658 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9660 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9661 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9662 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9664 aot_printf (acfg, "Executing the native linker: %s\n", command);
9665 if (execute_system (command) != 0) {
9666 g_free (tmp_outfile_name);
9667 g_free (outfile_name);
9676 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9677 printf ("Stripping the binary: %s\n", com);
9678 execute_system (com);
9681 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9683 * gas generates 'mapping symbols' each time code and data is mixed, which
9684 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9686 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9687 aot_printf (acfg, "Stripping the binary: %s\n", command);
9688 if (execute_system (command) != 0) {
9689 g_free (tmp_outfile_name);
9690 g_free (outfile_name);
9697 rename (tmp_outfile_name, outfile_name);
9699 #if defined(TARGET_MACH)
9700 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9701 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9702 if (execute_system (command) != 0) {
9707 if (!acfg->aot_opts.save_temps)
9710 g_free (tmp_outfile_name);
9711 g_free (outfile_name);
9714 if (acfg->aot_opts.save_temps)
9715 aot_printf (acfg, "Retained input file.\n");
9717 unlink (acfg->tmpfname);
9722 static void init_got_info (GotInfo *info)
9726 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9727 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9728 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9729 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9730 info->got_patches = g_ptr_array_new ();
9733 static MonoAotCompile*
9734 acfg_create (MonoAssembly *ass, guint32 opts)
9736 MonoImage *image = ass->image;
9737 MonoAotCompile *acfg;
9739 acfg = g_new0 (MonoAotCompile, 1);
9740 acfg->methods = g_ptr_array_new ();
9741 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9742 acfg->method_depth = g_hash_table_new (NULL, NULL);
9743 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9744 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9745 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9746 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9747 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9748 acfg->image_hash = g_hash_table_new (NULL, NULL);
9749 acfg->image_table = g_ptr_array_new ();
9750 acfg->globals = g_ptr_array_new ();
9751 acfg->image = image;
9753 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9754 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9755 acfg->mempool = mono_mempool_new ();
9756 acfg->extra_methods = g_ptr_array_new ();
9757 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9758 acfg->unwind_ops = g_ptr_array_new ();
9759 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9760 acfg->method_order = g_ptr_array_new ();
9761 acfg->export_names = g_hash_table_new (NULL, NULL);
9762 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9763 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9764 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9765 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9766 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9767 mono_os_mutex_init_recursive (&acfg->mutex);
9769 init_got_info (&acfg->got_info);
9770 init_got_info (&acfg->llvm_got_info);
9776 got_info_free (GotInfo *info)
9780 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9781 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9782 g_free (info->patch_to_got_offset_by_type);
9783 g_hash_table_destroy (info->patch_to_got_offset);
9784 g_ptr_array_free (info->got_patches, TRUE);
9788 acfg_free (MonoAotCompile *acfg)
9792 mono_img_writer_destroy (acfg->w);
9793 for (i = 0; i < acfg->nmethods; ++i)
9795 g_free (acfg->cfgs [i]);
9796 g_free (acfg->cfgs);
9797 g_free (acfg->static_linking_symbol);
9798 g_free (acfg->got_symbol);
9799 g_free (acfg->plt_symbol);
9800 g_ptr_array_free (acfg->methods, TRUE);
9801 g_ptr_array_free (acfg->image_table, TRUE);
9802 g_ptr_array_free (acfg->globals, TRUE);
9803 g_ptr_array_free (acfg->unwind_ops, TRUE);
9804 g_hash_table_destroy (acfg->method_indexes);
9805 g_hash_table_destroy (acfg->method_depth);
9806 g_hash_table_destroy (acfg->plt_offset_to_entry);
9807 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9808 if (acfg->patch_to_plt_entry [i])
9809 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9811 g_free (acfg->patch_to_plt_entry);
9812 g_hash_table_destroy (acfg->method_to_cfg);
9813 g_hash_table_destroy (acfg->token_info_hash);
9814 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9815 g_hash_table_destroy (acfg->image_hash);
9816 g_hash_table_destroy (acfg->unwind_info_offsets);
9817 g_hash_table_destroy (acfg->method_label_hash);
9818 g_hash_table_destroy (acfg->export_names);
9819 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9820 g_hash_table_destroy (acfg->klass_blob_hash);
9821 g_hash_table_destroy (acfg->method_blob_hash);
9822 got_info_free (&acfg->got_info);
9823 got_info_free (&acfg->llvm_got_info);
9824 mono_mempool_destroy (acfg->mempool);
9828 #define WRAPPER(e,n) n,
9829 static const char* const
9830 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9831 #include "mono/metadata/wrapper-types.h"
9835 static G_GNUC_UNUSED const char*
9836 get_wrapper_type_name (int type)
9838 return wrapper_type_names [type];
9844 static void aot_dump (MonoAotCompile *acfg)
9850 mono_json_writer_init (&writer);
9852 mono_json_writer_object_begin(&writer);
9855 mono_json_writer_indent (&writer);
9856 mono_json_writer_object_key(&writer, "methods");
9857 mono_json_writer_array_begin (&writer);
9860 for (i = 0; i < acfg->nmethods; ++i) {
9865 cfg = acfg->cfgs [i];
9869 method = cfg->orig_method;
9871 mono_json_writer_indent (&writer);
9872 mono_json_writer_object_begin(&writer);
9874 mono_json_writer_indent (&writer);
9875 mono_json_writer_object_key(&writer, "name");
9876 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9878 mono_json_writer_indent (&writer);
9879 mono_json_writer_object_key(&writer, "signature");
9880 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
9882 mono_json_writer_indent (&writer);
9883 mono_json_writer_object_key(&writer, "code_size");
9884 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9886 klass = method->klass;
9888 mono_json_writer_indent (&writer);
9889 mono_json_writer_object_key(&writer, "class");
9890 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9892 mono_json_writer_indent (&writer);
9893 mono_json_writer_object_key(&writer, "namespace");
9894 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9896 mono_json_writer_indent (&writer);
9897 mono_json_writer_object_key(&writer, "wrapper_type");
9898 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9900 mono_json_writer_indent_pop (&writer);
9901 mono_json_writer_indent (&writer);
9902 mono_json_writer_object_end (&writer);
9903 mono_json_writer_printf (&writer, ",\n");
9906 mono_json_writer_indent_pop (&writer);
9907 mono_json_writer_indent (&writer);
9908 mono_json_writer_array_end (&writer);
9909 mono_json_writer_printf (&writer, ",\n");
9913 mono_json_writer_indent_push (&writer);
9914 mono_json_writer_indent (&writer);
9915 mono_json_writer_object_key(&writer, "plt");
9916 mono_json_writer_array_begin (&writer);
9918 for (i = 0; i < acfg->plt_offset; ++i) {
9919 MonoPltEntry *plt_entry = NULL;
9924 * The first plt entry is unused.
9928 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9931 mono_json_writer_indent (&writer);
9932 mono_json_writer_printf (&writer, "{ ");
9933 mono_json_writer_object_key(&writer, "symbol");
9934 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9937 mono_json_writer_indent_pop (&writer);
9938 mono_json_writer_indent (&writer);
9939 mono_json_writer_array_end (&writer);
9940 mono_json_writer_printf (&writer, ",\n");
9945 mono_json_writer_indent_push (&writer);
9946 mono_json_writer_indent (&writer);
9947 mono_json_writer_object_key(&writer, "got");
9948 mono_json_writer_array_begin (&writer);
9950 mono_json_writer_indent_push (&writer);
9951 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9952 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9954 mono_json_writer_indent (&writer);
9955 mono_json_writer_printf (&writer, "{ ");
9956 mono_json_writer_object_key(&writer, "patch_name");
9957 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9960 mono_json_writer_indent_pop (&writer);
9961 mono_json_writer_indent (&writer);
9962 mono_json_writer_array_end (&writer);
9963 mono_json_writer_printf (&writer, ",\n");
9966 mono_json_writer_indent_pop (&writer);
9967 mono_json_writer_indent (&writer);
9968 mono_json_writer_object_end (&writer);
9970 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9971 dumpfile = fopen (dumpname, "w+");
9974 fprintf (dumpfile, "%s", writer.text->str);
9977 mono_json_writer_destroy (&writer);
9980 static const char *preinited_jit_icalls[] = {
9981 "mono_aot_init_llvm_method",
9982 "mono_aot_init_gshared_method_this",
9983 "mono_aot_init_gshared_method_mrgctx",
9984 "mono_aot_init_gshared_method_vtable",
9985 "mono_llvm_throw_corlib_exception",
9986 "mono_init_vtable_slot",
9987 "mono_helper_ldstr_mscorlib"
9991 add_preinit_got_slots (MonoAotCompile *acfg)
9997 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9998 * during method initialization etc.
10001 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10002 ji->type = MONO_PATCH_INFO_IMAGE;
10003 ji->data.image = acfg->image;
10004 get_got_offset (acfg, FALSE, ji);
10005 get_got_offset (acfg, TRUE, ji);
10007 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10008 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10009 get_got_offset (acfg, FALSE, ji);
10010 get_got_offset (acfg, TRUE, ji);
10012 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10013 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10014 get_got_offset (acfg, FALSE, ji);
10015 get_got_offset (acfg, TRUE, ji);
10017 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10018 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10019 get_got_offset (acfg, FALSE, ji);
10020 get_got_offset (acfg, TRUE, ji);
10022 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10023 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10024 get_got_offset (acfg, FALSE, ji);
10025 get_got_offset (acfg, TRUE, ji);
10027 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10028 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10029 get_got_offset (acfg, FALSE, ji);
10030 get_got_offset (acfg, TRUE, ji);
10032 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10033 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10034 get_got_offset (acfg, FALSE, ji);
10035 get_got_offset (acfg, TRUE, ji);
10037 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10038 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10039 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10040 ji->data.name = preinited_jit_icalls [i];
10041 get_got_offset (acfg, FALSE, ji);
10042 get_got_offset (acfg, TRUE, ji);
10045 acfg->nshared_got_entries = acfg->got_offset;
10049 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10051 MonoImage *image = ass->image;
10054 MonoAotCompile *acfg;
10055 char *outfile_name, *tmp_outfile_name, *p;
10056 char llvm_stats_msg [256];
10060 acfg = acfg_create (ass, opts);
10062 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10063 acfg->aot_opts.write_symbols = TRUE;
10064 acfg->aot_opts.ntrampolines = 1024;
10065 acfg->aot_opts.nrgctx_trampolines = 1024;
10066 acfg->aot_opts.nimt_trampolines = 128;
10067 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10068 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
10069 acfg->aot_opts.llvm_path = g_strdup ("");
10070 acfg->aot_opts.temp_path = g_strdup ("");
10072 acfg->aot_opts.use_trampolines_page = TRUE;
10075 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10077 if (acfg->aot_opts.logfile) {
10078 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10081 if (acfg->aot_opts.data_outfile) {
10082 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10083 if (!acfg->data_outfile) {
10084 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10087 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10090 //acfg->aot_opts.print_skipped_methods = TRUE;
10092 #if !defined(ENABLE_GSHAREDVT)
10093 if (opts & MONO_OPT_GSHAREDVT) {
10094 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10099 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10100 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10101 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10106 if (acfg->aot_opts.llvm_only) {
10107 #ifndef ENABLE_GSHAREDVT
10108 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with --enable-gsharedvt.\n");
10113 #if defined(ENABLE_GSHAREDVT) && defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10114 acfg->opts |= MONO_OPT_GSHAREDVT;
10115 opts |= MONO_OPT_GSHAREDVT;
10118 if (opts & MONO_OPT_GSHAREDVT)
10119 mono_set_generic_sharing_vt_supported (TRUE);
10121 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10123 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10124 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10125 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10130 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10131 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10135 if (acfg->aot_opts.static_link)
10136 acfg->aot_opts.asm_writer = TRUE;
10138 if (acfg->aot_opts.soft_debug) {
10139 MonoDebugOptions *opt = mini_get_debug_options ();
10141 opt->mdb_optimizations = TRUE;
10142 opt->gen_sdb_seq_points = TRUE;
10144 if (!mono_debug_enabled ()) {
10145 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10148 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10151 if (mono_use_llvm || acfg->aot_opts.llvm) {
10153 acfg->aot_opts.asm_writer = TRUE;
10154 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10156 if (acfg->aot_opts.soft_debug) {
10157 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10163 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10164 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10169 * Emit all LLVM code into a separate assembly/object file and link with it
10172 if (!acfg->aot_opts.asm_only) {
10173 acfg->llvm_owriter = TRUE;
10174 } else if (acfg->aot_opts.llvm_outfile) {
10175 int len = strlen (acfg->aot_opts.llvm_outfile);
10177 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10178 acfg->llvm_owriter = TRUE;
10182 if (mono_aot_mode_is_full (&acfg->aot_opts))
10183 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10185 if (mono_threads_is_coop_enabled ())
10186 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10188 if (acfg->aot_opts.instances_logfile_path) {
10189 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10190 if (!acfg->instances_logfile) {
10191 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10196 load_profile_files (acfg);
10198 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10199 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10200 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10202 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10203 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10204 if (acfg->opts & MONO_OPT_GSHAREDVT)
10205 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10208 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10212 if (acfg->llvm && acfg->thumb_mixed)
10213 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10214 if (acfg->aot_opts.llvm_only)
10215 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10217 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10218 /* Get rid of characters which cannot occur in symbols */
10219 for (p = acfg->assembly_name_sym; *p; ++p) {
10220 if (!(isalnum (*p) || *p == '_'))
10224 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10225 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10226 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10228 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10229 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10232 acfg->method_index = 1;
10234 if (mono_aot_mode_is_full (&acfg->aot_opts))
10235 mono_set_partial_sharing_supported (TRUE);
10237 res = collect_methods (acfg);
10241 acfg->cfgs_size = acfg->methods->len + 32;
10242 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10244 /* PLT offset 0 is reserved for the PLT trampoline */
10245 acfg->plt_offset = 1;
10246 add_preinit_got_slots (acfg);
10251 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10257 compile_methods (acfg);
10261 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10267 if (acfg->aot_opts.asm_only) {
10268 if (acfg->aot_opts.outfile) {
10269 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10270 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10272 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10273 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10275 g_assert (acfg->aot_opts.llvm_outfile);
10276 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10277 if (acfg->llvm_owriter)
10278 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10280 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10282 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10283 g_strdup_printf ("%s", "temp") :
10284 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10286 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10287 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10288 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10293 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10294 if (acfg->aot_opts.outfile)
10295 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10297 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10298 acfg->fp = fopen (acfg->tmpfname, "w+");
10300 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10301 acfg->fp = fdopen (i, "w+");
10303 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10304 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10308 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10310 tmp_outfile_name = NULL;
10311 outfile_name = NULL;
10313 /* Compute symbols for methods */
10314 for (i = 0; i < acfg->nmethods; ++i) {
10315 if (acfg->cfgs [i]) {
10316 MonoCompile *cfg = acfg->cfgs [i];
10317 int method_index = get_method_index (acfg, cfg->orig_method);
10319 if (COMPILE_LLVM (cfg))
10320 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10321 else if (acfg->global_symbols || acfg->llvm)
10322 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10324 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10325 cfg->asm_debug_symbol = cfg->asm_symbol;
10329 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
10331 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10332 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
10333 * .byte directives.
10335 //acfg->gas_line_numbers = TRUE;
10338 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10339 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10340 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10343 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10347 mono_img_writer_emit_start (acfg->w);
10350 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10356 emit_extra_methods (acfg);
10358 emit_trampolines (acfg);
10360 emit_class_name_table (acfg);
10362 emit_got_info (acfg, FALSE);
10364 emit_got_info (acfg, TRUE);
10366 emit_exception_info (acfg);
10368 emit_unwind_info (acfg);
10370 emit_class_info (acfg);
10374 emit_image_table (acfg);
10380 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10383 const char *gc_name = mono_gc_get_gc_name ();
10384 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10389 emit_objc_selectors (acfg);
10391 emit_globals (acfg);
10393 emit_file_info (acfg);
10396 emit_dwarf_info (acfg);
10397 mono_dwarf_writer_close (acfg->dwarf);
10400 emit_mem_end (acfg);
10402 if (acfg->need_pt_gnu_stack) {
10403 /* This is required so the .so doesn't have an executable stack */
10404 /* The bin writer already emits this */
10405 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10408 if (acfg->aot_opts.data_outfile)
10409 fclose (acfg->data_outfile);
10415 res = emit_llvm_file (acfg);
10423 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10426 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10428 strcpy (llvm_stats_msg, "");
10430 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;
10432 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",
10433 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10434 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10435 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10436 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10437 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10438 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,
10439 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10440 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10441 (int)(acfg->got_offset * sizeof (gpointer)));
10442 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10443 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10445 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10446 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10447 if (acfg->stats.genericcount)
10448 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10449 if (acfg->stats.abscount)
10450 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10451 if (acfg->stats.lmfcount)
10452 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10453 if (acfg->stats.ocount)
10454 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10458 res = mono_img_writer_emit_writeout (acfg->w);
10463 res = compile_asm (acfg);
10470 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10472 if (acfg->aot_opts.stats) {
10475 aot_printf (acfg, "GOT slot distribution:\n");
10476 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10477 if (acfg->stats.got_slot_types [i])
10478 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]);
10479 aot_printf (acfg, "\nMethod stats:\n");
10480 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10481 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10482 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10483 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10486 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);
10488 if (acfg->aot_opts.dump_json)
10501 mono_aot_readonly_field_override (MonoClassField *field)
10507 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10513 mono_aot_is_shared_got_offset (int offset)