3 * mono Ahead of Time compiler
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
8 * Johan Lorensson (lateralusx.github@gmail.com)
10 * (C) 2002 Ximian, Inc.
11 * Copyright 2003-2011 Novell, Inc
12 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 #include <sys/types.h>
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/utils/mono-logger-internals.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-time.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-rand.h>
57 #include <mono/utils/json.h>
58 #include <mono/utils/mono-threads-coop.h>
59 #include <mono/profiler/mono-profiler-aot.h>
60 #include <mono/utils/w32api.h>
62 #include "aot-compiler.h"
63 #include "seq-points.h"
64 #include "image-writer.h"
65 #include "dwarfwriter.h"
67 #include "mini-llvm.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
72 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
73 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
74 #define TARGET_X86_64_WIN32_MSVC
77 #if defined(TARGET_X86_64_WIN32_MSVC)
78 #define TARGET_WIN32_MSVC
81 #if defined(__linux__) || defined(__native_client_codegen__)
82 #define RODATA_SECT ".rodata"
83 #elif defined(TARGET_MACH)
84 #define RODATA_SECT ".section __TEXT, __const"
85 #elif defined(TARGET_WIN32_MSVC)
86 #define RODATA_SECT ".rdata"
88 #define RODATA_SECT ".text"
91 #define TV_DECLARE(name) gint64 name
92 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
93 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
95 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
96 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
97 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
104 typedef struct ClassProfileData ClassProfileData;
108 ClassProfileData **argv;
109 MonoGenericInst *inst;
112 struct ClassProfileData {
113 ImageProfileData *image;
115 GInstProfileData *inst;
120 ClassProfileData *klass;
125 GInstProfileData *inst;
130 GHashTable *images, *classes, *ginsts, *methods;
133 /* predefined values for static readonly fields without needed to run the .cctor */
134 typedef struct _ReadOnlyValue ReadOnlyValue;
135 struct _ReadOnlyValue {
138 int type; /* to be used later for typechecking to prevent user errors */
147 static ReadOnlyValue *readonly_values;
149 typedef struct MonoAotOptions {
153 GList *profile_files;
155 gboolean write_symbols;
156 gboolean metadata_only;
157 gboolean bind_to_runtime_version;
160 gboolean static_link;
164 gboolean dwarf_debug;
166 gboolean log_generics;
167 gboolean log_instances;
168 gboolean gen_msym_dir;
169 char *gen_msym_dir_path;
170 gboolean direct_pinvoke;
171 gboolean direct_icalls;
172 gboolean no_direct_calls;
173 gboolean use_trampolines_page;
174 gboolean no_instances;
180 int nrgctx_trampolines;
181 int nimt_trampolines;
182 int ngsharedvt_arg_trampolines;
183 int nrgctx_fetch_trampolines;
184 gboolean print_skipped_methods;
192 char *instances_logfile_path;
195 gboolean profile_only;
200 METHOD_CAT_GSHAREDVT,
206 typedef struct MonoAotStats {
207 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
208 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
209 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
210 int got_slots, offsets_size;
211 int method_categories [METHOD_CAT_NUM];
212 int got_slot_types [MONO_PATCH_INFO_NUM];
213 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
214 int jit_time, gen_time, link_time;
217 typedef struct GotInfo {
218 GHashTable *patch_to_got_offset;
219 GHashTable **patch_to_got_offset_by_type;
220 GPtrArray *got_patches;
223 typedef struct MonoAotCompile {
226 GHashTable *method_indexes;
227 GHashTable *method_depth;
230 GHashTable **patch_to_plt_entry;
231 GHashTable *plt_offset_to_entry;
232 //GHashTable *patch_to_got_offset;
233 //GHashTable **patch_to_got_offset_by_type;
234 //GPtrArray *got_patches;
235 GotInfo got_info, llvm_got_info;
236 GHashTable *image_hash;
237 GHashTable *method_to_cfg;
238 GHashTable *token_info_hash;
239 GHashTable *method_to_pinvoke_import;
240 GPtrArray *extra_methods;
241 GPtrArray *image_table;
243 GPtrArray *method_order;
244 GHashTable *export_names;
245 /* Maps MonoClass* -> blob offset */
246 GHashTable *klass_blob_hash;
247 /* Maps MonoMethod* -> blob offset */
248 GHashTable *method_blob_hash;
249 GHashTable *gsharedvt_in_signatures;
250 GHashTable *gsharedvt_out_signatures;
251 guint32 *plt_got_info_offsets;
252 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
253 /* Number of GOT entries reserved for trampolines */
254 guint32 num_trampoline_got_entries;
255 guint32 tramp_page_size;
257 guint32 table_offsets [MONO_AOT_TABLE_NUM];
258 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
259 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
260 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
261 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
263 MonoAotOptions aot_opts;
267 MonoMemPool *mempool;
270 char *static_linking_symbol;
272 gboolean gas_line_numbers;
273 /* Whenever to emit an object file directly from llc */
274 gboolean llvm_owriter;
275 gboolean llvm_owriter_supported;
277 MonoDwarfWriter *dwarf;
284 GHashTable *unwind_info_offsets;
285 GPtrArray *unwind_ops;
286 guint32 unwind_info_offset;
289 char *llvm_got_symbol;
291 char *llvm_eh_frame_symbol;
292 GHashTable *method_label_hash;
293 const char *temp_prefix;
294 const char *user_symbol_prefix;
295 const char *llvm_label_prefix;
296 const char *inst_directive;
298 guint32 label_generator;
300 gboolean has_jitted_code;
301 MonoAotFileFlags flags;
302 MonoDynamicStream blob;
303 gboolean blob_closed;
304 GHashTable *typespec_classes;
307 char *assembly_name_sym;
308 GHashTable *plt_entry_debug_sym_cache;
309 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
310 GHashTable *ginst_hash;
311 GHashTable *dwarf_ln_filenames;
312 gboolean global_symbols;
313 int objc_selector_index, objc_selector_index_2;
314 GPtrArray *objc_selectors;
315 GHashTable *objc_selector_to_index;
317 GHashTable *profile_methods;
319 FILE *instances_logfile;
327 char *symbol, *llvm_symbol, *debug_sym;
329 gboolean jit_used, llvm_used;
332 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
333 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
335 /* This points to the current acfg in LLVM mode */
336 static MonoAotCompile *llvm_acfg;
338 #ifdef HAVE_ARRAY_ELEM_INIT
339 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
340 #define MSGSTRFIELD1(line) str##line
341 static const struct msgstr_t {
342 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
343 #include "patch-info.h"
346 #define PATCH_INFO(a,b) b,
347 #include "patch-info.h"
350 static const gint16 opidx [] = {
351 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
352 #include "patch-info.h"
356 static G_GNUC_UNUSED const char*
357 get_patch_name (int info)
359 return (const char*)&opstr + opidx [info];
363 #define PATCH_INFO(a,b) b,
364 static const char* const
365 patch_types [MONO_PATCH_INFO_NUM + 1] = {
366 #include "patch-info.h"
370 static G_GNUC_UNUSED const char*
371 get_patch_name (int info)
373 return patch_types [info];
379 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
382 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
385 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
388 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
391 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
397 output = acfg->logfile;
401 va_start (args, format);
402 vfprintf (output, format, args);
407 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
413 output = acfg->logfile;
417 va_start (args, format);
418 vfprintf (output, format, args);
423 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
428 if (mono_error_ok (error))
432 output = acfg->logfile;
436 va_start (args, format);
437 vfprintf (output, format, args);
439 mono_error_cleanup (error);
441 g_error ("FullAOT cannot continue if there are loader errors");
444 /* Wrappers around the image writer functions */
446 #define MAX_SYMBOL_SIZE 256
448 static inline const char *
449 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
451 gsize needed_size = length;
453 g_assert (NULL != symbol);
454 g_assert (NULL != mangled_symbol);
455 g_assert (0 != length);
457 #if defined(TARGET_WIN32) && defined(TARGET_X86)
458 if (symbol && '_' != symbol [0]) {
459 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
461 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
464 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
467 g_assert (0 <= needed_size && needed_size < length);
468 return mangled_symbol;
472 mangle_symbol_alloc (const char * symbol)
474 g_assert (NULL != symbol);
476 #if defined(TARGET_WIN32) && defined(TARGET_X86)
477 if (symbol && '_' != symbol [0]) {
478 return g_strdup_printf ("_%s", symbol);
481 return g_strdup_printf ("%s", symbol);
484 return g_strdup_printf ("%s", symbol);
489 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
491 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
494 #if defined(TARGET_WIN32) && defined(TARGET_X86)
497 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
499 const char * mangled_symbol_name = name;
500 char * mangled_symbol_name_alloc = NULL;
503 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
504 mangled_symbol_name = mangled_symbol_name_alloc;
507 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
508 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
510 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
512 if (NULL != mangled_symbol_name_alloc) {
513 g_free (mangled_symbol_name_alloc);
520 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
522 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
528 emit_label (MonoAotCompile *acfg, const char *name)
530 mono_img_writer_emit_label (acfg->w, name);
534 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
536 mono_img_writer_emit_bytes (acfg->w, buf, size);
540 emit_string (MonoAotCompile *acfg, const char *value)
542 mono_img_writer_emit_string (acfg->w, value);
546 emit_line (MonoAotCompile *acfg)
548 mono_img_writer_emit_line (acfg->w);
552 emit_alignment (MonoAotCompile *acfg, int size)
554 mono_img_writer_emit_alignment (acfg->w, size);
558 emit_alignment_code (MonoAotCompile *acfg, int size)
560 if (acfg->align_pad_value)
561 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
563 mono_img_writer_emit_alignment (acfg->w, size);
567 emit_padding (MonoAotCompile *acfg, int size)
572 if (acfg->align_pad_value) {
573 for (i = 0; i < 16; ++i)
574 buf [i] = acfg->align_pad_value;
576 memset (buf, 0, sizeof (buf));
579 for (i = 0; i < size; i += 16) {
581 emit_bytes (acfg, buf, size - i);
583 emit_bytes (acfg, buf, 16);
588 emit_pointer (MonoAotCompile *acfg, const char *target)
590 mono_img_writer_emit_pointer (acfg->w, target);
594 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
596 if (prefix [0] != '\0') {
597 char *s = g_strdup_printf ("%s%s", prefix, target);
598 mono_img_writer_emit_pointer (acfg->w, s);
601 mono_img_writer_emit_pointer (acfg->w, target);
606 emit_int16 (MonoAotCompile *acfg, int value)
608 mono_img_writer_emit_int16 (acfg->w, value);
612 emit_int32 (MonoAotCompile *acfg, int value)
614 mono_img_writer_emit_int32 (acfg->w, value);
618 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
620 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
624 emit_zero_bytes (MonoAotCompile *acfg, int num)
626 mono_img_writer_emit_zero_bytes (acfg->w, num);
630 emit_byte (MonoAotCompile *acfg, guint8 val)
632 mono_img_writer_emit_byte (acfg->w, val);
635 #if defined(TARGET_WIN32) && defined(TARGET_X86)
637 static G_GNUC_UNUSED void
638 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
640 const char * mangled_symbol_name = name;
641 char * mangled_symbol_name_alloc = NULL;
643 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
644 mangled_symbol_name = mangled_symbol_name_alloc;
646 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
647 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
649 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
651 if (NULL != mangled_symbol_name_alloc) {
652 g_free (mangled_symbol_name_alloc);
658 static G_GNUC_UNUSED void
659 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
661 mono_img_writer_emit_global (acfg->w, name, func);
666 static inline gboolean
667 link_shared_library (MonoAotCompile *acfg)
669 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
672 static inline gboolean
673 add_to_global_symbol_table (MonoAotCompile *acfg)
675 #ifdef TARGET_WIN32_MSVC
676 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
678 return acfg->aot_opts.no_dlsym;
683 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
685 if (add_to_global_symbol_table (acfg))
686 g_ptr_array_add (acfg->globals, g_strdup (name));
688 if (acfg->aot_opts.no_dlsym) {
689 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
691 emit_global_inner (acfg, name, func);
696 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
698 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
701 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
703 emit_info_symbol (MonoAotCompile *acfg, const char *name)
705 char symbol [MAX_SYMBOL_SIZE];
708 emit_label (acfg, name);
709 /* LLVM generated code references this */
710 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
711 emit_label (acfg, symbol);
712 emit_global_inner (acfg, symbol, FALSE);
714 emit_label (acfg, name);
719 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
722 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
726 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
728 /* On apple, all symbols need to be aligned to avoid warnings from ld */
729 emit_alignment (acfg, 4);
731 mono_img_writer_emit_label (acfg->w, name);
732 mono_img_writer_emit_string (acfg->w, value);
735 static G_GNUC_UNUSED void
736 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
739 guint8 b = value & 0x7f;
741 if (value != 0) /* more bytes to come */
747 static G_GNUC_UNUSED void
748 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
751 gboolean negative = (value < 0);
758 /* the following is unnecessary if the
759 * implementation of >>= uses an arithmetic rather
760 * than logical shift for a signed left operand
764 value |= - ((gint64)1 <<(size - 7));
765 /* sign bit of byte is second high order bit (0x40) */
766 if ((value == 0 && !(byte & 0x40)) ||
767 (value == -1 && (byte & 0x40)))
771 emit_byte (acfg, byte);
775 static G_GNUC_UNUSED void
776 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
781 guint8 b = value & 0x7f;
783 if (value != 0) /* more bytes to come */
791 static G_GNUC_UNUSED void
792 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
795 gboolean negative = (value < 0);
803 /* the following is unnecessary if the
804 * implementation of >>= uses an arithmetic rather
805 * than logical shift for a signed left operand
809 value |= - (1 <<(size - 7));
810 /* sign bit of byte is second high order bit (0x40) */
811 if ((value == 0 && !(byte & 0x40)) ||
812 (value == -1 && (byte & 0x40)))
823 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
826 buf [0] = (val >> 0) & 0xff;
827 buf [1] = (val >> 8) & 0xff;
828 buf [2] = (val >> 16) & 0xff;
829 buf [3] = (val >> 24) & 0xff;
835 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
837 buf [0] = (val >> 0) & 0xff;
838 buf [1] = (val >> 8) & 0xff;
844 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
846 int len = strlen (s);
848 memcpy (buf, s, len + 1);
849 *endbuf = buf + len + 1;
853 emit_unset_mode (MonoAotCompile *acfg)
855 mono_img_writer_emit_unset_mode (acfg->w);
858 static G_GNUC_UNUSED void
859 emit_set_thumb_mode (MonoAotCompile *acfg)
861 emit_unset_mode (acfg);
862 fprintf (acfg->fp, ".code 16\n");
865 static G_GNUC_UNUSED void
866 emit_set_arm_mode (MonoAotCompile *acfg)
868 emit_unset_mode (acfg);
869 fprintf (acfg->fp, ".code 32\n");
873 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
878 g_assert (size % 4 == 0);
879 emit_unset_mode (acfg);
880 for (i = 0; i < size; i += 4)
881 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
883 emit_bytes (acfg, buf, size);
887 /* ARCHITECTURE SPECIFIC CODE */
889 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
890 #define EMIT_DWARF_INFO 1
893 #ifdef TARGET_WIN32_MSVC
894 #undef EMIT_DWARF_INFO
897 #if defined(TARGET_ARM)
898 #define AOT_FUNC_ALIGNMENT 4
900 #define AOT_FUNC_ALIGNMENT 16
903 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
904 #define PPC_LD_OP "ld"
905 #define PPC_LDX_OP "ldx"
907 #define PPC_LD_OP "lwz"
908 #define PPC_LDX_OP "lwzx"
911 #ifdef TARGET_X86_64_WIN32_MSVC
912 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
914 #define AOT_TARGET_STR "AMD64"
919 #define AOT_TARGET_STR "ARM (MACH)"
921 #define AOT_TARGET_STR "ARM (!MACH)"
927 #define AOT_TARGET_STR "ARM64 (MACH)"
929 #define AOT_TARGET_STR "ARM64 (!MACH)"
933 #ifdef TARGET_POWERPC64
934 #ifdef __mono_ilp32__
935 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
937 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
940 #ifdef TARGET_POWERPC
941 #ifdef __mono_ilp32__
942 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
944 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
951 #define AOT_TARGET_STR "X86 (WIN32)"
952 #elif defined(__native_client_codegen__)
953 #define AOT_TARGET_STR "X86 (native client codegen)"
955 #define AOT_TARGET_STR "X86 (!native client codegen)"
959 #ifndef AOT_TARGET_STR
960 #define AOT_TARGET_STR ""
964 arch_init (MonoAotCompile *acfg)
966 acfg->llc_args = g_string_new ("");
967 acfg->as_args = g_string_new ("");
968 acfg->llvm_owriter_supported = TRUE;
971 * The prefix LLVM likes to put in front of symbol names on darwin.
972 * The mach-os specs require this for globals, but LLVM puts them in front of all
973 * symbols. We need to handle this, since we need to refer to LLVM generated
976 acfg->llvm_label_prefix = "";
977 acfg->user_symbol_prefix = "";
979 #if defined(TARGET_X86)
980 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
983 #if defined(TARGET_AMD64)
984 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
986 acfg->align_pad_value = 0x90;
990 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
991 g_string_append (acfg->llc_args, "-mattr=+v6");
993 #if defined(ARM_FPU_VFP_HARD)
994 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
995 g_string_append (acfg->as_args, " -mfpu=vfp3");
996 #elif defined(ARM_FPU_VFP)
997 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
998 g_string_append (acfg->as_args, " -mfpu=vfp3");
1000 g_string_append (acfg->llc_args, " -soft-float");
1003 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1004 acfg->thumb_mixed = TRUE;
1006 if (acfg->aot_opts.mtriple)
1007 mono_arch_set_target (acfg->aot_opts.mtriple);
1011 acfg->inst_directive = ".inst";
1012 if (acfg->aot_opts.mtriple)
1013 mono_arch_set_target (acfg->aot_opts.mtriple);
1017 acfg->user_symbol_prefix = "_";
1018 acfg->llvm_label_prefix = "_";
1019 acfg->inst_directive = ".word";
1020 acfg->need_no_dead_strip = TRUE;
1021 acfg->aot_opts.gnu_asm = TRUE;
1024 #if defined(__linux__) && !defined(TARGET_ARM)
1025 acfg->need_pt_gnu_stack = TRUE;
1029 acfg->global_symbols = TRUE;
1032 #ifdef TARGET_ANDROID
1033 acfg->llvm_owriter_supported = FALSE;
1040 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1042 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1046 g_assert (acfg->fp);
1047 emit_unset_mode (acfg);
1049 offset = (int)(got_slot * sizeof (gpointer));
1051 /* clang's integrated assembler */
1052 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1053 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1054 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1057 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1058 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1059 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1064 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1068 g_assert (acfg->fp);
1069 emit_unset_mode (acfg);
1071 /* ldr rt, target */
1072 reg = arm_get_ldr_lit_reg (code);
1074 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1075 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1076 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1082 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1084 g_assert (acfg->fp);
1085 emit_unset_mode (acfg);
1086 if (ji && ji->relocation == MONO_R_ARM64_B) {
1087 fprintf (acfg->fp, "b %s\n", target);
1090 g_assert (ji->relocation == MONO_R_ARM64_BL);
1091 fprintf (acfg->fp, "bl %s\n", target);
1097 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1101 /* ldr rt, target */
1102 reg = arm_get_ldr_lit_reg (code);
1103 arm64_emit_load_got_slot (acfg, reg, got_slot);
1108 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1110 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1111 fprintf (acfg->fp, "br x16\n");
1112 /* Used by mono_aot_get_plt_info_offset () */
1113 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1117 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1123 /* The common code */
1126 /* The trampoline address is in IP0 */
1127 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1128 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1129 /* Compute the data slot address */
1130 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1131 /* Trampoline argument */
1132 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1134 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1135 arm_brx (code, ARMREG_IP0);
1138 emit_code_bytes (acfg, buf, code - buf);
1144 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1150 count = (pagesize - common_tramp_size) / specific_tramp_size;
1151 for (i = 0; i < count; ++i) {
1153 arm_adrx (code, ARMREG_IP0, code);
1154 /* Branch to the generic code */
1155 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1156 /* This has to be 2 pointers long */
1159 g_assert (code - buf == specific_tramp_size);
1160 emit_code_bytes (acfg, buf, code - buf);
1165 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1169 guint8 *labels [16];
1170 int common_tramp_size;
1171 int specific_tramp_size = 2 * 8;
1175 if (!acfg->aot_opts.use_trampolines_page)
1179 /* Have to match the target pagesize */
1182 pagesize = mono_pagesize ();
1184 acfg->tramp_page_size = pagesize;
1186 /* The specific trampolines */
1187 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1188 emit_alignment (acfg, pagesize);
1189 emit_global (acfg, symbol, TRUE);
1190 emit_label (acfg, symbol);
1192 /* The common code */
1193 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1194 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1196 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1198 /* The rgctx trampolines */
1199 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1200 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1201 emit_alignment (acfg, pagesize);
1202 emit_global (acfg, symbol, TRUE);
1203 emit_label (acfg, symbol);
1205 /* The common code */
1206 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1207 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1209 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1211 /* The gsharedvt arg trampolines */
1212 /* These are the same as the specific trampolines */
1213 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1214 emit_alignment (acfg, pagesize);
1215 emit_global (acfg, symbol, TRUE);
1216 emit_label (acfg, symbol);
1218 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1219 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1221 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1223 /* The IMT trampolines */
1224 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1225 emit_alignment (acfg, pagesize);
1226 emit_global (acfg, symbol, TRUE);
1227 emit_label (acfg, symbol);
1231 /* The trampoline address is in IP0 */
1232 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1233 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1234 /* Compute the data slot address */
1235 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1236 /* Trampoline argument */
1237 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1239 /* Same as arch_emit_imt_trampoline () */
1241 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1242 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1244 arm_bcc (code, ARMCOND_EQ, 0);
1246 /* End-of-loop check */
1248 arm_cbzx (code, ARMREG_IP0, 0);
1251 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1252 arm_b (code, labels [0]);
1255 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1256 /* Load vtable slot addr */
1257 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1258 /* Load vtable slot */
1259 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1260 arm_brx (code, ARMREG_IP0);
1263 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1264 /* Load fail addr */
1265 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1266 arm_brx (code, ARMREG_IP0);
1268 emit_code_bytes (acfg, buf, code - buf);
1270 common_tramp_size = code - buf;
1271 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1273 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1277 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1279 /* Load argument from second GOT slot */
1280 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1281 /* Load generic trampoline address from first GOT slot */
1282 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1283 fprintf (acfg->fp, "br x16\n");
1284 *tramp_size = 7 * 4;
1288 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1290 emit_unset_mode (acfg);
1291 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1292 fprintf (acfg->fp, "b %s\n", call_target);
1296 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1298 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1300 /* Load argument from first GOT slot */
1301 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1302 /* Load generic trampoline address from second GOT slot */
1303 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1304 fprintf (acfg->fp, "br x16\n");
1305 *tramp_size = 7 * 4;
1309 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1312 guint8 *code, *labels [16];
1314 /* Load parameter from GOT slot into ip1 */
1315 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1319 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1320 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1322 arm_bcc (code, ARMCOND_EQ, 0);
1324 /* End-of-loop check */
1326 arm_cbzx (code, ARMREG_IP0, 0);
1329 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1330 arm_b (code, labels [0]);
1333 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1334 /* Load vtable slot addr */
1335 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1336 /* Load vtable slot */
1337 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1338 arm_brx (code, ARMREG_IP0);
1341 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1342 /* Load fail addr */
1343 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1344 arm_brx (code, ARMREG_IP0);
1346 emit_code_bytes (acfg, buf, code - buf);
1348 *tramp_size = code - buf + (3 * 4);
1352 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1354 /* Similar to the specific trampolines, but the address is in the second slot */
1355 /* Load argument from first GOT slot */
1356 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1357 /* Load generic trampoline address from second GOT slot */
1358 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1359 fprintf (acfg->fp, "br x16\n");
1360 *tramp_size = 7 * 4;
1366 #ifdef MONO_ARCH_AOT_SUPPORTED
1368 * arch_emit_direct_call:
1370 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1374 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1376 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1377 /* Need to make sure this is exactly 5 bytes long */
1378 emit_unset_mode (acfg);
1379 fprintf (acfg->fp, "call %s\n", target);
1381 #elif defined(TARGET_ARM)
1382 emit_unset_mode (acfg);
1384 fprintf (acfg->fp, "blx %s\n", target);
1386 fprintf (acfg->fp, "bl %s\n", target);
1388 #elif defined(TARGET_ARM64)
1389 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1390 #elif defined(TARGET_POWERPC)
1391 emit_unset_mode (acfg);
1392 fprintf (acfg->fp, "bl %s\n", target);
1395 g_assert_not_reached ();
1402 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1404 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1405 * in in the 2. slot of every GOT, and require every method to place the GOT
1406 * address in r30, even when it doesn't access the GOT otherwise. This way,
1407 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1412 * PPC64 uses function descriptors which greatly complicate all code, since
1413 * these are used very inconsistently in the runtime. Some functions like
1414 * mono_compile_method () return ftn descriptors, while others like the
1415 * trampoline creation functions do not.
1416 * We assume that all GOT slots contain function descriptors, and create
1417 * descriptors in aot-runtime.c when needed.
1418 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1419 * from function descriptors, we could do the same, but it would require
1420 * rewriting all the ppc/aot code to handle function descriptors properly.
1421 * So instead, we use the same approach as on PPC32.
1422 * This is a horrible mess, but fixing it would probably lead to an even bigger
1428 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1431 #ifdef MONO_ARCH_AOT_SUPPORTED
1433 * arch_emit_got_offset:
1435 * The memory pointed to by CODE should hold native code for computing the GOT
1436 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1437 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1440 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1442 #if defined(TARGET_POWERPC64)
1443 emit_unset_mode (acfg);
1445 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1446 * unsupported relocations. So we store the got address into the .Lgot_addr
1447 * symbol which is in the text segment, compute its address, and load it.
1449 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1450 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1451 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1452 fprintf (acfg->fp, "add 30, 30, 0\n");
1453 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1454 acfg->label_generator ++;
1456 #elif defined(TARGET_POWERPC)
1457 emit_unset_mode (acfg);
1458 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1459 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1460 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1461 acfg->label_generator ++;
1464 guint32 offset = mono_arch_get_patch_offset (code);
1465 emit_bytes (acfg, code, offset);
1466 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1468 *code_size = offset + 4;
1473 * arch_emit_got_access:
1475 * The memory pointed to by CODE should hold native code for loading a GOT
1476 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1477 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1480 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1483 /* mov reg, got+offset(%rip) */
1485 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1489 /* Decode reg, see amd64_mov_reg_membase () */
1490 rex_r = code [0] & AMD64_REX_R;
1491 g_assert (code [0] == 0x49 + rex_r);
1492 g_assert (code [1] == 0x8b);
1493 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1495 emit_unset_mode (acfg);
1496 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1499 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1500 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1501 *code_size = mono_arch_get_patch_offset (code) + 4;
1503 #elif defined(TARGET_X86)
1504 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1505 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1506 *code_size = mono_arch_get_patch_offset (code) + 4;
1507 #elif defined(TARGET_ARM)
1508 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1509 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1510 *code_size = mono_arch_get_patch_offset (code) + 4;
1511 #elif defined(TARGET_ARM64)
1512 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1513 arm64_emit_got_access (acfg, code, got_slot, code_size);
1514 #elif defined(TARGET_POWERPC)
1518 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1520 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1521 g_assert (code - buf == 8);
1522 emit_bytes (acfg, buf, code - buf);
1523 *code_size = code - buf;
1526 g_assert_not_reached ();
1532 #ifdef MONO_ARCH_AOT_SUPPORTED
1534 * arch_emit_objc_selector_ref:
1536 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1539 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1541 #if defined(TARGET_ARM)
1542 char symbol1 [MAX_SYMBOL_SIZE];
1543 char symbol2 [MAX_SYMBOL_SIZE];
1544 int lindex = acfg->objc_selector_index_2 ++;
1546 /* Emit ldr.imm/b */
1547 emit_bytes (acfg, code, 8);
1549 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1550 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1552 emit_label (acfg, symbol1);
1553 mono_img_writer_emit_unset_mode (acfg->w);
1554 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1557 #elif defined(TARGET_ARM64)
1558 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1560 g_assert_not_reached ();
1566 * arch_emit_plt_entry:
1568 * Emit code for the PLT entry.
1569 * The plt entry should look like this:
1570 * <indirect jump to GOT_SYMBOL + OFFSET>
1571 * <INFO_OFFSET embedded into the instruction stream>
1574 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1576 #if defined(TARGET_X86)
1577 /* jmp *<offset>(%ebx) */
1578 emit_byte (acfg, 0xff);
1579 emit_byte (acfg, 0xa3);
1580 emit_int32 (acfg, offset);
1581 /* Used by mono_aot_get_plt_info_offset */
1582 emit_int32 (acfg, info_offset);
1583 #elif defined(TARGET_AMD64)
1584 emit_unset_mode (acfg);
1585 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1586 /* Used by mono_aot_get_plt_info_offset */
1587 emit_int32 (acfg, info_offset);
1588 acfg->stats.plt_size += 10;
1589 #elif defined(TARGET_ARM)
1594 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1595 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1596 emit_bytes (acfg, buf, code - buf);
1597 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1598 /* Used by mono_aot_get_plt_info_offset */
1599 emit_int32 (acfg, info_offset);
1600 #elif defined(TARGET_ARM64)
1601 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1602 #elif defined(TARGET_POWERPC)
1603 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1604 emit_unset_mode (acfg);
1605 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1606 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1607 fprintf (acfg->fp, "add 11, 11, 30\n");
1608 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1609 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1610 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1611 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1613 fprintf (acfg->fp, "mtctr 11\n");
1614 fprintf (acfg->fp, "bctr\n");
1615 emit_int32 (acfg, info_offset);
1617 g_assert_not_reached ();
1622 * arch_emit_llvm_plt_entry:
1624 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1625 * This is only needed on arm to handle thumb interop.
1628 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1630 #if defined(TARGET_ARM)
1631 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1632 /* The caller already transitioned to thumb */
1633 /* The code below should be 12 bytes long */
1634 /* clang has trouble encoding these instructions, so emit the binary */
1636 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1637 /* thumb can't encode ld pc, [pc, ip] */
1638 fprintf (acfg->fp, "add ip, pc, ip\n");
1639 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1640 fprintf (acfg->fp, "bx ip\n");
1642 emit_set_thumb_mode (acfg);
1643 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1644 fprintf (acfg->fp, ".2byte 0x44fc\n");
1645 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1646 fprintf (acfg->fp, ".2byte 0x4760\n");
1647 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1648 emit_int32 (acfg, info_offset);
1649 emit_unset_mode (acfg);
1650 emit_set_arm_mode (acfg);
1652 g_assert_not_reached ();
1656 /* Save unwind_info in the module and emit the offset to the information at symbol */
1657 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1659 guint32 uw_offset, encoded_len;
1662 emit_section_change (acfg, RODATA_SECT, 0);
1663 emit_global (acfg, symbol, FALSE);
1664 emit_label (acfg, symbol);
1666 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1667 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1669 emit_int32 (acfg, uw_offset);
1673 * arch_emit_specific_trampoline_pages:
1675 * Emits a page full of trampolines: each trampoline uses its own address to
1676 * lookup both the generic trampoline code and the data argument.
1677 * This page can be remapped in process multiple times so we can get an
1678 * unlimited number of trampolines.
1679 * Specifically this implementation uses the following trick: two memory pages
1680 * are allocated, with the first containing the data and the second containing the trampolines.
1681 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1682 * implementation does all the lifting.
1683 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1684 * on the arm 32 bit system.
1687 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1689 #if defined(TARGET_ARM)
1692 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1694 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1695 GSList *unwind_ops = NULL;
1696 #define COMMON_TRAMP_SIZE 16
1697 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1698 int imm8, rot_amount;
1701 if (!acfg->aot_opts.use_trampolines_page)
1704 acfg->tramp_page_size = pagesize;
1706 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1707 emit_alignment (acfg, pagesize);
1708 emit_global (acfg, symbol, TRUE);
1709 emit_label (acfg, symbol);
1711 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1713 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1714 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1715 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1716 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1718 g_assert (code - buf == COMMON_TRAMP_SIZE);
1721 emit_bytes (acfg, buf, code - buf);
1723 for (i = 0; i < count; ++i) {
1725 ARM_PUSH (code, 0x5fff);
1727 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1728 g_assert (code - buf == 8);
1729 emit_bytes (acfg, buf, code - buf);
1732 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1733 * the instruction pointer address, so the generic trampoline at the start of the page
1734 * subtracts 4096 to get to the data page and loads the values
1735 * We again fit the generic trampiline in 16 bytes.
1737 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1738 emit_global (acfg, symbol, TRUE);
1739 emit_label (acfg, symbol);
1741 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1742 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1743 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1744 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1746 g_assert (code - buf == COMMON_TRAMP_SIZE);
1749 emit_bytes (acfg, buf, code - buf);
1751 for (i = 0; i < count; ++i) {
1753 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1755 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1756 g_assert (code - buf == 8);
1757 emit_bytes (acfg, buf, code - buf);
1761 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1763 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1764 emit_global (acfg, symbol, TRUE);
1765 emit_label (acfg, symbol);
1767 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1768 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1769 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1770 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1771 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1772 g_assert (code - buf == COMMON_TRAMP_SIZE);
1774 emit_bytes (acfg, buf, code - buf);
1776 for (i = 0; i < count; ++i) {
1778 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1780 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1781 g_assert (code - buf == 8);
1782 emit_bytes (acfg, buf, code - buf);
1785 /* now the imt trampolines: each specific trampolines puts in the ip register
1786 * the instruction pointer address, so the generic trampoline at the start of the page
1787 * subtracts 4096 to get to the data page and loads the values
1789 #define IMT_TRAMP_SIZE 72
1790 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1791 emit_global (acfg, symbol, TRUE);
1792 emit_label (acfg, symbol);
1794 /* Need at least two free registers, plus a slot for storing the pc */
1795 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1797 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1798 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1799 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1801 /* The IMT method is in v5, r0 has the imt array address */
1804 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1805 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1806 imt_found_check = code;
1807 ARM_B_COND (code, ARMCOND_EQ, 0);
1809 /* End-of-loop check */
1810 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1811 loop_end_check = code;
1812 ARM_B_COND (code, ARMCOND_EQ, 0);
1815 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1816 loop_branch_back = code;
1818 arm_patch (loop_branch_back, loop_start);
1821 arm_patch (imt_found_check, code);
1822 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1823 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1824 /* Save it to the third stack slot */
1825 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1826 /* Restore the registers and branch */
1827 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1830 arm_patch (loop_end_check, code);
1831 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1832 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1833 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1837 g_assert (code - buf == IMT_TRAMP_SIZE);
1838 emit_bytes (acfg, buf, code - buf);
1840 for (i = 0; i < count; ++i) {
1842 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1844 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1845 g_assert (code - buf == 8);
1846 emit_bytes (acfg, buf, code - buf);
1849 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1850 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1851 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1852 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1854 /* Unwind info for specifc trampolines */
1855 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1856 /* We unwind to the original caller, from the stack, since lr is clobbered */
1857 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1858 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1859 save_unwind_info (acfg, symbol, unwind_ops);
1860 mono_free_unwind_info (unwind_ops);
1862 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1863 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1864 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1865 save_unwind_info (acfg, symbol, unwind_ops);
1866 mono_free_unwind_info (unwind_ops);
1868 /* Unwind info for rgctx trampolines */
1869 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1870 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1871 save_unwind_info (acfg, symbol, unwind_ops);
1873 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1874 save_unwind_info (acfg, symbol, unwind_ops);
1875 mono_free_unwind_info (unwind_ops);
1877 /* Unwind info for gsharedvt trampolines */
1878 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1879 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1880 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1881 save_unwind_info (acfg, symbol, unwind_ops);
1882 mono_free_unwind_info (unwind_ops);
1884 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1885 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1886 save_unwind_info (acfg, symbol, unwind_ops);
1887 mono_free_unwind_info (unwind_ops);
1889 /* Unwind info for imt trampolines */
1890 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1891 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1892 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1893 save_unwind_info (acfg, symbol, unwind_ops);
1894 mono_free_unwind_info (unwind_ops);
1896 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1897 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1898 save_unwind_info (acfg, symbol, unwind_ops);
1899 mono_free_unwind_info (unwind_ops);
1900 #elif defined(TARGET_ARM64)
1901 arm64_emit_specific_trampoline_pages (acfg);
1906 * arch_emit_specific_trampoline:
1908 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1909 * two GOT slots which contain the generic trampoline address and the trampoline
1910 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1913 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1916 * The trampolines created here are variations of the specific
1917 * trampolines created in mono_arch_create_specific_trampoline (). The
1919 * - the generic trampoline address is taken from a got slot.
1920 * - the offset of the got slot where the trampoline argument is stored
1921 * is embedded in the instruction stream, and the generic trampoline
1922 * can load the argument by loading the offset, adding it to the
1923 * address of the trampoline to get the address of the got slot, and
1924 * loading the argument from there.
1925 * - all the trampolines should be of the same length.
1927 #if defined(TARGET_AMD64)
1928 /* This should be exactly 8 bytes long */
1930 /* call *<offset>(%rip) */
1932 emit_unset_mode (acfg);
1933 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1934 emit_zero_bytes (acfg, 2);
1936 emit_byte (acfg, '\x41');
1937 emit_byte (acfg, '\xff');
1938 emit_byte (acfg, '\x15');
1939 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1940 emit_zero_bytes (acfg, 1);
1942 #elif defined(TARGET_ARM)
1946 /* This should be exactly 20 bytes long */
1949 ARM_PUSH (code, 0x5fff);
1950 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1951 /* Load the value from the GOT */
1952 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1954 ARM_BLX_REG (code, ARMREG_R1);
1956 g_assert (code - buf == 16);
1959 emit_bytes (acfg, buf, code - buf);
1961 * Only one offset is needed, since the second one would be equal to the
1964 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1965 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1966 #elif defined(TARGET_ARM64)
1967 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1968 #elif defined(TARGET_POWERPC)
1976 * PPC has no ip relative addressing, so we need to compute the address
1977 * of the mscorlib got. That is slow and complex, so instead, we store it
1978 * in the second got slot of every aot image. The caller already computed
1979 * the address of its got and placed it into r30.
1981 emit_unset_mode (acfg);
1982 /* Load mscorlib got address */
1983 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1984 /* Load generic trampoline address */
1985 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1986 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1987 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1988 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1989 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1991 fprintf (acfg->fp, "mtctr 11\n");
1992 /* Load trampoline argument */
1993 /* On ppc, we pass it normally to the generic trampoline */
1994 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1995 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1996 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1997 /* Branch to generic trampoline */
1998 fprintf (acfg->fp, "bctr\n");
2000 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2001 *tramp_size = 10 * 4;
2003 *tramp_size = 9 * 4;
2005 #elif defined(TARGET_X86)
2009 /* Similar to the PPC code above */
2011 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2014 /* Load mscorlib got address */
2015 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2016 /* Push trampoline argument */
2017 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2018 /* Load generic trampoline address */
2019 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2020 /* Branch to generic trampoline */
2021 x86_jump_reg (code, X86_ECX);
2023 emit_bytes (acfg, buf, code - buf);
2026 g_assert (code - buf == *tramp_size);
2028 g_assert_not_reached ();
2033 * arch_emit_unbox_trampoline:
2035 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2036 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2039 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2041 #if defined(TARGET_AMD64)
2046 this_reg = mono_arch_get_this_arg_reg (NULL);
2048 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2050 emit_bytes (acfg, buf, code - buf);
2053 emit_unset_mode (acfg);
2054 fprintf (acfg->fp, "jmp %s\n", call_target);
2056 emit_byte (acfg, '\xe9');
2057 emit_symbol_diff (acfg, call_target, ".", -4);
2059 #elif defined(TARGET_X86)
2066 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2068 emit_bytes (acfg, buf, code - buf);
2071 emit_byte (acfg, '\xe9');
2072 emit_symbol_diff (acfg, call_target, ".", -4);
2073 #elif defined(TARGET_ARM)
2077 if (acfg->thumb_mixed && cfg->compile_llvm) {
2078 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2079 fprintf (acfg->fp, "b %s\n", call_target);
2080 fprintf (acfg->fp, ".arm\n");
2081 fprintf (acfg->fp, ".align 2\n");
2087 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2089 emit_bytes (acfg, buf, code - buf);
2090 /* jump to method */
2091 if (acfg->thumb_mixed && cfg->compile_llvm)
2092 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2094 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2095 #elif defined(TARGET_ARM64)
2096 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2097 #elif defined(TARGET_POWERPC)
2100 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2101 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2103 g_assert_not_reached ();
2108 * arch_emit_static_rgctx_trampoline:
2110 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2111 * two GOT slots which contain the rgctx argument, and the method to jump to.
2112 * TRAMP_SIZE is set to the size of the emitted trampoline.
2113 * These kinds of trampolines cannot be enumerated statically, since there could
2114 * be one trampoline per method instantiation, so we emit the same code for all
2115 * trampolines, and parameterize them using two GOT slots.
2118 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2120 #if defined(TARGET_AMD64)
2121 /* This should be exactly 13 bytes long */
2125 emit_unset_mode (acfg);
2126 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2127 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2129 /* mov <OFFSET>(%rip), %r10 */
2130 emit_byte (acfg, '\x4d');
2131 emit_byte (acfg, '\x8b');
2132 emit_byte (acfg, '\x15');
2133 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2135 /* jmp *<offset>(%rip) */
2136 emit_byte (acfg, '\xff');
2137 emit_byte (acfg, '\x25');
2138 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2140 #elif defined(TARGET_ARM)
2144 /* This should be exactly 24 bytes long */
2147 /* Load rgctx value */
2148 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2149 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2150 /* Load branch addr + branch */
2151 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2152 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2154 g_assert (code - buf == 16);
2157 emit_bytes (acfg, buf, code - buf);
2158 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2159 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2160 #elif defined(TARGET_ARM64)
2161 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2162 #elif defined(TARGET_POWERPC)
2170 * PPC has no ip relative addressing, so we need to compute the address
2171 * of the mscorlib got. That is slow and complex, so instead, we store it
2172 * in the second got slot of every aot image. The caller already computed
2173 * the address of its got and placed it into r30.
2175 emit_unset_mode (acfg);
2176 /* Load mscorlib got address */
2177 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2179 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2180 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2181 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2182 /* Load target address */
2183 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2184 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2185 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2186 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2187 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2188 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2190 fprintf (acfg->fp, "mtctr 11\n");
2191 /* Branch to the target address */
2192 fprintf (acfg->fp, "bctr\n");
2194 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2195 *tramp_size = 11 * 4;
2197 *tramp_size = 9 * 4;
2200 #elif defined(TARGET_X86)
2204 /* Similar to the PPC code above */
2206 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2209 /* Load mscorlib got address */
2210 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2212 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2213 /* Branch to the target address */
2214 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2216 emit_bytes (acfg, buf, code - buf);
2219 g_assert (code - buf == *tramp_size);
2221 g_assert_not_reached ();
2226 * arch_emit_imt_trampoline:
2228 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2229 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2230 * key is the IMT key, and ptr holds the address of a memory location holding
2231 * the address to branch to if the IMT arg matches the key. The array is
2232 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2234 * TRAMP_SIZE is set to the size of the emitted trampoline.
2237 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2239 #if defined(TARGET_AMD64)
2241 guint8 *labels [16];
2243 guint8 *mov_buf_ptr = mov_buf;
2245 const int kSizeOfMove = 7;
2247 code = buf = (guint8 *)g_malloc (256);
2249 /* FIXME: Optimize this, i.e. use binary search etc. */
2250 /* Maybe move the body into a separate function (slower, but much smaller) */
2252 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2255 emit_unset_mode (acfg);
2256 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2260 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2262 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2265 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2267 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2270 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2271 amd64_jump_code (code, labels [0]);
2274 mono_amd64_patch (labels [2], code);
2275 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2276 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2279 mono_amd64_patch (labels [1], code);
2280 /* Load fail tramp */
2281 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2282 /* Check if there is a fail tramp */
2283 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2285 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2286 /* Jump to fail tramp */
2287 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2290 mono_amd64_patch (labels [3], code);
2291 x86_breakpoint (code);
2294 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2295 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2296 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2297 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2298 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2299 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2301 emit_bytes (acfg, buf, code - buf);
2303 *tramp_size = code - buf + kSizeOfMove;
2307 #elif defined(TARGET_X86)
2309 guint8 *labels [16];
2311 code = buf = g_malloc (256);
2313 /* Allocate a temporary stack slot */
2314 x86_push_reg (code, X86_EAX);
2316 x86_push_reg (code, X86_EAX);
2318 /* Load mscorlib got address */
2319 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2321 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2324 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2326 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2329 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2331 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2334 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2335 x86_jump_code (code, labels [0]);
2338 mono_x86_patch (labels [2], code);
2339 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2340 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2341 /* Save the target address to the temporary stack location */
2342 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2344 x86_pop_reg (code, X86_EAX);
2345 /* Jump to the target address */
2349 mono_x86_patch (labels [1], code);
2350 /* Load fail tramp */
2351 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2352 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2354 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2355 /* Jump to fail tramp */
2356 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2357 x86_pop_reg (code, X86_EAX);
2361 mono_x86_patch (labels [3], code);
2362 x86_breakpoint (code);
2364 emit_bytes (acfg, buf, code - buf);
2366 *tramp_size = code - buf;
2370 #elif defined(TARGET_ARM)
2372 guint8 *code, *code2, *labels [16];
2376 /* The IMT method is in v5 */
2378 /* Need at least two free registers, plus a slot for storing the pc */
2379 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2381 /* Load the parameter from the GOT */
2382 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2383 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2386 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2387 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2389 ARM_B_COND (code, ARMCOND_EQ, 0);
2391 /* End-of-loop check */
2392 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2394 ARM_B_COND (code, ARMCOND_EQ, 0);
2397 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2400 arm_patch (labels [4], labels [1]);
2403 arm_patch (labels [2], code);
2404 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2405 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2406 /* Save it to the third stack slot */
2407 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2408 /* Restore the registers and branch */
2409 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2412 arm_patch (labels [3], code);
2413 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2414 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2415 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2419 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2421 emit_bytes (acfg, buf, code - buf);
2422 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2424 *tramp_size = code - buf + 4;
2425 #elif defined(TARGET_ARM64)
2426 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2427 #elif defined(TARGET_POWERPC)
2429 guint8 *code, *labels [16];
2433 /* Load the mscorlib got address */
2434 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2435 /* Load the parameter from the GOT */
2436 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2437 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2439 /* Load and check key */
2441 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2442 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2444 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2446 /* End-of-loop check */
2447 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2449 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2452 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2455 mono_ppc_patch (labels [4], labels [1]);
2458 mono_ppc_patch (labels [2], code);
2459 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2460 /* r12 now contains the value of the vtable slot */
2461 /* this is not a function descriptor on ppc64 */
2462 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2463 ppc_mtctr (code, ppc_r12);
2464 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2467 mono_ppc_patch (labels [3], code);
2471 *tramp_size = code - buf;
2473 emit_bytes (acfg, buf, code - buf);
2475 g_assert_not_reached ();
2480 #if defined (TARGET_AMD64)
2483 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2486 g_assert (acfg->fp);
2487 emit_unset_mode (acfg);
2489 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2496 * arch_emit_gsharedvt_arg_trampoline:
2498 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2499 * two GOT slots which contain the argument, and the code to jump to.
2500 * TRAMP_SIZE is set to the size of the emitted trampoline.
2501 * These kinds of trampolines cannot be enumerated statically, since there could
2502 * be one trampoline per method instantiation, so we emit the same code for all
2503 * trampolines, and parameterize them using two GOT slots.
2506 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2508 #if defined(TARGET_X86)
2512 /* Similar to the PPC code above */
2514 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2517 /* Load mscorlib got address */
2518 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2520 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2521 /* Branch to the target address */
2522 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2524 emit_bytes (acfg, buf, code - buf);
2527 g_assert (code - buf == *tramp_size);
2528 #elif defined(TARGET_ARM)
2532 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2533 /* Similar to arch_emit_specific_trampoline () */
2536 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2537 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2538 /* Load the arg value from the GOT */
2539 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2540 /* Load the addr from the GOT */
2541 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2543 ARM_BX (code, ARMREG_R1);
2545 g_assert (code - buf == 20);
2548 emit_bytes (acfg, buf, code - buf);
2549 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2550 #elif defined(TARGET_ARM64)
2551 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2552 #elif defined (TARGET_AMD64)
2554 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2555 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2556 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2557 fprintf (acfg->fp, "jmp *%%r11\n");
2561 g_assert_not_reached ();
2565 /* END OF ARCH SPECIFIC CODE */
2568 mono_get_field_token (MonoClassField *field)
2570 MonoClass *klass = field->parent;
2573 int fcount = mono_class_get_field_count (klass);
2574 for (i = 0; i < fcount; ++i) {
2575 if (field == &klass->fields [i])
2576 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2579 g_assert_not_reached ();
2584 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2588 //printf ("ENCODE: %d 0x%x.\n", value, value);
2591 * Same encoding as the one used in the metadata, extended to handle values
2592 * greater than 0x1fffffff.
2594 if ((value >= 0) && (value <= 127))
2596 else if ((value >= 0) && (value <= 16383)) {
2597 p [0] = 0x80 | (value >> 8);
2598 p [1] = value & 0xff;
2600 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2601 p [0] = (value >> 24) | 0xc0;
2602 p [1] = (value >> 16) & 0xff;
2603 p [2] = (value >> 8) & 0xff;
2604 p [3] = value & 0xff;
2609 p [1] = (value >> 24) & 0xff;
2610 p [2] = (value >> 16) & 0xff;
2611 p [3] = (value >> 8) & 0xff;
2612 p [4] = value & 0xff;
2620 stream_init (MonoDynamicStream *sh)
2623 sh->alloc_size = 4096;
2624 sh->data = (char *)g_malloc (4096);
2626 /* So offsets are > 0 */
2632 make_room_in_stream (MonoDynamicStream *stream, int size)
2634 if (size <= stream->alloc_size)
2637 while (stream->alloc_size <= size) {
2638 if (stream->alloc_size < 4096)
2639 stream->alloc_size = 4096;
2641 stream->alloc_size *= 2;
2644 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2648 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2652 make_room_in_stream (stream, stream->index + len);
2653 memcpy (stream->data + stream->index, data, len);
2654 idx = stream->index;
2655 stream->index += len;
2662 * Add data to the binary blob inside the aot image. Returns the offset inside the
2663 * blob where the data was stored.
2666 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2668 g_assert (!acfg->blob_closed);
2670 if (acfg->blob.alloc_size == 0)
2671 stream_init (&acfg->blob);
2673 return add_stream_data (&acfg->blob, (char*)data, data_len);
2677 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2682 if (acfg->blob.alloc_size == 0)
2683 stream_init (&acfg->blob);
2685 count = acfg->blob.index % align;
2687 /* we assume the stream data will be aligned */
2689 add_stream_data (&acfg->blob, buf, 4 - count);
2691 return add_stream_data (&acfg->blob, (char*)data, data_len);
2694 /* Emit a table of data into the aot image */
2696 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2698 if (acfg->data_outfile) {
2699 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2700 fwrite (data,1, size, acfg->data_outfile);
2701 acfg->datafile_offset += size;
2702 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2703 int align = 8 - size % 8;
2704 acfg->datafile_offset += align;
2705 guint8 align_buf [16];
2706 memset (&align_buf, 0, sizeof (align_buf));
2707 fwrite (align_buf, align, 1, acfg->data_outfile);
2708 } else if (acfg->llvm) {
2709 mono_llvm_emit_aot_data (symbol, data, size);
2711 emit_section_change (acfg, RODATA_SECT, 0);
2712 emit_alignment (acfg, 8);
2713 emit_label (acfg, symbol);
2714 emit_bytes (acfg, data, size);
2719 * emit_offset_table:
2721 * Emit a table of increasing offsets in a compact form using differential encoding.
2722 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2723 * group size, the more compact the table becomes, but the slower it becomes to compute
2724 * a given entry. Returns the size of the table.
2727 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2729 gint32 current_offset;
2730 int i, buf_size, ngroups, index_entry_size;
2732 guint8 *data_p, *data_buf;
2733 guint32 *index_offsets;
2735 ngroups = (noffsets + (group_size - 1)) / group_size;
2737 index_offsets = g_new0 (guint32, ngroups);
2739 buf_size = noffsets * 4;
2740 p = buf = (guint8 *)g_malloc0 (buf_size);
2743 for (i = 0; i < noffsets; ++i) {
2744 //printf ("D: %d -> %d\n", i, offsets [i]);
2745 if ((i % group_size) == 0) {
2746 index_offsets [i / group_size] = p - buf;
2747 /* Emit the full value for these entries */
2748 encode_value (offsets [i], p, &p);
2750 /* The offsets are allowed to be non-increasing */
2751 //g_assert (offsets [i] >= current_offset);
2752 encode_value (offsets [i] - current_offset, p, &p);
2754 current_offset = offsets [i];
2759 if (ngroups && index_offsets [ngroups - 1] < 65000)
2760 index_entry_size = 2;
2762 index_entry_size = 4;
2764 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2765 p = buf = (guint8 *)g_malloc0 (buf_size);
2767 /* Emit the header */
2768 encode_int (noffsets, p, &p);
2769 encode_int (group_size, p, &p);
2770 encode_int (ngroups, p, &p);
2771 encode_int (index_entry_size, p, &p);
2773 /* Emit the index */
2774 for (i = 0; i < ngroups; ++i) {
2775 if (index_entry_size == 2)
2776 encode_int16 (index_offsets [i], p, &p);
2778 encode_int (index_offsets [i], p, &p);
2781 memcpy (p, data_buf, data_p - data_buf);
2782 p += data_p - data_buf;
2784 g_assert (p - buf <= buf_size);
2786 emit_aot_data (acfg, table, symbol, buf, p - buf);
2791 return (int)(p - buf);
2795 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2799 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2803 index = g_hash_table_size (cfg->image_hash);
2804 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2805 g_ptr_array_add (cfg->image_table, image);
2811 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2814 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2816 /* FIXME: Search referenced images as well */
2817 if (!acfg->typespec_classes) {
2818 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2819 for (i = 0; i < len; i++) {
2821 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2822 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2823 if (!is_ok (&error)) {
2824 mono_error_cleanup (&error);
2827 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2830 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2834 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2837 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2840 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2843 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2846 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2851 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2855 if (mono_class_is_ginst (klass)) {
2857 g_assert (klass->type_token);
2859 /* Find a typespec for a class if possible */
2860 token = find_typespec_for_class (acfg, klass);
2862 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2863 encode_value (token, p, &p);
2865 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2866 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2867 static int count = 0;
2870 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2871 encode_klass_ref (acfg, gclass, p, &p);
2872 encode_ginst (acfg, inst, p, &p);
2876 } else if (klass->type_token) {
2877 int iindex = get_image_index (acfg, klass->image);
2879 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2881 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2882 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2884 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2885 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2886 encode_value (get_image_index (acfg, klass->image), p, &p);
2888 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2889 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2890 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2892 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2894 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2895 if (par->gshared_constraint) {
2896 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2897 encode_type (acfg, par->gshared_constraint, p, &p);
2898 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2900 encode_value (klass->byval_arg.type, p, &p);
2901 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2903 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2905 if (!container->is_anonymous) {
2906 encode_value (container->is_method, p, &p);
2907 if (container->is_method)
2908 encode_method_ref (acfg, container->owner.method, p, &p);
2910 encode_klass_ref (acfg, container->owner.klass, p, &p);
2913 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2914 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2915 encode_type (acfg, &klass->byval_arg, p, &p);
2918 g_assert (klass->rank > 0);
2919 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2920 encode_value (klass->rank, p, &p);
2921 encode_klass_ref (acfg, klass->element_class, p, &p);
2929 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2930 * standard metadata encoding.
2933 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2935 gboolean shared = FALSE;
2938 * The encoding of generic instances is large so emit them only once.
2940 if (mono_class_is_ginst (klass)) {
2942 g_assert (klass->type_token);
2944 /* Find a typespec for a class if possible */
2945 token = find_typespec_for_class (acfg, klass);
2948 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2953 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2957 buf2 = (guint8 *)g_malloc (1024);
2960 encode_klass_ref_inner (acfg, klass, p, &p);
2961 g_assert (p - buf2 < 1024);
2963 offset = add_to_blob (acfg, buf2, p - buf2);
2966 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2972 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2973 encode_value (offset, p, &p);
2978 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2982 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2984 guint32 token = mono_get_field_token (field);
2987 encode_klass_ref (cfg, field->parent, p, &p);
2988 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2989 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2994 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2999 encode_value (inst->type_argc, p, &p);
3000 for (i = 0; i < inst->type_argc; ++i)
3001 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3006 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3009 MonoGenericInst *inst;
3011 inst = context->class_inst;
3013 g_assert (inst->type_argc);
3014 encode_ginst (acfg, inst, p, &p);
3016 encode_value (0, p, &p);
3018 inst = context->method_inst;
3020 g_assert (inst->type_argc);
3021 encode_ginst (acfg, inst, p, &p);
3023 encode_value (0, p, &p);
3029 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3033 g_assert (t->num_mods == 0);
3034 /* t->attrs can be ignored */
3035 //g_assert (t->attrs == 0);
3038 *p = MONO_TYPE_PINNED;
3042 *p = MONO_TYPE_BYREF;
3050 case MONO_TYPE_VOID:
3051 case MONO_TYPE_BOOLEAN:
3052 case MONO_TYPE_CHAR:
3065 case MONO_TYPE_STRING:
3066 case MONO_TYPE_OBJECT:
3067 case MONO_TYPE_TYPEDBYREF:
3069 case MONO_TYPE_VALUETYPE:
3070 case MONO_TYPE_CLASS:
3071 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3073 case MONO_TYPE_SZARRAY:
3074 encode_klass_ref (acfg, t->data.klass, p, &p);
3077 encode_type (acfg, t->data.type, p, &p);
3079 case MONO_TYPE_GENERICINST: {
3080 MonoClass *gclass = t->data.generic_class->container_class;
3081 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3083 encode_klass_ref (acfg, gclass, p, &p);
3084 encode_ginst (acfg, inst, p, &p);
3087 case MONO_TYPE_ARRAY: {
3088 MonoArrayType *array = t->data.array;
3091 encode_klass_ref (acfg, array->eklass, p, &p);
3092 encode_value (array->rank, p, &p);
3093 encode_value (array->numsizes, p, &p);
3094 for (i = 0; i < array->numsizes; ++i)
3095 encode_value (array->sizes [i], p, &p);
3096 encode_value (array->numlobounds, p, &p);
3097 for (i = 0; i < array->numlobounds; ++i)
3098 encode_value (array->lobounds [i], p, &p);
3102 case MONO_TYPE_MVAR:
3103 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3106 g_assert_not_reached ();
3113 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3119 /* Similar to the metadata encoding */
3120 if (sig->generic_param_count)
3124 if (sig->explicit_this)
3126 flags |= (sig->call_convention & 0x0F);
3130 if (sig->generic_param_count)
3131 encode_value (sig->generic_param_count, p, &p);
3132 encode_value (sig->param_count, p, &p);
3134 encode_type (acfg, sig->ret, p, &p);
3135 for (i = 0; i < sig->param_count; ++i) {
3136 if (sig->sentinelpos == i) {
3137 *p = MONO_TYPE_SENTINEL;
3140 encode_type (acfg, sig->params [i], p, &p);
3146 #define MAX_IMAGE_INDEX 250
3149 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3151 guint32 image_index = get_image_index (acfg, method->klass->image);
3152 guint32 token = method->token;
3153 MonoJumpInfoToken *ji;
3157 * The encoding for most methods is as follows:
3158 * - image index encoded as a leb128
3159 * - token index encoded as a leb128
3160 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3161 * types of method encodings.
3164 /* Mark methods which can't use aot trampolines because they need the further
3165 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3167 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3168 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3169 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3171 if (method->wrapper_type) {
3172 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3174 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3176 encode_value (method->wrapper_type, p, &p);
3178 switch (method->wrapper_type) {
3179 case MONO_WRAPPER_REMOTING_INVOKE:
3180 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3181 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3184 m = mono_marshal_method_from_wrapper (method);
3186 encode_method_ref (acfg, m, p, &p);
3189 case MONO_WRAPPER_PROXY_ISINST:
3190 case MONO_WRAPPER_LDFLD:
3191 case MONO_WRAPPER_LDFLDA:
3192 case MONO_WRAPPER_STFLD: {
3194 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3197 case MONO_WRAPPER_ALLOC: {
3198 /* The GC name is saved once in MonoAotFileInfo */
3199 g_assert (info->d.alloc.alloc_type != -1);
3200 encode_value (info->d.alloc.alloc_type, p, &p);
3203 case MONO_WRAPPER_WRITE_BARRIER: {
3207 case MONO_WRAPPER_STELEMREF: {
3209 encode_value (info->subtype, p, &p);
3210 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3211 encode_value (info->d.virtual_stelemref.kind, p, &p);
3214 case MONO_WRAPPER_UNKNOWN: {
3216 encode_value (info->subtype, p, &p);
3217 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3218 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3219 encode_klass_ref (acfg, method->klass, p, &p);
3220 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3221 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3222 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3223 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3224 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3225 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3226 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3227 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3230 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3232 encode_value (info->subtype, p, &p);
3233 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3234 strcpy ((char*)p, method->name);
3235 p += strlen (method->name) + 1;
3236 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3237 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3239 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3240 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3244 case MONO_WRAPPER_SYNCHRONIZED: {
3247 m = mono_marshal_method_from_wrapper (method);
3249 g_assert (m != method);
3250 encode_method_ref (acfg, m, p, &p);
3253 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3255 encode_value (info->subtype, p, &p);
3257 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3258 encode_value (info->d.element_addr.rank, p, &p);
3259 encode_value (info->d.element_addr.elem_size, p, &p);
3260 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3261 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3263 g_assert_not_reached ();
3267 case MONO_WRAPPER_CASTCLASS: {
3269 encode_value (info->subtype, p, &p);
3272 case MONO_WRAPPER_RUNTIME_INVOKE: {
3274 encode_value (info->subtype, p, &p);
3275 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3276 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3277 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3278 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3281 case MONO_WRAPPER_DELEGATE_INVOKE:
3282 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3283 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3284 if (method->is_inflated) {
3285 /* These wrappers are identified by their class */
3286 encode_value (1, p, &p);
3287 encode_klass_ref (acfg, method->klass, p, &p);
3289 MonoMethodSignature *sig = mono_method_signature (method);
3290 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3292 encode_value (0, p, &p);
3293 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3294 encode_value (info ? info->subtype : 0, p, &p);
3295 encode_signature (acfg, sig, p, &p);
3299 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3301 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3302 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3306 g_assert_not_reached ();
3308 } else if (mono_method_signature (method)->is_inflated) {
3310 * This is a generic method, find the original token which referenced it and
3312 * Obtain the token from information recorded by the JIT.
3314 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3316 image_index = get_image_index (acfg, ji->image);
3317 g_assert (image_index < MAX_IMAGE_INDEX);
3320 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3321 encode_value (image_index, p, &p);
3322 encode_value (token, p, &p);
3324 MonoMethod *declaring;
3325 MonoGenericContext *context = mono_method_get_context (method);
3327 g_assert (method->is_inflated);
3328 declaring = ((MonoMethodInflated*)method)->declaring;
3331 * This might be a non-generic method of a generic instance, which
3332 * doesn't have a token since the reference is generated by the JIT
3333 * like Nullable:Box/Unbox, or by generic sharing.
3335 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3336 /* Encode the klass */
3337 encode_klass_ref (acfg, method->klass, p, &p);
3338 /* Encode the method */
3339 image_index = get_image_index (acfg, method->klass->image);
3340 g_assert (image_index < MAX_IMAGE_INDEX);
3341 g_assert (declaring->token);
3342 token = declaring->token;
3343 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3344 encode_value (image_index, p, &p);
3345 encode_value (token, p, &p);
3346 encode_generic_context (acfg, context, p, &p);
3348 } else if (token == 0) {
3349 /* This might be a method of a constructed type like int[,].Set */
3350 /* Obtain the token from information recorded by the JIT */
3351 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3353 image_index = get_image_index (acfg, ji->image);
3354 g_assert (image_index < MAX_IMAGE_INDEX);
3357 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3358 encode_value (image_index, p, &p);
3359 encode_value (token, p, &p);
3362 g_assert (method->klass->rank);
3364 /* Encode directly */
3365 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3366 encode_klass_ref (acfg, method->klass, p, &p);
3367 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3368 encode_value (0, p, &p);
3369 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3370 encode_value (1, p, &p);
3371 else if (!strcmp (method->name, "Get"))
3372 encode_value (2, p, &p);
3373 else if (!strcmp (method->name, "Address"))
3374 encode_value (3, p, &p);
3375 else if (!strcmp (method->name, "Set"))
3376 encode_value (4, p, &p);
3378 g_assert_not_reached ();
3381 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3383 if (image_index >= MONO_AOT_METHODREF_MIN) {
3384 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3385 encode_value (image_index, p, &p);
3386 encode_value (mono_metadata_token_index (token), p, &p);
3388 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3395 compare_patches (gconstpointer a, gconstpointer b)
3399 i = (*(MonoJumpInfo**)a)->ip.i;
3400 j = (*(MonoJumpInfo**)b)->ip.i;
3411 static G_GNUC_UNUSED char*
3412 patch_to_string (MonoJumpInfo *patch_info)
3416 str = g_string_new ("");
3418 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3420 switch (patch_info->type) {
3421 case MONO_PATCH_INFO_VTABLE:
3422 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3427 g_string_append_printf (str, ")");
3428 return g_string_free (str, FALSE);
3434 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3437 static inline gboolean
3438 is_plt_patch (MonoJumpInfo *patch_info)
3440 switch (patch_info->type) {
3441 case MONO_PATCH_INFO_METHOD:
3442 case MONO_PATCH_INFO_INTERNAL_METHOD:
3443 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3444 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3445 case MONO_PATCH_INFO_RGCTX_FETCH:
3455 * Return the symbol identifying the plt entry PLT_OFFSET.
3458 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3462 * The Apple linker reorganizes object files, so it doesn't like branches to local
3463 * labels, since those have no relocations.
3465 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3467 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3474 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3476 static MonoPltEntry*
3477 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3480 gboolean synchronized = FALSE;
3481 static int synchronized_symbol_idx;
3483 if (!is_plt_patch (patch_info))
3486 if (!acfg->patch_to_plt_entry [patch_info->type])
3487 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3488 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3490 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3492 * Allocate a separate PLT slot for each such patch, since some plt
3493 * entries will refer to the method itself, and some will refer to the
3497 synchronized = TRUE;
3501 MonoJumpInfo *new_ji;
3503 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3505 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3506 res->plt_offset = acfg->plt_offset;
3508 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3509 if (acfg->aot_opts.write_symbols)
3510 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3512 /* Avoid duplicate symbols because we don't cache */
3513 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3515 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3516 synchronized_symbol_idx ++;
3519 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3521 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3523 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3525 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3527 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3528 //mono_print_ji (patch_info); printf ("\n");
3529 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3531 acfg->plt_offset ++;
3540 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3541 * JI could be found if it exists, otherwise allocates a new one.
3544 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3547 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3549 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3551 return got_offset - 1;
3554 got_offset = acfg->llvm_got_offset;
3555 acfg->llvm_got_offset ++;
3557 got_offset = acfg->got_offset;
3558 acfg->got_offset ++;
3561 acfg->stats.got_slots ++;
3562 acfg->stats.got_slot_types [ji->type] ++;
3564 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3565 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3566 g_ptr_array_add (info->got_patches, ji);
3571 /* Add a method to the list of methods which need to be emitted */
3573 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3576 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3577 g_ptr_array_add (acfg->methods, method);
3578 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3579 acfg->nmethods = acfg->methods->len + 1;
3582 if (method->wrapper_type || extra)
3583 g_ptr_array_add (acfg->extra_methods, method);
3587 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3589 /* One instantiation with valuetypes is generated for each async method */
3590 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3597 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3599 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3607 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3611 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3615 index = acfg->method_index;
3616 add_method_with_index (acfg, method, index, extra);
3618 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3620 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3622 acfg->method_index ++;
3628 add_method (MonoAotCompile *acfg, MonoMethod *method)
3630 return add_method_full (acfg, method, FALSE, 0);
3634 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3636 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3637 method = mini_get_shared_method (method);
3638 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3639 /* Use the gsharedvt version */
3640 method = mini_get_shared_method_full (method, TRUE, TRUE);
3642 if (acfg->aot_opts.log_generics)
3643 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3645 add_method_full (acfg, method, TRUE, depth);
3649 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3651 add_extra_method_with_depth (acfg, method, 0);
3655 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3657 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3658 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3659 MonoMethod *wrapper;
3665 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3666 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3669 add_method (acfg, wrapper);
3673 get_runtime_invoke_sig (MonoMethodSignature *sig)
3675 MonoMethodBuilder *mb;
3678 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3679 m = mono_mb_create_method (mb, sig, 16);
3680 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3686 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3688 return mono_marshal_get_runtime_invoke (method, virtual_);
3692 can_marshal_struct (MonoClass *klass)
3694 MonoClassField *field;
3695 gboolean can_marshal = TRUE;
3696 gpointer iter = NULL;
3697 MonoMarshalType *info;
3700 if (mono_class_is_auto_layout (klass))
3703 info = mono_marshal_load_type_info (klass);
3705 /* Only allow a few field types to avoid asserts in the marshalling code */
3706 while ((field = mono_class_get_fields (klass, &iter))) {
3707 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3710 switch (field->type->type) {
3715 case MONO_TYPE_BOOLEAN:
3718 case MONO_TYPE_CHAR:
3726 case MONO_TYPE_STRING:
3728 case MONO_TYPE_VALUETYPE:
3729 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3730 can_marshal = FALSE;
3732 case MONO_TYPE_SZARRAY: {
3733 gboolean has_mspec = FALSE;
3736 for (i = 0; i < info->num_fields; ++i) {
3737 if (info->fields [i].field == field && info->fields [i].mspec)
3742 can_marshal = FALSE;
3746 can_marshal = FALSE;
3752 /* Its hard to compute whenever these can be marshalled or not */
3753 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3760 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3762 /* Create a vtype instantiation */
3763 MonoGenericContext shared_context;
3765 MonoGenericInst *inst;
3766 MonoGenericContainer *container;
3767 MonoClass **constraints;
3770 memset (ctx, 0, sizeof (MonoGenericContext));
3772 if (mono_class_is_gtd (method->klass)) {
3773 shared_context = mono_class_get_generic_container (method->klass)->context;
3774 inst = shared_context.class_inst;
3776 args = g_new0 (MonoType*, inst->type_argc);
3777 for (i = 0; i < inst->type_argc; ++i) {
3778 args [i] = &mono_defaults.int_class->byval_arg;
3780 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3782 if (method->is_generic) {
3783 container = mono_method_get_generic_container (method);
3784 shared_context = container->context;
3785 inst = shared_context.method_inst;
3787 args = g_new0 (MonoType*, inst->type_argc);
3788 for (i = 0; i < container->type_argc; ++i) {
3789 MonoGenericParamInfo *info = &container->type_params [i].info;
3790 gboolean ref_only = FALSE;
3792 if (info && info->constraints) {
3793 constraints = info->constraints;
3795 while (*constraints) {
3796 MonoClass *cklass = *constraints;
3797 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3798 /* Inflaring the method with our vtype would not be valid */
3805 args [i] = &mono_defaults.object_class->byval_arg;
3807 args [i] = &mono_defaults.int_class->byval_arg;
3809 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3814 add_wrappers (MonoAotCompile *acfg)
3816 MonoMethod *method, *m;
3818 MonoMethodSignature *sig, *csig;
3822 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3823 * so there is only one wrapper of a given type, or inlining their contents into their
3826 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3829 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3830 gboolean skip = FALSE;
3832 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3833 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3835 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3836 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3837 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3840 /* Skip methods which can not be handled by get_runtime_invoke () */
3841 sig = mono_method_signature (method);
3844 if ((sig->ret->type == MONO_TYPE_PTR) ||
3845 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3847 if (mono_class_is_open_constructed_type (sig->ret))
3850 for (j = 0; j < sig->param_count; j++) {
3851 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3853 if (mono_class_is_open_constructed_type (sig->params [j]))
3857 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3858 if (!mono_class_is_contextbound (method->klass)) {
3859 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3860 gboolean has_nullable = FALSE;
3862 for (j = 0; j < sig->param_count; j++) {
3863 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3864 has_nullable = TRUE;
3867 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3868 /* Supported by the dynamic runtime-invoke wrapper */
3872 mono_arch_dyn_call_free (info);
3876 if (acfg->aot_opts.llvm_only)
3877 /* Supported by the gsharedvt based runtime-invoke wrapper */
3881 //printf ("%s\n", mono_method_full_name (method, TRUE));
3882 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3886 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3889 /* Runtime invoke wrappers */
3891 /* void runtime-invoke () [.cctor] */
3892 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3893 csig->ret = &mono_defaults.void_class->byval_arg;
3894 add_method (acfg, get_runtime_invoke_sig (csig));
3896 /* void runtime-invoke () [Finalize] */
3897 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3899 csig->ret = &mono_defaults.void_class->byval_arg;
3900 add_method (acfg, get_runtime_invoke_sig (csig));
3902 /* void runtime-invoke (string) [exception ctor] */
3903 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3905 csig->ret = &mono_defaults.void_class->byval_arg;
3906 csig->params [0] = &mono_defaults.string_class->byval_arg;
3907 add_method (acfg, get_runtime_invoke_sig (csig));
3909 /* void runtime-invoke (string, string) [exception ctor] */
3910 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3912 csig->ret = &mono_defaults.void_class->byval_arg;
3913 csig->params [0] = &mono_defaults.string_class->byval_arg;
3914 csig->params [1] = &mono_defaults.string_class->byval_arg;
3915 add_method (acfg, get_runtime_invoke_sig (csig));
3917 /* string runtime-invoke () [Exception.ToString ()] */
3918 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3920 csig->ret = &mono_defaults.string_class->byval_arg;
3921 add_method (acfg, get_runtime_invoke_sig (csig));
3923 /* void runtime-invoke (string, Exception) [exception ctor] */
3924 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3926 csig->ret = &mono_defaults.void_class->byval_arg;
3927 csig->params [0] = &mono_defaults.string_class->byval_arg;
3928 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3929 add_method (acfg, get_runtime_invoke_sig (csig));
3931 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3932 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3934 csig->ret = &(mono_class_load_from_name (
3935 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3936 csig->params [0] = &mono_defaults.string_class->byval_arg;
3937 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3938 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3939 add_method (acfg, get_runtime_invoke_sig (csig));
3941 /* runtime-invoke used by finalizers */
3942 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3944 /* This is used by mono_runtime_capture_context () */
3945 method = mono_get_context_capture_method ();
3947 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3949 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3950 if (!acfg->aot_opts.llvm_only)
3951 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3954 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3955 if (acfg->aot_opts.llvm_only) {
3958 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3959 for (variants = 0; variants < 4; ++variants) {
3960 for (i = 0; i < 16; ++i) {
3961 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3962 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3970 add_method (acfg, mono_marshal_get_stelemref ());
3972 /* Managed Allocators */
3973 nallocators = mono_gc_get_managed_allocator_types ();
3974 for (i = 0; i < nallocators; ++i) {
3975 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3976 add_method (acfg, m);
3977 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3978 add_method (acfg, m);
3981 /* write barriers */
3982 if (mono_gc_is_moving ()) {
3983 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3984 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3987 /* Stelemref wrappers */
3989 MonoMethod **wrappers;
3992 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3993 for (i = 0; i < nwrappers; ++i)
3994 add_method (acfg, wrappers [i]);
3998 /* castclass_with_check wrapper */
3999 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4000 /* isinst_with_check wrapper */
4001 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4003 /* JIT icall wrappers */
4004 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4005 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4009 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4010 * we use the original method instead at runtime.
4011 * Since full-aot doesn't support remoting, this is not a problem.
4014 /* remoting-invoke wrappers */
4015 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4017 MonoMethodSignature *sig;
4019 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4020 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4021 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4023 sig = mono_method_signature (method);
4025 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4026 m = mono_marshal_get_remoting_invoke_with_check (method);
4028 add_method (acfg, m);
4033 /* delegate-invoke wrappers */
4034 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4037 MonoCustomAttrInfo *cattr;
4039 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4040 klass = mono_class_get_checked (acfg->image, token, &error);
4043 mono_error_cleanup (&error);
4047 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4050 if (!mono_class_is_gtd (klass)) {
4051 method = mono_get_delegate_invoke (klass);
4053 m = mono_marshal_get_delegate_invoke (method, NULL);
4055 add_method (acfg, m);
4057 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4059 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4061 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4063 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4065 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4066 if (!is_ok (&error)) {
4067 mono_error_cleanup (&error);
4074 for (j = 0; j < cattr->num_attrs; ++j)
4075 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4077 if (j < cattr->num_attrs) {
4079 MonoMethod *wrapper;
4080 MonoMethod *del_invoke;
4082 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4083 invoke = mono_get_delegate_invoke (klass);
4084 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4085 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4086 add_method (acfg, wrapper);
4087 add_method (acfg, del_invoke);
4090 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4092 MonoGenericContext ctx;
4093 MonoMethod *inst, *gshared;
4096 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4099 method = mono_get_delegate_invoke (klass);
4100 create_gsharedvt_inst (acfg, method, &ctx);
4102 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4103 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4105 m = mono_marshal_get_delegate_invoke (inst, NULL);
4106 g_assert (m->is_inflated);
4108 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4109 add_extra_method (acfg, gshared);
4112 method = mono_get_delegate_begin_invoke (klass);
4114 create_gsharedvt_inst (acfg, method, &ctx);
4116 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4117 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4119 m = mono_marshal_get_delegate_begin_invoke (inst);
4120 g_assert (m->is_inflated);
4122 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4123 add_extra_method (acfg, gshared);
4127 method = mono_get_delegate_end_invoke (klass);
4129 create_gsharedvt_inst (acfg, method, &ctx);
4131 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4132 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4134 m = mono_marshal_get_delegate_end_invoke (inst);
4135 g_assert (m->is_inflated);
4137 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4138 add_extra_method (acfg, gshared);
4143 /* array access wrappers */
4144 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4148 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4149 klass = mono_class_get_checked (acfg->image, token, &error);
4152 mono_error_cleanup (&error);
4156 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4157 MonoMethod *m, *wrapper;
4159 /* Add runtime-invoke wrappers too */
4161 m = mono_class_get_method_from_name (klass, "Get", -1);
4163 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4164 add_extra_method (acfg, wrapper);
4165 if (!acfg->aot_opts.llvm_only)
4166 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4168 m = mono_class_get_method_from_name (klass, "Set", -1);
4170 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4171 add_extra_method (acfg, wrapper);
4172 if (!acfg->aot_opts.llvm_only)
4173 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4177 /* Synchronized wrappers */
4178 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4180 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4181 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4182 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4184 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4185 if (method->is_generic) {
4187 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4189 MonoGenericContext ctx;
4190 MonoMethod *inst, *gshared, *m;
4193 * Create a generic wrapper for a generic instance, and AOT that.
4195 create_gsharedvt_inst (acfg, method, &ctx);
4196 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4197 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4198 m = mono_marshal_get_synchronized_wrapper (inst);
4199 g_assert (m->is_inflated);
4200 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4201 add_method (acfg, gshared);
4203 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4208 /* pinvoke wrappers */
4209 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4212 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4214 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4215 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4217 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4218 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4219 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4222 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4223 if (acfg->aot_opts.llvm_only) {
4224 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4225 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4230 /* native-to-managed wrappers */
4231 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4234 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4235 MonoCustomAttrInfo *cattr;
4238 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4239 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4242 * Only generate native-to-managed wrappers for methods which have an
4243 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4244 * name to avoid defining a new assembly to contain it.
4246 cattr = mono_custom_attrs_from_method_checked (method, &error);
4247 if (!is_ok (&error)) {
4248 char *name = mono_method_get_full_name (method);
4249 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4254 for (j = 0; j < cattr->num_attrs; ++j)
4255 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4257 if (j < cattr->num_attrs) {
4258 MonoCustomAttrEntry *e = &cattr->attrs [j];
4259 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4260 const char *p = (const char*)e->data;
4262 int slen, num_named, named_type;
4266 char *export_name = NULL;
4267 MonoMethod *wrapper;
4269 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4270 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4271 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4272 mono_method_full_name (method, TRUE));
4276 g_assert (sig->param_count == 1);
4277 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4280 * Decode the cattr manually since we can't create objects
4281 * during aot compilation.
4287 /* From load_cattr_value () in reflection.c */
4288 slen = mono_metadata_decode_value (p, &p);
4289 n = (char *)g_memdup (p, slen + 1);
4291 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4293 mono_error_assert_ok (&error);
4296 klass = mono_class_from_mono_type (t);
4297 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4301 num_named = read16 (p);
4304 g_assert (num_named < 2);
4305 if (num_named == 1) {
4309 /* parse ExportSymbol attribute */
4311 named_type = *named;
4313 /* data_type = *named; */
4316 name_len = mono_metadata_decode_blob_size (named, &named);
4317 name = (char *)g_malloc (name_len + 1);
4318 memcpy (name, named, name_len);
4319 name [name_len] = 0;
4322 g_assert (named_type == 0x54);
4323 g_assert (!strcmp (name, "ExportSymbol"));
4325 /* load_cattr_value (), string case */
4326 g_assert (*named != (char)0xff);
4327 slen = mono_metadata_decode_value (named, &named);
4328 export_name = (char *)g_malloc (slen + 1);
4329 memcpy (export_name, named, slen);
4330 export_name [slen] = 0;
4334 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, &error);
4335 mono_error_assert_ok (&error);
4337 add_method (acfg, wrapper);
4339 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4344 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4345 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4346 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4350 /* StructureToPtr/PtrToStructure wrappers */
4351 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4355 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4356 klass = mono_class_get_checked (acfg->image, token, &error);
4359 mono_error_cleanup (&error);
4363 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4364 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4365 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4366 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4372 has_type_vars (MonoClass *klass)
4374 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4377 return has_type_vars (klass->element_class);
4378 if (mono_class_is_ginst (klass)) {
4379 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4380 if (context->class_inst) {
4383 for (i = 0; i < context->class_inst->type_argc; ++i)
4384 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4388 if (mono_class_is_gtd (klass))
4394 is_vt_inst (MonoGenericInst *inst)
4398 for (i = 0; i < inst->type_argc; ++i) {
4399 MonoType *t = inst->type_argv [i];
4400 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4407 method_has_type_vars (MonoMethod *method)
4409 if (has_type_vars (method->klass))
4412 if (method->is_inflated) {
4413 MonoGenericContext *context = mono_method_get_context (method);
4414 if (context->method_inst) {
4417 for (i = 0; i < context->method_inst->type_argc; ++i)
4418 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4426 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4428 return opts->mode == MONO_AOT_MODE_FULL;
4432 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4434 return opts->mode == MONO_AOT_MODE_HYBRID;
4437 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4440 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4442 /* This might lead to a huge code blowup so only do it if neccesary */
4443 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4446 add_generic_class_with_depth (acfg, klass, 0, ref);
4450 check_type_depth (MonoType *t, int depth)
4458 case MONO_TYPE_GENERICINST: {
4459 MonoGenericClass *gklass = t->data.generic_class;
4460 MonoGenericInst *ginst = gklass->context.class_inst;
4463 for (i = 0; i < ginst->type_argc; ++i) {
4464 if (check_type_depth (ginst->type_argv [i], depth + 1))
4478 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4481 * add_generic_class:
4483 * Add all methods of a generic class.
4486 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4489 MonoClassField *field;
4491 gboolean use_gsharedvt = FALSE;
4493 if (!acfg->ginst_hash)
4494 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4496 mono_class_init (klass);
4498 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4501 if (has_type_vars (klass))
4504 if (!mono_class_is_ginst (klass) && !klass->rank)
4507 if (mono_class_has_failure (klass))
4510 if (!acfg->ginst_hash)
4511 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4513 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4516 if (check_type_depth (&klass->byval_arg, 0))
4519 if (acfg->aot_opts.log_generics)
4520 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4522 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4525 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4526 * Enable this only for some classes since gsharedvt might not support all methods.
4528 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4529 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4530 use_gsharedvt = TRUE;
4533 while ((method = mono_class_get_methods (klass, &iter))) {
4534 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4536 * This is partial sharing, and we can't handle it yet
4541 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4543 add_types_from_method_header (acfg, method);
4547 if (method->is_generic)
4552 * FIXME: Instances which are referenced by these methods are not added,
4553 * for example Array.Resize<int> for List<int>.Add ().
4555 add_extra_method_with_depth (acfg, method, depth + 1);
4559 while ((field = mono_class_get_fields (klass, &iter))) {
4560 if (field->type->type == MONO_TYPE_GENERICINST)
4561 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4564 if (klass->delegate) {
4565 method = mono_get_delegate_invoke (klass);
4567 method = mono_marshal_get_delegate_invoke (method, NULL);
4569 if (acfg->aot_opts.log_generics)
4570 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4572 add_method (acfg, method);
4575 /* Add superclasses */
4577 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4580 * For ICollection<T>, add instances of the helper methods
4581 * in Array, since a T[] could be cast to ICollection<T>.
4583 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4584 (!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"))) {
4585 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4586 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4590 if (!strcmp (klass->name, "IEnumerator`1"))
4591 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4593 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4595 /* Add the T[]/InternalEnumerator class */
4596 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4601 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4602 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4606 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4607 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4608 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4612 while ((method = mono_class_get_methods (array_class, &iter))) {
4613 if (strstr (method->name, name_prefix)) {
4614 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4616 add_extra_method_with_depth (acfg, m, depth);
4620 g_free (name_prefix);
4623 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4624 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4626 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4627 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4628 MonoGenericContext ctx;
4629 MonoType *args [16];
4631 memset (&ctx, 0, sizeof (ctx));
4633 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4635 args [0] = &tclass->byval_arg;
4636 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4638 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4639 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4641 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4642 MonoClass *gcomparer_inst;
4643 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4644 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4645 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4647 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4651 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4652 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4654 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4655 MonoClass *iface, *gcomparer, *iface_inst;
4656 MonoGenericContext ctx;
4657 MonoType *args [16];
4659 memset (&ctx, 0, sizeof (ctx));
4661 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4663 args [0] = &tclass->byval_arg;
4664 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4666 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4667 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4669 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4670 MonoClass *gcomparer_inst;
4673 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4674 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4675 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4676 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4680 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4681 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4682 MonoClass *enum_comparer;
4683 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4684 MonoGenericContext ctx;
4685 MonoType *args [16];
4687 if (mono_class_is_enum (tclass)) {
4688 MonoClass *enum_comparer_inst;
4691 memset (&ctx, 0, sizeof (ctx));
4692 args [0] = &tclass->byval_arg;
4693 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4695 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4696 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4697 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4698 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4702 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4703 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4704 MonoClass *comparer;
4705 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4706 MonoGenericContext ctx;
4707 MonoType *args [16];
4709 if (mono_class_is_enum (tclass)) {
4710 MonoClass *comparer_inst;
4713 memset (&ctx, 0, sizeof (ctx));
4714 args [0] = &tclass->byval_arg;
4715 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4717 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4718 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4719 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4720 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4726 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4729 MonoGenericContext ctx;
4730 MonoType *args [16];
4732 if (acfg->aot_opts.no_instances)
4735 memset (&ctx, 0, sizeof (ctx));
4737 for (i = 0; i < ninsts; ++i) {
4739 MonoClass *generic_inst;
4740 args [0] = insts [i];
4741 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4742 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4743 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4744 add_generic_class (acfg, generic_inst, force, "");
4749 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4752 MonoMethodHeader *header;
4753 MonoMethodSignature *sig;
4756 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4758 sig = mono_method_signature (method);
4761 for (j = 0; j < sig->param_count; ++j)
4762 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4763 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4766 header = mono_method_get_header_checked (method, &error);
4769 for (j = 0; j < header->num_locals; ++j)
4770 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4771 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4772 mono_metadata_free_mh (header);
4774 mono_error_cleanup (&error); /* FIXME report the error */
4780 * add_generic_instances:
4782 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4785 add_generic_instances (MonoAotCompile *acfg)
4790 MonoGenericContext *context;
4792 if (acfg->aot_opts.no_instances)
4795 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4797 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4798 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4801 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4802 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4803 mono_error_cleanup (&error);
4807 if (method->klass->image != acfg->image)
4810 context = mono_method_get_context (method);
4812 if (context && ((context->class_inst && context->class_inst->is_open)))
4816 * For open methods, create an instantiation which can be passed to the JIT.
4817 * FIXME: Handle class_inst as well.
4819 if (context && context->method_inst && context->method_inst->is_open) {
4821 MonoGenericContext shared_context;
4822 MonoGenericInst *inst;
4823 MonoType **type_argv;
4825 MonoMethod *declaring_method;
4826 gboolean supported = TRUE;
4828 /* Check that the context doesn't contain open constructed types */
4829 if (context->class_inst) {
4830 inst = context->class_inst;
4831 for (i = 0; i < inst->type_argc; ++i) {
4832 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)
4834 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4838 if (context->method_inst) {
4839 inst = context->method_inst;
4840 for (i = 0; i < inst->type_argc; ++i) {
4841 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)
4843 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4851 memset (&shared_context, 0, sizeof (MonoGenericContext));
4853 inst = context->class_inst;
4855 type_argv = g_new0 (MonoType*, inst->type_argc);
4856 for (i = 0; i < inst->type_argc; ++i) {
4857 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)
4858 type_argv [i] = &mono_defaults.object_class->byval_arg;
4860 type_argv [i] = inst->type_argv [i];
4863 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4867 inst = context->method_inst;
4869 type_argv = g_new0 (MonoType*, inst->type_argc);
4870 for (i = 0; i < inst->type_argc; ++i) {
4871 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)
4872 type_argv [i] = &mono_defaults.object_class->byval_arg;
4874 type_argv [i] = inst->type_argv [i];
4877 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4881 if (method->is_generic || mono_class_is_gtd (method->klass))
4882 declaring_method = method;
4884 declaring_method = mono_method_get_declaring_generic_method (method);
4886 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4887 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4891 * If the method is fully sharable, it was already added in place of its
4892 * generic definition.
4894 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4898 * FIXME: Partially shared methods are not shared here, so we end up with
4899 * many identical methods.
4901 add_extra_method (acfg, method);
4904 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4908 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4910 klass = mono_class_get_checked (acfg->image, token, &error);
4911 if (!klass || klass->rank) {
4912 mono_error_cleanup (&error);
4916 add_generic_class (acfg, klass, FALSE, "typespec");
4919 /* Add types of args/locals */
4920 for (i = 0; i < acfg->methods->len; ++i) {
4921 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4922 add_types_from_method_header (acfg, method);
4925 if (acfg->image == mono_defaults.corlib) {
4927 MonoType *insts [256];
4930 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4931 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4932 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4933 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4934 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4936 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4937 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4938 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4939 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4940 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4941 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4943 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4944 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4946 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4947 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4949 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4951 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4953 MonoClass *enum_comparer;
4954 MonoType *insts [16];
4958 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4959 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4960 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4961 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4962 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4963 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4966 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4967 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4968 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4971 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4972 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4973 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4975 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4977 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4978 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4979 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4982 /* Add instances of the array generic interfaces for primitive types */
4983 /* This will add instances of the InternalArray_ helper methods in Array too */
4984 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4986 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4988 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4990 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4992 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4994 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4997 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4998 * used for all instances of GetGenericValueImpl by the AOT runtime.
5001 MonoGenericContext ctx;
5002 MonoType *args [16];
5003 MonoMethod *get_method;
5004 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5006 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5010 memset (&ctx, 0, sizeof (ctx));
5011 args [0] = &mono_defaults.object_class->byval_arg;
5012 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5013 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5014 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5018 /* Same for CompareExchange<T>/Exchange<T> */
5020 MonoGenericContext ctx;
5021 MonoType *args [16];
5023 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5024 gpointer iter = NULL;
5026 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5027 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5029 memset (&ctx, 0, sizeof (ctx));
5030 args [0] = &mono_defaults.object_class->byval_arg;
5031 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5032 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5033 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5038 /* Same for Volatile.Read/Write<T> */
5040 MonoGenericContext ctx;
5041 MonoType *args [16];
5043 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5044 gpointer iter = NULL;
5046 if (volatile_klass) {
5047 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5048 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5050 memset (&ctx, 0, sizeof (ctx));
5051 args [0] = &mono_defaults.object_class->byval_arg;
5052 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5053 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5054 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5060 /* object[] accessor wrappers. */
5061 for (i = 1; i < 4; ++i) {
5062 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5065 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5068 m = mono_marshal_get_array_accessor_wrapper (m);
5069 add_extra_method (acfg, m);
5071 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5074 m = mono_marshal_get_array_accessor_wrapper (m);
5075 add_extra_method (acfg, m);
5077 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5080 m = mono_marshal_get_array_accessor_wrapper (m);
5081 add_extra_method (acfg, m);
5087 * is_direct_callable:
5089 * Return whenever the method identified by JI is directly callable without
5090 * going through the PLT.
5093 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5095 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5096 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5098 gboolean direct_callable = TRUE;
5100 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5101 direct_callable = FALSE;
5102 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5103 // FIXME: Maybe call the wrapper directly ?
5104 direct_callable = FALSE;
5106 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5107 /* Disable this so all calls go through load_method (), see the
5108 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5109 * mono_debugger_agent_init ().
5111 direct_callable = FALSE;
5114 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5115 /* sgen does some initialization when the allocator method is created */
5116 direct_callable = FALSE;
5117 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5118 /* we don't know at compile time whether sgen is concurrent or not */
5119 direct_callable = FALSE;
5121 if (direct_callable)
5124 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5125 if (acfg->aot_opts.direct_pinvoke)
5127 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5128 if (acfg->aot_opts.direct_icalls)
5136 #ifdef MONO_ARCH_AOT_SUPPORTED
5138 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5140 MonoImage *image = method->klass->image;
5141 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5142 MonoTableInfo *tables = image->tables;
5143 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5144 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5145 guint32 im_cols [MONO_IMPLMAP_SIZE];
5148 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5152 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5155 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5157 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5160 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5162 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5168 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5175 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5177 if (a->native_offset == b->native_offset)
5178 return a->il_offset - b->il_offset;
5180 return a->native_offset - b->native_offset;
5184 * compute_line_numbers:
5186 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5189 static MonoDebugSourceLocation**
5190 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5192 MonoDebugMethodInfo *minfo;
5193 MonoDebugLineNumberEntry *ln_array;
5194 MonoDebugSourceLocation *loc;
5195 int i, prev_line, prev_il_offset;
5196 int *native_to_il_offset = NULL;
5197 MonoDebugSourceLocation **res;
5200 minfo = mono_debug_lookup_method (method);
5203 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5204 if (debug_info->code_size != code_size)
5207 g_assert (code_size);
5209 /* Compute the native->IL offset mapping */
5211 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5212 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5214 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5216 native_to_il_offset = g_new0 (int, code_size + 1);
5218 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5220 MonoDebugLineNumberEntry *lne = &ln_array [i];
5223 for (j = 0; j < lne->native_offset; ++j)
5224 native_to_il_offset [j] = -1;
5227 if (i < debug_info->num_line_numbers - 1) {
5228 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5230 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5231 native_to_il_offset [j] = lne->il_offset;
5233 for (j = lne->native_offset; j < code_size; ++j)
5234 native_to_il_offset [j] = lne->il_offset;
5239 /* Compute the native->line number mapping */
5240 res = g_new0 (MonoDebugSourceLocation*, code_size);
5241 prev_il_offset = -1;
5244 for (i = 0; i < code_size; ++i) {
5245 int il_offset = native_to_il_offset [i];
5247 if (il_offset == -1 || il_offset == prev_il_offset)
5249 prev_il_offset = il_offset;
5250 loc = mono_debug_method_lookup_location (minfo, il_offset);
5251 if (!(loc && loc->source_file))
5253 if (loc->row == prev_line) {
5254 mono_debug_free_source_location (loc);
5257 prev_line = loc->row;
5258 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5260 /* This will cover the prolog too */
5270 get_file_index (MonoAotCompile *acfg, const char *source_file)
5274 // FIXME: Free these
5275 if (!acfg->dwarf_ln_filenames)
5276 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5277 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5279 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5280 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5281 emit_unset_mode (acfg);
5282 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5294 * emit_and_reloc_code:
5296 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5297 * is true, calls are made through the GOT too. This is used for emitting trampolines
5298 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5299 * since trampolines are needed to make PTL work.
5302 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5304 int i, pindex, start_index;
5306 MonoJumpInfo *patch_info;
5307 MonoDebugSourceLocation **locs = NULL;
5308 gboolean skip, prologue_end = FALSE;
5309 #ifdef MONO_ARCH_AOT_SUPPORTED
5310 gboolean direct_call, external_call;
5312 const char *direct_call_target = 0;
5313 const char *direct_pinvoke;
5316 if (acfg->gas_line_numbers && method && debug_info) {
5317 locs = compute_line_numbers (method, code_len, debug_info);
5319 int findex = get_file_index (acfg, "<unknown>");
5320 emit_unset_mode (acfg);
5321 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5325 /* Collect and sort relocations */
5326 patches = g_ptr_array_new ();
5327 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5328 g_ptr_array_add (patches, patch_info);
5329 g_ptr_array_sort (patches, compare_patches);
5332 for (i = 0; i < code_len; i += INST_LEN) {
5334 for (pindex = start_index; pindex < patches->len; ++pindex) {
5335 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5336 if (patch_info->ip.i >= i)
5340 if (locs && locs [i]) {
5341 MonoDebugSourceLocation *loc = locs [i];
5343 const char *options;
5345 findex = get_file_index (acfg, loc->source_file);
5346 emit_unset_mode (acfg);
5348 options = " prologue_end";
5351 prologue_end = TRUE;
5352 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5353 mono_debug_free_source_location (loc);
5357 #ifdef MONO_ARCH_AOT_SUPPORTED
5358 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5359 start_index = pindex;
5361 switch (patch_info->type) {
5362 case MONO_PATCH_INFO_NONE:
5364 case MONO_PATCH_INFO_GOT_OFFSET: {
5367 arch_emit_got_offset (acfg, code + i, &code_size);
5368 i += code_size - INST_LEN;
5370 patch_info->type = MONO_PATCH_INFO_NONE;
5373 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5374 int code_size, index;
5375 char *selector = (char *)patch_info->data.target;
5377 if (!acfg->objc_selector_to_index)
5378 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5379 if (!acfg->objc_selectors)
5380 acfg->objc_selectors = g_ptr_array_new ();
5381 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5385 index = acfg->objc_selector_index;
5386 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5387 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5388 acfg->objc_selector_index ++;
5391 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5392 i += code_size - INST_LEN;
5394 patch_info->type = MONO_PATCH_INFO_NONE;
5399 * If this patch is a call, try emitting a direct call instead of
5400 * through a PLT entry. This is possible if the called method is in
5401 * the same assembly and requires no initialization.
5403 direct_call = FALSE;
5404 external_call = FALSE;
5405 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5406 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5407 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5408 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5410 direct_call_target = callee_cfg->asm_symbol;
5411 patch_info->type = MONO_PATCH_INFO_NONE;
5412 acfg->stats.direct_calls ++;
5415 acfg->stats.all_calls ++;
5416 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5417 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5418 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5419 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5421 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5422 if (direct_pinvoke) {
5424 g_assert (strlen (direct_pinvoke) < 1000);
5425 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5428 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5429 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5430 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5431 /* Call to a C function implementing a jit icall */
5433 external_call = TRUE;
5434 g_assert (strlen (sym) < 1000);
5435 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5437 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5438 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5439 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5440 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5441 /* Call to a jit icall without a wrapper */
5443 external_call = TRUE;
5444 g_assert (strlen (sym) < 1000);
5445 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5450 patch_info->type = MONO_PATCH_INFO_NONE;
5451 acfg->stats.direct_calls ++;
5454 if (!got_only && !direct_call) {
5455 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5457 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5459 direct_call_target = plt_entry->symbol;
5461 /* Nullify the patch */
5462 patch_info->type = MONO_PATCH_INFO_NONE;
5463 plt_entry->jit_used = TRUE;
5470 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5471 i += call_size - INST_LEN;
5475 got_slot = get_got_offset (acfg, FALSE, patch_info);
5477 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5478 i += code_size - INST_LEN;
5484 #endif /* MONO_ARCH_AOT_SUPPORTED */
5487 /* Find next patch */
5489 for (pindex = start_index; pindex < patches->len; ++pindex) {
5490 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5491 if (patch_info->ip.i >= i)
5495 /* Try to emit multiple bytes at once */
5496 if (pindex < patches->len && patch_info->ip.i > i) {
5499 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5500 if (locs && locs [limit])
5504 emit_code_bytes (acfg, code + i, limit - i);
5505 i = limit - INST_LEN;
5507 emit_code_bytes (acfg, code + i, INST_LEN);
5512 g_ptr_array_free (patches, TRUE);
5519 * Return a modified version of S which only includes characters permissible in symbols.
5522 sanitize_symbol (MonoAotCompile *acfg, char *s)
5524 gboolean process = FALSE;
5533 for (i = 0; i < len; ++i)
5534 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5539 gs = g_string_sized_new (len);
5540 for (i = 0; i < len; ++i) {
5542 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5543 g_string_append_c (gs, c);
5544 } else if (c > 0x7f) {
5545 /* multi-byte utf8 */
5546 g_string_append_printf (gs, "_0x%x", c);
5549 while (c >> 6 == 0x2) {
5550 g_string_append_printf (gs, "%x", c);
5554 g_string_append_printf (gs, "_");
5557 g_string_append_c (gs, '_');
5561 res = mono_mempool_strdup (acfg->mempool, gs->str);
5562 g_string_free (gs, TRUE);
5567 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5569 char *name1, *name2, *cached;
5570 int i, j, len, count;
5571 MonoMethod *cached_method;
5573 name1 = mono_method_full_name (method, TRUE);
5576 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5577 if ((!prefix || !*prefix) && name1 [0] == 'L')
5581 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5582 char adjustedPrefix [MAX_SYMBOL_SIZE];
5583 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5586 len = strlen (name1);
5587 name2 = (char *)malloc (strlen (prefix) + len + 16);
5588 memcpy (name2, prefix, strlen (prefix));
5589 j = strlen (prefix);
5590 for (i = 0; i < len; ++i) {
5591 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5593 } else if (isalnum (name1 [i])) {
5594 name2 [j ++] = name1 [i];
5595 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5597 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5600 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5610 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5611 if (!(cached_method && cached_method != method))
5613 sprintf (name2 + j, "_%d", count);
5617 cached = g_strdup (name2);
5618 g_hash_table_insert (cache, cached, method);
5624 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5629 char *debug_sym = NULL;
5630 char *symbol = NULL;
5631 int func_alignment = AOT_FUNC_ALIGNMENT;
5634 method = cfg->orig_method;
5635 code = cfg->native_code;
5637 method_index = get_method_index (acfg, method);
5638 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5640 /* Make the labels local */
5641 emit_section_change (acfg, ".text", 0);
5642 emit_alignment_code (acfg, func_alignment);
5644 if (acfg->global_symbols && acfg->need_no_dead_strip)
5645 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5647 emit_label (acfg, cfg->asm_symbol);
5649 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5651 * Write a C style symbol for every method, this has two uses:
5652 * - it works on platforms where the dwarf debugging info is not
5654 * - it allows the setting of breakpoints of aot-ed methods.
5656 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5657 cfg->asm_debug_symbol = g_strdup (debug_sym);
5659 if (acfg->need_no_dead_strip)
5660 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5661 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5662 emit_label (acfg, debug_sym);
5665 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5667 /* Emit a global symbol for the method */
5668 emit_global_inner (acfg, export_name, TRUE);
5669 emit_label (acfg, export_name);
5672 if (cfg->verbose_level > 0)
5673 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5675 acfg->stats.code_size += cfg->code_len;
5677 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5679 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 ()));
5683 if (acfg->aot_opts.write_symbols) {
5685 emit_symbol_size (acfg, debug_sym, ".");
5687 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5691 emit_label (acfg, symbol);
5698 * Encode PATCH_INFO into its disk representation.
5701 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5705 switch (patch_info->type) {
5706 case MONO_PATCH_INFO_NONE:
5708 case MONO_PATCH_INFO_IMAGE:
5709 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5711 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5712 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5713 case MONO_PATCH_INFO_GC_NURSERY_START:
5714 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5716 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5717 encode_value (patch_info->data.index, p, &p);
5719 case MONO_PATCH_INFO_METHOD_REL:
5720 encode_value ((gint)patch_info->data.offset, p, &p);
5722 case MONO_PATCH_INFO_SWITCH: {
5723 gpointer *table = (gpointer *)patch_info->data.table->table;
5726 encode_value (patch_info->data.table->table_size, p, &p);
5727 for (k = 0; k < patch_info->data.table->table_size; k++)
5728 encode_value ((int)(gssize)table [k], p, &p);
5731 case MONO_PATCH_INFO_METHODCONST:
5732 case MONO_PATCH_INFO_METHOD:
5733 case MONO_PATCH_INFO_METHOD_JUMP:
5734 case MONO_PATCH_INFO_ICALL_ADDR:
5735 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5736 case MONO_PATCH_INFO_METHOD_RGCTX:
5737 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5738 encode_method_ref (acfg, patch_info->data.method, p, &p);
5740 case MONO_PATCH_INFO_AOT_JIT_INFO:
5741 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5742 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5743 encode_value (patch_info->data.index, p, &p);
5745 case MONO_PATCH_INFO_INTERNAL_METHOD:
5746 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5747 guint32 len = strlen (patch_info->data.name);
5749 encode_value (len, p, &p);
5751 memcpy (p, patch_info->data.name, len);
5756 case MONO_PATCH_INFO_LDSTR: {
5757 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5758 guint32 token = patch_info->data.token->token;
5759 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5760 encode_value (image_index, p, &p);
5761 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5764 case MONO_PATCH_INFO_RVA:
5765 case MONO_PATCH_INFO_DECLSEC:
5766 case MONO_PATCH_INFO_LDTOKEN:
5767 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5768 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5769 encode_value (patch_info->data.token->token, p, &p);
5770 encode_value (patch_info->data.token->has_context, p, &p);
5771 if (patch_info->data.token->has_context)
5772 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5774 case MONO_PATCH_INFO_EXC_NAME: {
5775 MonoClass *ex_class;
5778 mono_class_load_from_name (mono_defaults.exception_class->image,
5779 "System", (const char *)patch_info->data.target);
5780 encode_klass_ref (acfg, ex_class, p, &p);
5783 case MONO_PATCH_INFO_R4:
5784 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5786 case MONO_PATCH_INFO_R8:
5787 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5788 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5790 case MONO_PATCH_INFO_VTABLE:
5791 case MONO_PATCH_INFO_CLASS:
5792 case MONO_PATCH_INFO_IID:
5793 case MONO_PATCH_INFO_ADJUSTED_IID:
5794 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5796 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5797 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5798 if (patch_info->data.del_tramp->method) {
5799 encode_value (1, p, &p);
5800 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5802 encode_value (0, p, &p);
5804 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5806 case MONO_PATCH_INFO_FIELD:
5807 case MONO_PATCH_INFO_SFLDA:
5808 encode_field_info (acfg, patch_info->data.field, p, &p);
5810 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5812 case MONO_PATCH_INFO_RGCTX_FETCH:
5813 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5814 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5819 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5820 * reference the same method, so encode the method only once.
5822 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5824 buf2 = (guint8 *)g_malloc (1024);
5827 encode_method_ref (acfg, entry->method, p2, &p2);
5828 g_assert (p2 - buf2 < 1024);
5830 offset = add_to_blob (acfg, buf2, p2 - buf2);
5833 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5838 encode_value (offset, p, &p);
5839 g_assert ((int)entry->info_type < 256);
5840 g_assert (entry->data->type < 256);
5841 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5842 encode_patch (acfg, entry->data, p, &p);
5845 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5846 case MONO_PATCH_INFO_AOT_MODULE:
5848 case MONO_PATCH_INFO_SIGNATURE:
5849 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5850 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5852 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5853 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5854 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5856 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5857 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5860 encode_method_ref (acfg, info->method, p, &p);
5861 encode_value (info->num_entries, p, &p);
5862 for (i = 0; i < info->num_entries; ++i) {
5863 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5865 encode_value (template_->info_type, p, &p);
5866 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5867 case MONO_PATCH_INFO_CLASS:
5868 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5870 case MONO_PATCH_INFO_FIELD:
5871 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5874 g_assert_not_reached ();
5880 case MONO_PATCH_INFO_LDSTR_LIT: {
5881 const char *s = (const char *)patch_info->data.target;
5882 int len = strlen (s);
5884 encode_value (len, p, &p);
5885 memcpy (p, s, len + 1);
5889 case MONO_PATCH_INFO_VIRT_METHOD:
5890 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5891 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5893 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5894 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5897 g_warning ("unable to handle jump info %d", patch_info->type);
5898 g_assert_not_reached ();
5905 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5908 guint32 pindex, offset;
5909 MonoJumpInfo *patch_info;
5911 encode_value (n_patches, p, &p);
5913 for (pindex = 0; pindex < patches->len; ++pindex) {
5914 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5916 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5920 offset = get_got_offset (acfg, llvm, patch_info);
5921 encode_value (offset, p, &p);
5928 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5931 int pindex, buf_size, n_patches;
5933 MonoJumpInfo *patch_info;
5934 guint32 method_index;
5936 guint32 first_got_offset;
5938 method = cfg->orig_method;
5940 method_index = get_method_index (acfg, method);
5942 /* Sort relocations */
5943 patches = g_ptr_array_new ();
5944 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5945 g_ptr_array_add (patches, patch_info);
5946 g_ptr_array_sort (patches, compare_patches);
5948 first_got_offset = acfg->cfgs [method_index]->got_offset;
5950 /**********************/
5951 /* Encode method info */
5952 /**********************/
5954 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5955 p = buf = (guint8 *)g_malloc (buf_size);
5957 if (mono_class_get_cctor (method->klass)) {
5958 encode_value (1, p, &p);
5959 encode_klass_ref (acfg, method->klass, p, &p);
5961 /* Not needed when loading the method */
5962 encode_value (0, p, &p);
5965 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5968 for (pindex = 0; pindex < patches->len; ++pindex) {
5969 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5971 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5972 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5973 patch_info->type = MONO_PATCH_INFO_NONE;
5978 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5979 /* Stored in a GOT slot initialized at module load time */
5980 patch_info->type = MONO_PATCH_INFO_NONE;
5984 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5985 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5986 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5987 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5988 /* Stored in a GOT slot initialized at module load time */
5989 patch_info->type = MONO_PATCH_INFO_NONE;
5993 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5994 /* Calls are made through the PLT */
5995 patch_info->type = MONO_PATCH_INFO_NONE;
6003 g_assert (cfg->has_got_slots);
6005 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6007 g_ptr_array_free (patches, TRUE);
6009 acfg->stats.info_size += p - buf;
6011 g_assert (p - buf < buf_size);
6013 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6018 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6020 guint32 cache_index;
6023 /* Reuse the unwind module to canonize and store unwind info entries */
6024 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6026 /* Use +/- 1 to distinguish 0s from missing entries */
6027 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6035 * It would be easier to use assembler symbols, but the caller needs an
6038 offset = acfg->unwind_info_offset;
6039 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6040 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6043 encode_value (encoded_len, p, &p);
6045 acfg->unwind_info_offset += encoded_len + (p - buf);
6051 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6054 guint32 debug_info_size, seq_points_size;
6056 MonoMethodHeader *header;
6057 guint8 *p, *buf, *debug_info;
6058 MonoJitInfo *jinfo = cfg->jit_info;
6060 gboolean use_unwind_ops = FALSE;
6061 MonoSeqPointInfo *seq_points;
6063 code = cfg->native_code;
6064 header = cfg->header;
6066 if (!acfg->aot_opts.nodebug) {
6067 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6070 debug_info_size = 0;
6073 seq_points = cfg->seq_point_info;
6074 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6076 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6078 p = buf = (guint8 *)g_malloc (buf_size);
6080 use_unwind_ops = cfg->unwind_ops != NULL;
6082 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);
6084 encode_value (flags, p, &p);
6086 if (use_unwind_ops) {
6087 guint32 encoded_len;
6089 guint32 unwind_desc;
6091 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6093 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6094 encode_value (unwind_desc, p, &p);
6098 encode_value (jinfo->unwind_info, p, &p);
6101 /*Encode the number of holes before the number of clauses to make decoding easier*/
6102 if (jinfo->has_try_block_holes) {
6103 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6104 encode_value (table->num_holes, p, &p);
6107 if (jinfo->has_arch_eh_info) {
6109 * In AOT mode, the code length is calculated from the address of the previous method,
6110 * which could include alignment padding, so calculating the start of the epilog as
6111 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6113 encode_value (jinfo->code_size, p, &p);
6116 /* Exception table */
6117 if (cfg->compile_llvm) {
6119 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6120 * since the information is only available to llc. Instead, we let llc save the data
6121 * into the LSDA, and read it from there at runtime.
6123 /* The assembly might be CIL stripped so emit the data ourselves */
6124 if (header->num_clauses)
6125 encode_value (header->num_clauses, p, &p);
6127 for (k = 0; k < header->num_clauses; ++k) {
6128 MonoExceptionClause *clause;
6130 clause = &header->clauses [k];
6132 encode_value (clause->flags, p, &p);
6133 if (clause->data.catch_class) {
6134 encode_value (1, p, &p);
6135 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6137 encode_value (0, p, &p);
6140 /* Emit the IL ranges too, since they might not be available at runtime */
6141 encode_value (clause->try_offset, p, &p);
6142 encode_value (clause->try_len, p, &p);
6143 encode_value (clause->handler_offset, p, &p);
6144 encode_value (clause->handler_len, p, &p);
6146 /* Emit a list of nesting clauses */
6147 for (i = 0; i < header->num_clauses; ++i) {
6149 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6151 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6153 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6154 encode_value (i, p, &p);
6156 encode_value (-1, p, &p);
6159 if (jinfo->num_clauses)
6160 encode_value (jinfo->num_clauses, p, &p);
6162 for (k = 0; k < jinfo->num_clauses; ++k) {
6163 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6165 encode_value (ei->flags, p, &p);
6166 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6167 /* Not used for catch clauses */
6168 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6169 encode_value (ei->exvar_offset, p, &p);
6171 encode_value (ei->exvar_offset, p, &p);
6174 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6175 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6177 if (ei->data.catch_class) {
6181 buf2 = (guint8 *)g_malloc (4096);
6183 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6185 g_assert (len < 4096);
6186 encode_value (len, p, &p);
6187 memcpy (p, buf2, len);
6191 encode_value (0, p, &p);
6195 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6196 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6197 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6201 if (jinfo->has_try_block_holes) {
6202 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6203 for (i = 0; i < table->num_holes; ++i) {
6204 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6205 encode_value (hole->clause, p, &p);
6206 encode_value (hole->length, p, &p);
6207 encode_value (hole->offset, p, &p);
6211 if (jinfo->has_arch_eh_info) {
6212 MonoArchEHJitInfo *eh_info;
6214 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6215 encode_value (eh_info->stack_size, p, &p);
6216 encode_value (eh_info->epilog_size, p, &p);
6219 if (jinfo->has_generic_jit_info) {
6220 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6221 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6225 encode_value (gi->nlocs, p, &p);
6227 for (i = 0; i < gi->nlocs; ++i) {
6228 MonoDwarfLocListEntry *entry = &gi->locations [i];
6230 encode_value (entry->is_reg ? 1 : 0, p, &p);
6231 encode_value (entry->reg, p, &p);
6233 encode_value (entry->offset, p, &p);
6235 g_assert (entry->from == 0);
6237 encode_value (entry->from, p, &p);
6238 encode_value (entry->to, p, &p);
6241 if (!cfg->compile_llvm) {
6242 encode_value (gi->has_this ? 1 : 0, p, &p);
6243 encode_value (gi->this_reg, p, &p);
6244 encode_value (gi->this_offset, p, &p);
6249 * Need to encode jinfo->method too, since it is not equal to 'method'
6250 * when using generic sharing.
6252 buf2 = (guint8 *)g_malloc (4096);
6254 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6256 g_assert (len < 4096);
6257 encode_value (len, p, &p);
6258 memcpy (p, buf2, len);
6262 if (gsctx && gsctx->is_gsharedvt) {
6263 encode_value (1, p, &p);
6265 encode_value (0, p, &p);
6269 if (seq_points_size)
6270 p += mono_seq_point_info_write (seq_points, p);
6272 g_assert (debug_info_size < buf_size);
6274 encode_value (debug_info_size, p, &p);
6275 if (debug_info_size) {
6276 memcpy (p, debug_info, debug_info_size);
6277 p += debug_info_size;
6278 g_free (debug_info);
6283 encode_value (cfg->gc_map_size, p, &p);
6284 /* The GC map requires 4 bytes of alignment */
6285 while ((gsize)p % 4)
6287 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6288 p += cfg->gc_map_size;
6291 acfg->stats.ex_info_size += p - buf;
6293 g_assert (p - buf < buf_size);
6296 /* The GC Map requires 4 byte alignment */
6297 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6302 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6305 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6307 int i, buf_size, res;
6308 gboolean no_special_static, cant_encode;
6309 gpointer iter = NULL;
6312 mono_error_cleanup (&error);
6316 p = buf = (guint8 *)g_malloc (buf_size);
6318 /* Mark as unusable */
6319 encode_value (-1, p, &p);
6321 res = add_to_blob (acfg, buf, p - buf);
6327 buf_size = 10240 + (klass->vtable_size * 16);
6328 p = buf = (guint8 *)g_malloc (buf_size);
6332 mono_class_init (klass);
6334 mono_class_get_nested_types (klass, &iter);
6335 g_assert (klass->nested_classes_inited);
6337 mono_class_setup_vtable (klass);
6340 * Emit all the information which is required for creating vtables so
6341 * the runtime does not need to create the MonoMethod structures which
6342 * take up a lot of space.
6345 no_special_static = !mono_class_has_special_static_fields (klass);
6347 /* Check whenever we have enough info to encode the vtable */
6348 cant_encode = FALSE;
6349 for (i = 0; i < klass->vtable_size; ++i) {
6350 MonoMethod *cm = klass->vtable [i];
6352 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6356 mono_class_has_finalizer (klass);
6357 if (mono_class_has_failure (klass))
6360 if (mono_class_is_gtd (klass) || cant_encode) {
6361 encode_value (-1, p, &p);
6363 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6364 encode_value (klass->vtable_size, p, &p);
6365 encode_value ((mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (has_nested ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6366 if (klass->has_cctor)
6367 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6368 if (klass->has_finalize)
6369 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6371 encode_value (klass->instance_size, p, &p);
6372 encode_value (mono_class_data_size (klass), p, &p);
6373 encode_value (klass->packing_size, p, &p);
6374 encode_value (klass->min_align, p, &p);
6376 for (i = 0; i < klass->vtable_size; ++i) {
6377 MonoMethod *cm = klass->vtable [i];
6380 encode_method_ref (acfg, cm, p, &p);
6382 encode_value (0, p, &p);
6386 acfg->stats.class_info_size += p - buf;
6388 g_assert (p - buf < buf_size);
6389 res = add_to_blob (acfg, buf, p - buf);
6396 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6398 char *debug_sym = NULL;
6401 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6402 /* Need to add a prefix to create unique symbols */
6403 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6405 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6406 prefix = mangle_symbol_alloc ("plt_");
6408 prefix = g_strdup ("plt_");
6413 case MONO_PATCH_INFO_METHOD:
6414 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6416 case MONO_PATCH_INFO_INTERNAL_METHOD:
6417 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6419 case MONO_PATCH_INFO_RGCTX_FETCH:
6420 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6422 case MONO_PATCH_INFO_ICALL_ADDR:
6423 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6424 char *s = get_debug_sym (ji->data.method, "", cache);
6426 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6430 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6431 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6439 return sanitize_symbol (acfg, debug_sym);
6443 * Calls made from AOTed code are routed through a table of jumps similar to the
6444 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6445 * control to the AOT runtime through a trampoline.
6448 emit_plt (MonoAotCompile *acfg)
6452 if (acfg->aot_opts.llvm_only) {
6453 g_assert (acfg->plt_offset == 1);
6459 emit_section_change (acfg, ".text", 0);
6460 emit_alignment_code (acfg, 16);
6461 emit_info_symbol (acfg, "plt");
6462 emit_label (acfg, acfg->plt_symbol);
6464 for (i = 0; i < acfg->plt_offset; ++i) {
6465 char *debug_sym = NULL;
6466 MonoPltEntry *plt_entry = NULL;
6470 * The first plt entry is unused.
6474 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6476 debug_sym = plt_entry->debug_sym;
6478 if (acfg->thumb_mixed && !plt_entry->jit_used)
6479 /* Emit only a thumb version */
6482 /* Skip plt entries not actually called */
6483 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6486 if (acfg->llvm && !acfg->thumb_mixed) {
6487 emit_label (acfg, plt_entry->llvm_symbol);
6489 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6490 #if defined(TARGET_MACH)
6491 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6497 if (acfg->need_no_dead_strip) {
6498 emit_unset_mode (acfg);
6499 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6501 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6502 emit_label (acfg, debug_sym);
6505 emit_label (acfg, plt_entry->symbol);
6507 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6510 emit_symbol_size (acfg, debug_sym, ".");
6513 if (acfg->thumb_mixed) {
6514 /* Make sure the ARM symbols don't alias the thumb ones */
6515 emit_zero_bytes (acfg, 16);
6518 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6521 for (i = 0; i < acfg->plt_offset; ++i) {
6522 char *debug_sym = NULL;
6523 MonoPltEntry *plt_entry = NULL;
6528 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6530 /* Skip plt entries not actually called by LLVM code */
6531 if (!plt_entry->llvm_used)
6534 if (acfg->aot_opts.write_symbols) {
6535 if (plt_entry->debug_sym)
6536 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6540 #if defined(TARGET_MACH)
6541 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6542 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6544 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6545 emit_label (acfg, debug_sym);
6547 fprintf (acfg->fp, "\n.thumb_func\n");
6549 emit_label (acfg, plt_entry->llvm_symbol);
6552 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6554 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6557 emit_symbol_size (acfg, debug_sym, ".");
6563 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6565 emit_info_symbol (acfg, "plt_end");
6569 * emit_trampoline_full:
6571 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6572 * create_jit_info_for_trampoline ().
6574 static G_GNUC_UNUSED void
6575 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6577 char start_symbol [MAX_SYMBOL_SIZE];
6578 char end_symbol [MAX_SYMBOL_SIZE];
6579 char symbol [MAX_SYMBOL_SIZE];
6580 guint32 buf_size, info_offset;
6581 MonoJumpInfo *patch_info;
6594 code_size = info->code_size;
6596 unwind_ops = info->unwind_ops;
6600 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6602 emit_section_change (acfg, ".text", 0);
6603 emit_global (acfg, start_symbol, TRUE);
6604 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6605 emit_label (acfg, start_symbol);
6607 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6608 emit_label (acfg, symbol);
6611 * The code should access everything through the GOT, so we pass
6614 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6616 emit_symbol_size (acfg, start_symbol, ".");
6619 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6620 emit_label (acfg, end_symbol);
6625 /* Sort relocations */
6626 patches = g_ptr_array_new ();
6627 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6628 if (patch_info->type != MONO_PATCH_INFO_NONE)
6629 g_ptr_array_add (patches, patch_info);
6630 g_ptr_array_sort (patches, compare_patches);
6632 buf_size = patches->len * 128 + 128;
6633 buf = (guint8 *)g_malloc (buf_size);
6636 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6637 g_assert (p - buf < buf_size);
6638 g_ptr_array_free (patches, TRUE);
6640 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6642 info_offset = add_to_blob (acfg, buf, p - buf);
6644 emit_section_change (acfg, RODATA_SECT, 0);
6645 emit_global (acfg, symbol, FALSE);
6646 emit_label (acfg, symbol);
6648 emit_int32 (acfg, info_offset);
6652 guint32 encoded_len;
6656 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6658 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6659 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6662 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6663 emit_int32 (acfg, uw_offset);
6666 /* Emit debug info */
6668 char symbol2 [MAX_SYMBOL_SIZE];
6670 sprintf (symbol, "%s", name);
6671 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6674 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6680 static G_GNUC_UNUSED void
6681 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6683 emit_trampoline_full (acfg, got_offset, info, TRUE);
6687 emit_trampolines (MonoAotCompile *acfg)
6689 char symbol [MAX_SYMBOL_SIZE];
6690 char end_symbol [MAX_SYMBOL_SIZE];
6691 int i, tramp_got_offset;
6693 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6697 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6700 g_assert (acfg->image->assembly);
6702 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6703 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6704 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6705 MonoTrampInfo *info;
6708 * Emit the generic trampolines.
6710 * We could save some code by treating the generic trampolines as a wrapper
6711 * method, but that approach has its own complexities, so we choose the simpler
6714 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6715 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6716 #ifdef DISABLE_REMOTING
6717 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6720 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6721 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6724 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6725 emit_trampoline (acfg, acfg->got_offset, info);
6728 /* Emit the exception related code pieces */
6729 mono_arch_get_restore_context (&info, TRUE);
6730 emit_trampoline (acfg, acfg->got_offset, info);
6731 mono_arch_get_call_filter (&info, TRUE);
6732 emit_trampoline (acfg, acfg->got_offset, info);
6733 mono_arch_get_throw_exception (&info, TRUE);
6734 emit_trampoline (acfg, acfg->got_offset, info);
6735 mono_arch_get_rethrow_exception (&info, TRUE);
6736 emit_trampoline (acfg, acfg->got_offset, info);
6737 mono_arch_get_throw_corlib_exception (&info, TRUE);
6738 emit_trampoline (acfg, acfg->got_offset, info);
6740 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6741 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6742 emit_trampoline (acfg, acfg->got_offset, info);
6743 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6744 emit_trampoline (acfg, acfg->got_offset, info);
6747 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6748 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6750 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6752 /* Create a separate out trampoline for more information in stack traces */
6753 info->name = g_strdup ("gsharedvt_out_trampoline");
6754 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6758 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6760 GSList *l = mono_arch_get_trampolines (TRUE);
6763 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6765 emit_trampoline (acfg, acfg->got_offset, info);
6771 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6774 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6775 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6776 emit_trampoline (acfg, acfg->got_offset, info);
6779 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6780 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6781 emit_trampoline (acfg, acfg->got_offset, info);
6785 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6786 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6787 emit_trampoline (acfg, acfg->got_offset, info);
6793 /* delegate_invoke_impl trampolines */
6794 l = mono_arch_get_delegate_invoke_impls ();
6796 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6798 emit_trampoline (acfg, acfg->got_offset, info);
6803 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6804 mono_arch_create_handler_block_trampoline (&info, TRUE);
6805 emit_trampoline (acfg, acfg->got_offset, info);
6808 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6810 /* Emit trampolines which are numerous */
6813 * These include the following:
6814 * - specific trampolines
6815 * - static rgctx invoke trampolines
6817 * These trampolines have the same code, they are parameterized by GOT
6819 * They are defined in this file, in the arch_... routines instead of
6820 * in tramp-<ARCH>.c, since it is easier to do it this way.
6824 * When running in aot-only mode, we can't create specific trampolines at
6825 * runtime, so we create a few, and save them in the AOT file.
6826 * Normal trampolines embed their argument as a literal inside the
6827 * trampoline code, we can't do that here, so instead we embed an offset
6828 * which needs to be added to the trampoline address to get the address of
6829 * the GOT slot which contains the argument value.
6830 * The generated trampolines jump to the generic trampolines using another
6831 * GOT slot, which will be setup by the AOT loader to point to the
6832 * generic trampoline code of the given type.
6836 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6840 emit_section_change (acfg, ".text", 0);
6842 tramp_got_offset = acfg->got_offset;
6844 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6846 case MONO_AOT_TRAMP_SPECIFIC:
6847 sprintf (symbol, "specific_trampolines");
6849 case MONO_AOT_TRAMP_STATIC_RGCTX:
6850 sprintf (symbol, "static_rgctx_trampolines");
6852 case MONO_AOT_TRAMP_IMT:
6853 sprintf (symbol, "imt_trampolines");
6855 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6856 sprintf (symbol, "gsharedvt_arg_trampolines");
6859 g_assert_not_reached ();
6862 sprintf (end_symbol, "%s_e", symbol);
6864 if (acfg->aot_opts.write_symbols)
6865 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6867 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6868 emit_info_symbol (acfg, symbol);
6870 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6872 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6876 case MONO_AOT_TRAMP_SPECIFIC:
6877 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6878 tramp_got_offset += 2;
6880 case MONO_AOT_TRAMP_STATIC_RGCTX:
6881 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6882 tramp_got_offset += 2;
6884 case MONO_AOT_TRAMP_IMT:
6885 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6886 tramp_got_offset += 1;
6888 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6889 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6890 tramp_got_offset += 2;
6893 g_assert_not_reached ();
6895 if (!acfg->trampoline_size [ntype]) {
6896 g_assert (tramp_size);
6897 acfg->trampoline_size [ntype] = tramp_size;
6901 emit_label (acfg, end_symbol);
6902 emit_int32 (acfg, 0);
6905 arch_emit_specific_trampoline_pages (acfg);
6907 /* Reserve some entries at the end of the GOT for our use */
6908 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6911 acfg->got_offset += acfg->num_trampoline_got_entries;
6915 str_begins_with (const char *str1, const char *str2)
6917 int len = strlen (str2);
6918 return strncmp (str1, str2, len) == 0;
6922 mono_aot_readonly_field_override (MonoClassField *field)
6925 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6926 char *p = rdv->name;
6928 len = strlen (field->parent->name_space);
6929 if (strncmp (p, field->parent->name_space, len))
6934 len = strlen (field->parent->name);
6935 if (strncmp (p, field->parent->name, len))
6940 if (strcmp (p, field->name))
6942 switch (rdv->type) {
6944 return &rdv->value.i1;
6946 return &rdv->value.i2;
6948 return &rdv->value.i4;
6957 add_readonly_value (MonoAotOptions *opts, const char *val)
6962 /* the format of val is:
6963 * namespace.typename.fieldname=type/value
6964 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6966 fval = strrchr (val, '/');
6968 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6971 tval = strrchr (val, '=');
6973 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6976 rdv = g_new0 (ReadOnlyValue, 1);
6977 rdv->name = (char *)g_malloc0 (tval - val + 1);
6978 memcpy (rdv->name, val, tval - val);
6981 if (strncmp (tval, "i1", 2) == 0) {
6982 rdv->value.i1 = atoi (fval);
6983 rdv->type = MONO_TYPE_I1;
6984 } else if (strncmp (tval, "i2", 2) == 0) {
6985 rdv->value.i2 = atoi (fval);
6986 rdv->type = MONO_TYPE_I2;
6987 } else if (strncmp (tval, "i4", 2) == 0) {
6988 rdv->value.i4 = atoi (fval);
6989 rdv->type = MONO_TYPE_I4;
6991 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6994 rdv->next = readonly_values;
6995 readonly_values = rdv;
6999 clean_path (gchar * path)
7004 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7007 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7014 wrap_path (gchar * path)
7020 // If the string contains no spaces, just return the original string.
7021 if (strstr (path, " ") == NULL)
7024 // If the string is already wrapped in quotes, return it.
7025 len = strlen (path);
7026 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7029 // If the string contains spaces, then wrap it in quotes.
7030 gchar *clean = g_strdup_printf ("\"%s\"", path);
7035 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7037 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7039 ptrdiff_t len = end-start;
7041 g_ptr_array_add (args, g_strndup (start, len));
7045 mono_aot_split_options (const char *aot_options)
7047 enum MonoAotOptionState {
7048 MONO_AOT_OPTION_STATE_DEFAULT,
7049 MONO_AOT_OPTION_STATE_STRING,
7050 MONO_AOT_OPTION_STATE_ESCAPE,
7053 GPtrArray *args = g_ptr_array_new ();
7054 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7055 gchar const *opt_start = aot_options;
7056 gboolean end_of_string = FALSE;
7059 g_return_val_if_fail (aot_options != NULL, NULL);
7061 while ((cur = *aot_options) != '\0') {
7062 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7067 // If we find a quote, then if we're in the default case then
7068 // it means we've found the start of a string, if not then it
7069 // means we've found the end of the string and should switch
7070 // back to the default case.
7072 case MONO_AOT_OPTION_STATE_DEFAULT:
7073 state = MONO_AOT_OPTION_STATE_STRING;
7075 case MONO_AOT_OPTION_STATE_STRING:
7076 state = MONO_AOT_OPTION_STATE_DEFAULT;
7078 case MONO_AOT_OPTION_STATE_ESCAPE:
7079 g_assert_not_reached ();
7084 // If we've found an escaping operator, then this means we
7085 // should not process the next character if inside a string.
7086 if (state == MONO_AOT_OPTION_STATE_STRING)
7087 state = MONO_AOT_OPTION_STATE_ESCAPE;
7090 // If we're in the default state then this means we've found
7091 // an option, store it for later processing.
7092 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7100 // If the next character is end of string, then process the last option.
7101 if (*(aot_options) == '\0') {
7102 end_of_string = TRUE;
7108 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7109 opt_start = ++aot_options;
7112 goto restart; // Check for null and continue loop
7119 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7123 args = mono_aot_split_options (aot_options ? aot_options : "");
7124 for (int i = 0; i < args->len; ++i) {
7125 const char *arg = (const char *)g_ptr_array_index (args, i);
7127 if (str_begins_with (arg, "outfile=")) {
7128 opts->outfile = g_strdup (arg + strlen ("outfile="));
7129 } else if (str_begins_with (arg, "llvm-outfile=")) {
7130 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7131 } else if (str_begins_with (arg, "temp-path=")) {
7132 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7133 } else if (str_begins_with (arg, "save-temps")) {
7134 opts->save_temps = TRUE;
7135 } else if (str_begins_with (arg, "keep-temps")) {
7136 opts->save_temps = TRUE;
7137 } else if (str_begins_with (arg, "write-symbols")) {
7138 opts->write_symbols = TRUE;
7139 } else if (str_begins_with (arg, "no-write-symbols")) {
7140 opts->write_symbols = FALSE;
7141 } else if (str_begins_with (arg, "metadata-only")) {
7142 opts->metadata_only = TRUE;
7143 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7144 opts->bind_to_runtime_version = TRUE;
7145 } else if (str_begins_with (arg, "full")) {
7146 opts->mode = MONO_AOT_MODE_FULL;
7147 } else if (str_begins_with (arg, "hybrid")) {
7148 opts->mode = MONO_AOT_MODE_HYBRID;
7149 } else if (str_begins_with (arg, "threads=")) {
7150 opts->nthreads = atoi (arg + strlen ("threads="));
7151 } else if (str_begins_with (arg, "static")) {
7152 opts->static_link = TRUE;
7153 opts->no_dlsym = TRUE;
7154 } else if (str_begins_with (arg, "asmonly")) {
7155 opts->asm_only = TRUE;
7156 } else if (str_begins_with (arg, "asmwriter")) {
7157 opts->asm_writer = TRUE;
7158 } else if (str_begins_with (arg, "nodebug")) {
7159 opts->nodebug = TRUE;
7160 } else if (str_begins_with (arg, "dwarfdebug")) {
7161 opts->dwarf_debug = TRUE;
7162 } else if (str_begins_with (arg, "nopagetrampolines")) {
7163 opts->use_trampolines_page = FALSE;
7164 } else if (str_begins_with (arg, "ntrampolines=")) {
7165 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7166 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7167 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7168 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7169 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7170 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7171 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7172 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7173 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7174 } else if (str_begins_with (arg, "tool-prefix=")) {
7175 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7176 } else if (str_begins_with (arg, "ld-flags=")) {
7177 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7178 } else if (str_begins_with (arg, "soft-debug")) {
7179 opts->soft_debug = TRUE;
7180 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7181 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7182 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7183 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7184 } else if (str_begins_with (arg, "msym-dir=")) {
7185 debug_options.no_seq_points_compact_data = FALSE;
7186 opts->gen_msym_dir = TRUE;
7187 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7188 } else if (str_begins_with (arg, "direct-pinvoke")) {
7189 opts->direct_pinvoke = TRUE;
7190 } else if (str_begins_with (arg, "direct-icalls")) {
7191 opts->direct_icalls = TRUE;
7192 } else if (str_begins_with (arg, "no-direct-calls")) {
7193 opts->no_direct_calls = TRUE;
7194 } else if (str_begins_with (arg, "print-skipped")) {
7195 opts->print_skipped_methods = TRUE;
7196 } else if (str_begins_with (arg, "stats")) {
7198 } else if (str_begins_with (arg, "no-instances")) {
7199 opts->no_instances = TRUE;
7200 } else if (str_begins_with (arg, "log-generics")) {
7201 opts->log_generics = TRUE;
7202 } else if (str_begins_with (arg, "log-instances=")) {
7203 opts->log_instances = TRUE;
7204 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7205 } else if (str_begins_with (arg, "log-instances")) {
7206 opts->log_instances = TRUE;
7207 } else if (str_begins_with (arg, "internal-logfile=")) {
7208 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7209 } else if (str_begins_with (arg, "mtriple=")) {
7210 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7211 } else if (str_begins_with (arg, "llvm-path=")) {
7212 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7213 } else if (!strcmp (arg, "llvm")) {
7215 } else if (str_begins_with (arg, "readonly-value=")) {
7216 add_readonly_value (opts, arg + strlen ("readonly-value="));
7217 } else if (str_begins_with (arg, "info")) {
7218 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7220 } else if (str_begins_with (arg, "gc-maps")) {
7221 mini_gc_enable_gc_maps_for_aot ();
7222 } else if (str_begins_with (arg, "dump")) {
7223 opts->dump_json = TRUE;
7224 } else if (str_begins_with (arg, "llvmonly")) {
7225 opts->mode = MONO_AOT_MODE_FULL;
7227 opts->llvm_only = TRUE;
7228 } else if (str_begins_with (arg, "data-outfile=")) {
7229 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7230 } else if (str_begins_with (arg, "profile=")) {
7231 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7232 } else if (!strcmp (arg, "profile-only")) {
7233 opts->profile_only = TRUE;
7234 } else if (!strcmp (arg, "verbose")) {
7235 opts->verbose = TRUE;
7236 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7237 printf ("Supported options for --aot:\n");
7238 printf (" outfile=\n");
7239 printf (" llvm-outfile=\n");
7240 printf (" llvm-path=\n");
7241 printf (" temp-path=\n");
7242 printf (" save-temps\n");
7243 printf (" keep-temps\n");
7244 printf (" write-symbols\n");
7245 printf (" metadata-only\n");
7246 printf (" bind-to-runtime-version\n");
7248 printf (" threads=\n");
7249 printf (" static\n");
7250 printf (" asmonly\n");
7251 printf (" asmwriter\n");
7252 printf (" nodebug\n");
7253 printf (" dwarfdebug\n");
7254 printf (" ntrampolines=\n");
7255 printf (" nrgctx-trampolines=\n");
7256 printf (" nimt-trampolines=\n");
7257 printf (" ngsharedvt-trampolines=\n");
7258 printf (" tool-prefix=\n");
7259 printf (" readonly-value=\n");
7260 printf (" soft-debug\n");
7261 printf (" msym-dir=\n");
7262 printf (" gc-maps\n");
7263 printf (" print-skipped\n");
7264 printf (" no-instances\n");
7265 printf (" stats\n");
7268 printf (" verbose\n");
7269 printf (" help/?\n");
7272 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7276 g_free ((gpointer) arg);
7279 if (opts->use_trampolines_page) {
7280 opts->ntrampolines = 0;
7281 opts->nrgctx_trampolines = 0;
7282 opts->nimt_trampolines = 0;
7283 opts->ngsharedvt_arg_trampolines = 0;
7286 g_ptr_array_free (args, /*free_seg=*/TRUE);
7290 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7292 MonoMethod *method = (MonoMethod*)key;
7293 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7294 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7295 MonoJumpInfoToken *new_ji;
7297 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7298 new_ji->image = ji->image;
7299 new_ji->token = ji->token;
7300 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7304 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7306 if (klass->type_token)
7308 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7311 return can_encode_class (acfg, klass->element_class);
7316 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7318 if (method->wrapper_type) {
7319 switch (method->wrapper_type) {
7320 case MONO_WRAPPER_NONE:
7321 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7322 case MONO_WRAPPER_XDOMAIN_INVOKE:
7323 case MONO_WRAPPER_STFLD:
7324 case MONO_WRAPPER_LDFLD:
7325 case MONO_WRAPPER_LDFLDA:
7326 case MONO_WRAPPER_STELEMREF:
7327 case MONO_WRAPPER_PROXY_ISINST:
7328 case MONO_WRAPPER_ALLOC:
7329 case MONO_WRAPPER_REMOTING_INVOKE:
7330 case MONO_WRAPPER_UNKNOWN:
7331 case MONO_WRAPPER_WRITE_BARRIER:
7332 case MONO_WRAPPER_DELEGATE_INVOKE:
7333 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7334 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7335 case MONO_WRAPPER_SYNCHRONIZED:
7337 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7338 case MONO_WRAPPER_CASTCLASS: {
7339 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7348 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7352 if (!method->token) {
7353 /* The method is part of a constructed type like Int[,].Set (). */
7354 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7355 if (method->klass->rank)
7365 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7367 switch (patch_info->type) {
7368 case MONO_PATCH_INFO_METHOD:
7369 case MONO_PATCH_INFO_METHODCONST:
7370 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7371 MonoMethod *method = patch_info->data.method;
7373 return can_encode_method (acfg, method);
7375 case MONO_PATCH_INFO_VTABLE:
7376 case MONO_PATCH_INFO_CLASS:
7377 case MONO_PATCH_INFO_IID:
7378 case MONO_PATCH_INFO_ADJUSTED_IID:
7379 if (!can_encode_class (acfg, patch_info->data.klass)) {
7380 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7384 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7385 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7386 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7391 case MONO_PATCH_INFO_RGCTX_FETCH:
7392 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7393 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7395 if (!can_encode_method (acfg, entry->method))
7397 if (!can_encode_patch (acfg, entry->data))
7409 is_concrete_type (MonoType *t)
7414 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7416 if (t->type == MONO_TYPE_GENERICINST) {
7417 MonoGenericContext *orig_ctx;
7418 MonoGenericInst *inst;
7421 if (!MONO_TYPE_ISSTRUCT (t))
7423 klass = mono_class_from_mono_type (t);
7424 orig_ctx = &mono_class_get_generic_class (klass)->context;
7426 inst = orig_ctx->class_inst;
7428 for (i = 0; i < inst->type_argc; ++i) {
7429 arg = mini_get_underlying_type (inst->type_argv [i]);
7430 if (!is_concrete_type (arg))
7434 inst = orig_ctx->method_inst;
7436 for (i = 0; i < inst->type_argc; ++i) {
7437 arg = mini_get_underlying_type (inst->type_argv [i]);
7438 if (!is_concrete_type (arg))
7446 /* LOCKING: Assumes the loader lock is held */
7448 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7450 MonoMethod *wrapper;
7451 gboolean concrete = TRUE;
7452 gboolean add_in = gsharedvt_in;
7453 gboolean add_out = gsharedvt_out;
7455 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7457 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7460 if (!add_in && !add_out)
7463 if (mini_is_gsharedvt_variable_signature (sig))
7467 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7469 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7471 if (!sig->has_type_parameters) {
7472 //printf ("%s\n", mono_signature_full_name (sig));
7475 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7476 add_extra_method (acfg, wrapper);
7478 if (gsharedvt_out) {
7479 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7480 add_extra_method (acfg, wrapper);
7483 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7484 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7487 //printf ("%s\n", mono_signature_full_name (sig));
7489 copy->ret = mini_get_underlying_type (sig->ret);
7490 if (!is_concrete_type (copy->ret))
7492 for (i = 0; i < sig->param_count; ++i) {
7493 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7494 if (!is_concrete_type (copy->params [i]))
7498 copy->has_type_parameters = 0;
7501 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7502 add_extra_method (acfg, wrapper);
7505 if (gsharedvt_out) {
7506 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7507 add_extra_method (acfg, wrapper);
7510 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7518 * AOT compile a given method.
7519 * This function might be called by multiple threads, so it must be thread-safe.
7522 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7525 MonoJumpInfo *patch_info;
7528 MonoMethod *wrapped;
7532 if (acfg->aot_opts.metadata_only)
7535 mono_acfg_lock (acfg);
7536 index = get_method_index (acfg, method);
7537 mono_acfg_unlock (acfg);
7539 /* fixme: maybe we can also precompile wrapper methods */
7540 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7541 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7542 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7543 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7547 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7550 wrapped = mono_marshal_method_from_wrapper (method);
7551 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7552 // FIXME: The wrapper should be generic too, but it is not
7555 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7558 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7561 InterlockedIncrement (&acfg->stats.mcount);
7564 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7565 InterlockedIncrement (&acfg->stats.genericcount);
7570 //acfg->aot_opts.print_skipped_methods = TRUE;
7573 * Since these methods are the only ones which are compiled with
7574 * AOT support, and they are not used by runtime startup/shutdown code,
7575 * the runtime will not see AOT methods during AOT compilation,so it
7576 * does not need to support them by creating a fake GOT etc.
7578 flags = JIT_FLAG_AOT;
7579 if (mono_aot_mode_is_full (&acfg->aot_opts))
7580 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7582 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7583 if (acfg->aot_opts.llvm_only)
7584 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7585 if (acfg->aot_opts.no_direct_calls)
7586 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7587 if (acfg->aot_opts.direct_pinvoke)
7588 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7590 jit_timer = mono_time_track_start ();
7591 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7592 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7594 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7595 if (acfg->aot_opts.print_skipped_methods)
7596 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7597 InterlockedIncrement (&acfg->stats.genericcount);
7600 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7601 if (acfg->aot_opts.print_skipped_methods) {
7602 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7603 if (cfg->exception_message)
7604 printf ("Caused by: %s\n", cfg->exception_message);
7606 /* Let the exception happen at runtime */
7610 if (cfg->disable_aot) {
7611 if (acfg->aot_opts.print_skipped_methods)
7612 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7613 InterlockedIncrement (&acfg->stats.ocount);
7616 cfg->method_index = index;
7618 /* Nullify patches which need no aot processing */
7619 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7620 switch (patch_info->type) {
7621 case MONO_PATCH_INFO_LABEL:
7622 case MONO_PATCH_INFO_BB:
7623 patch_info->type = MONO_PATCH_INFO_NONE;
7630 /* Collect method->token associations from the cfg */
7631 mono_acfg_lock (acfg);
7632 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7633 mono_acfg_unlock (acfg);
7634 g_hash_table_destroy (cfg->token_info_hash);
7635 cfg->token_info_hash = NULL;
7638 * Check for absolute addresses.
7641 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7642 switch (patch_info->type) {
7643 case MONO_PATCH_INFO_ABS:
7644 /* unable to handle this */
7653 if (acfg->aot_opts.print_skipped_methods)
7654 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7655 InterlockedIncrement (&acfg->stats.abscount);
7659 /* Lock for the rest of the code */
7660 mono_acfg_lock (acfg);
7663 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7664 else if (cfg->gshared)
7665 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7666 else if (cfg->method->wrapper_type)
7667 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7669 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7672 * Check for methods/klasses we can't encode.
7675 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7676 if (!can_encode_patch (acfg, patch_info))
7681 if (acfg->aot_opts.print_skipped_methods)
7682 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7683 acfg->stats.ocount++;
7684 mono_acfg_unlock (acfg);
7688 if (!cfg->compile_llvm)
7689 acfg->has_jitted_code = TRUE;
7691 if (method->is_inflated && acfg->aot_opts.log_instances) {
7692 if (acfg->instances_logfile)
7693 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7695 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7698 /* Adds generic instances referenced by this method */
7700 * The depth is used to avoid infinite loops when generic virtual recursion is
7703 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7704 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7705 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7706 switch (patch_info->type) {
7707 case MONO_PATCH_INFO_RGCTX_FETCH:
7708 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7709 case MONO_PATCH_INFO_METHOD: {
7710 MonoMethod *m = NULL;
7712 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7713 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7715 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7716 m = e->data->data.method;
7718 m = patch_info->data.method;
7723 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7724 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7725 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7726 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7727 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7728 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7729 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7731 add_extra_method_with_depth (acfg, m, depth + 1);
7732 add_types_from_method_header (acfg, m);
7735 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7737 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7738 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7740 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7741 add_extra_method_with_depth (acfg, m, depth + 1);
7745 case MONO_PATCH_INFO_VTABLE: {
7746 MonoClass *klass = patch_info->data.klass;
7748 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7749 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7752 case MONO_PATCH_INFO_SFLDA: {
7753 MonoClass *klass = patch_info->data.field->parent;
7755 /* The .cctor needs to run at runtime. */
7756 if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7757 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7766 /* Determine whenever the method has GOT slots */
7767 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7768 switch (patch_info->type) {
7769 case MONO_PATCH_INFO_GOT_OFFSET:
7770 case MONO_PATCH_INFO_NONE:
7771 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7772 case MONO_PATCH_INFO_GC_NURSERY_START:
7773 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7775 case MONO_PATCH_INFO_IMAGE:
7776 /* The assembly is stored in GOT slot 0 */
7777 if (patch_info->data.image != acfg->image)
7778 cfg->has_got_slots = TRUE;
7781 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7782 cfg->has_got_slots = TRUE;
7787 if (!cfg->has_got_slots)
7788 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7790 /* Add gsharedvt wrappers for signatures used by the method */
7791 if (acfg->aot_opts.llvm_only) {
7794 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7795 /* These only need out wrappers */
7796 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7798 for (l = cfg->signatures; l; l = l->next) {
7799 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7801 /* These only need in wrappers */
7802 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7807 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7809 /* Make a copy of the patch info which is in the mempool */
7811 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7813 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7814 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7817 patches = new_patch_info;
7819 patches_end->next = new_patch_info;
7820 patches_end = new_patch_info;
7822 cfg->patch_info = patches;
7824 /* Make a copy of the unwind info */
7826 GSList *l, *unwind_ops;
7830 for (l = cfg->unwind_ops; l; l = l->next) {
7831 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7832 memcpy (op, l->data, sizeof (MonoUnwindOp));
7833 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7835 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7837 /* Make a copy of the argument/local info */
7840 MonoInst **args, **locals;
7841 MonoMethodSignature *sig;
7842 MonoMethodHeader *header;
7845 sig = mono_method_signature (method);
7846 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7847 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7848 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7849 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7853 header = mono_method_get_header_checked (method, &error);
7854 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7855 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7856 for (i = 0; i < header->num_locals; ++i) {
7857 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7858 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7860 mono_metadata_free_mh (header);
7861 cfg->locals = locals;
7864 /* Free some fields used by cfg to conserve memory */
7865 mono_empty_compile (cfg);
7867 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7869 while (index >= acfg->cfgs_size) {
7870 MonoCompile **new_cfgs;
7873 new_size = acfg->cfgs_size * 2;
7874 new_cfgs = g_new0 (MonoCompile*, new_size);
7875 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7876 g_free (acfg->cfgs);
7877 acfg->cfgs = new_cfgs;
7878 acfg->cfgs_size = new_size;
7880 acfg->cfgs [index] = cfg;
7882 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7884 mono_update_jit_stats (cfg);
7887 if (cfg->orig_method->wrapper_type)
7888 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7891 mono_acfg_unlock (acfg);
7893 InterlockedIncrement (&acfg->stats.ccount);
7896 static mono_thread_start_return_t WINAPI
7897 compile_thread_main (gpointer user_data)
7899 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7900 GPtrArray *methods = ((GPtrArray **)user_data) [1];
7904 MonoInternalThread *internal = mono_thread_internal_current ();
7905 mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "AOT compiler"), TRUE, FALSE, &error);
7906 mono_error_assert_ok (&error);
7908 for (i = 0; i < methods->len; ++i)
7909 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7914 /* Used by the LLVM backend */
7916 mono_aot_get_got_offset (MonoJumpInfo *ji)
7918 return get_got_offset (llvm_acfg, TRUE, ji);
7922 * mono_aot_is_shared_got_offset:
7924 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7925 * when the AOT image is loaded.
7928 mono_aot_is_shared_got_offset (int offset)
7930 return offset < llvm_acfg->nshared_got_entries;
7934 mono_aot_get_method_name (MonoCompile *cfg)
7936 if (llvm_acfg->aot_opts.static_link)
7937 /* Include the assembly name too to avoid duplicate symbol errors */
7938 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7940 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7944 * mono_aot_is_linkonce_method:
7946 * Return whenever METHOD should be emitted with linkonce linkage,
7947 * eliminating duplicate copies when compiling in static mode.
7950 mono_aot_is_linkonce_method (MonoMethod *method)
7956 // FIXME: Add more cases
7957 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7959 info = mono_marshal_get_wrapper_info (method);
7960 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7967 append_mangled_type (GString *s, MonoType *t)
7970 g_string_append_printf (s, "b");
7972 case MONO_TYPE_VOID:
7973 g_string_append_printf (s, "void_");
7976 g_string_append_printf (s, "i1");
7979 g_string_append_printf (s, "u1");
7982 g_string_append_printf (s, "i2");
7985 g_string_append_printf (s, "u2");
7988 g_string_append_printf (s, "i4");
7991 g_string_append_printf (s, "u4");
7994 g_string_append_printf (s, "i8");
7997 g_string_append_printf (s, "u8");
8000 g_string_append_printf (s, "ii");
8003 g_string_append_printf (s, "ui");
8006 g_string_append_printf (s, "fl");
8009 g_string_append_printf (s, "do");
8012 char *fullname = mono_type_full_name (t);
8018 * Have to create a mangled name which is:
8022 temp = g_string_new ("");
8023 len = strlen (fullname);
8024 for (i = 0; i < len; ++i) {
8025 char c = fullname [i];
8027 g_string_append_c (temp, c);
8028 } else if (c == '_') {
8029 g_string_append_c (temp, '_');
8030 g_string_append_c (temp, '_');
8032 g_string_append_c (temp, '_');
8033 g_string_append_printf (temp, "%x", (int)c);
8036 temps = g_string_free (temp, FALSE);
8037 /* Include the length to avoid different length type names aliasing each other */
8038 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8047 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8052 supported = append_mangled_type (s, sig->ret);
8056 g_string_append_printf (s, "this_");
8057 for (i = 0; i < sig->param_count; ++i) {
8058 supported = append_mangled_type (s, sig->params [i]);
8067 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8071 switch (wrapper_type) {
8072 case MONO_WRAPPER_REMOTING_INVOKE:
8073 label = "remoting_invoke";
8075 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8076 label = "remoting_invoke_check";
8078 case MONO_WRAPPER_XDOMAIN_INVOKE:
8079 label = "remoting_invoke_xdomain";
8081 case MONO_WRAPPER_PROXY_ISINST:
8082 label = "proxy_isinst";
8084 case MONO_WRAPPER_LDFLD:
8087 case MONO_WRAPPER_LDFLDA:
8090 case MONO_WRAPPER_STFLD:
8093 case MONO_WRAPPER_ALLOC:
8096 case MONO_WRAPPER_WRITE_BARRIER:
8097 label = "write_barrier";
8099 case MONO_WRAPPER_STELEMREF:
8100 label = "stelemref";
8102 case MONO_WRAPPER_UNKNOWN:
8105 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8106 label = "man2native";
8108 case MONO_WRAPPER_SYNCHRONIZED:
8111 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8114 case MONO_WRAPPER_CASTCLASS:
8115 label = "castclass";
8117 case MONO_WRAPPER_RUNTIME_INVOKE:
8118 label = "run_invoke";
8120 case MONO_WRAPPER_DELEGATE_INVOKE:
8123 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8124 label = "del_beg_inv";
8126 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8127 label = "del_end_inv";
8129 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8130 label = "native2man";
8133 g_assert_not_reached ();
8136 g_string_append_printf (s, "%s_", label);
8140 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8146 case WRAPPER_SUBTYPE_NONE:
8148 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8149 label = "elem_addr";
8151 case WRAPPER_SUBTYPE_STRING_CTOR:
8154 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8155 label = "virt_stelem";
8157 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8158 label = "fast_mon_enter";
8160 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8161 label = "fast_mon_enter_4";
8163 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8164 label = "fast_monitor_exit";
8166 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8167 label = "ptr2struct";
8169 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8170 label = "struct2ptr";
8172 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8173 label = "castclass_w_cache";
8175 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8176 label = "isinst_w_cache";
8178 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8179 label = "run_inv_norm";
8181 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8182 label = "run_inv_dyn";
8184 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8185 label = "run_inv_dir";
8187 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8188 label = "run_inv_vir";
8190 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8193 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8194 label = "native_func_aot";
8196 case WRAPPER_SUBTYPE_PINVOKE:
8199 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8200 label = "synch_inner";
8202 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8203 label = "gshared_in";
8205 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8206 label = "gshared_out";
8208 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8209 label = "array_acc";
8211 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8212 label = "generic_arry_help";
8214 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8215 label = "del_inv_virt";
8217 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8218 label = "del_inv_bound";
8220 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8221 label = "gsharedvt_in_sig";
8223 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8224 label = "gsharedvt_out_sig";
8227 g_assert_not_reached ();
8230 g_string_append_printf (s, "%s_", label);
8234 sanitize_mangled_string (const char *input)
8236 GString *s = g_string_new ("");
8238 for (int i=0; input [i] != '\0'; i++) {
8242 g_string_append (s, "_dot_");
8245 g_string_append (s, "_");
8248 g_string_append (s, "_bt_");
8251 g_string_append (s, "_le_");
8254 g_string_append (s, "_gt_");
8257 g_string_append (s, "_sl_");
8260 g_string_append (s, "_lbrack_");
8263 g_string_append (s, "_rbrack_");
8266 g_string_append (s, "_lparen_");
8269 g_string_append (s, "_dash_");
8272 g_string_append (s, "_rparen_");
8275 g_string_append (s, "_comma_");
8278 g_string_append_c (s, c);
8282 return g_string_free (s, FALSE);
8286 append_mangled_klass (GString *s, MonoClass *klass)
8288 char *klass_desc = mono_class_full_name (klass);
8289 g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8290 g_free (klass_desc);
8297 append_mangled_method (GString *s, MonoMethod *method);
8300 append_mangled_wrapper (GString *s, MonoMethod *method)
8302 gboolean success = TRUE;
8303 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8304 g_string_append_printf (s, "wrapper_");
8306 append_mangled_wrapper_type (s, method->wrapper_type);
8308 switch (method->wrapper_type) {
8309 case MONO_WRAPPER_REMOTING_INVOKE:
8310 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8311 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8312 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8314 success = success && append_mangled_method (s, m);
8317 case MONO_WRAPPER_PROXY_ISINST:
8318 case MONO_WRAPPER_LDFLD:
8319 case MONO_WRAPPER_LDFLDA:
8320 case MONO_WRAPPER_STFLD: {
8322 success = success && append_mangled_klass (s, info->d.proxy.klass);
8325 case MONO_WRAPPER_ALLOC: {
8326 /* The GC name is saved once in MonoAotFileInfo */
8327 g_assert (info->d.alloc.alloc_type != -1);
8328 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8330 g_string_append_printf (s, "%s_", method->name);
8333 case MONO_WRAPPER_WRITE_BARRIER: {
8336 case MONO_WRAPPER_STELEMREF: {
8337 append_mangled_wrapper_subtype (s, info->subtype);
8338 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8339 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8342 case MONO_WRAPPER_UNKNOWN: {
8343 append_mangled_wrapper_subtype (s, info->subtype);
8344 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8345 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8346 success = success && append_mangled_klass (s, method->klass);
8347 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8348 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8349 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8350 success = success && append_mangled_method (s, info->d.array_accessor.method);
8351 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8352 append_mangled_signature (s, info->d.gsharedvt.sig);
8353 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8354 append_mangled_signature (s, info->d.gsharedvt.sig);
8357 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8358 append_mangled_wrapper_subtype (s, info->subtype);
8359 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8360 g_string_append_printf (s, "%s", method->name);
8361 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8362 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8364 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8365 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8369 case MONO_WRAPPER_SYNCHRONIZED: {
8372 m = mono_marshal_method_from_wrapper (method);
8374 g_assert (m != method);
8375 success = success && append_mangled_method (s, m);
8378 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8379 append_mangled_wrapper_subtype (s, info->subtype);
8381 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8382 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8383 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8384 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8385 success = success && append_mangled_method (s, info->d.string_ctor.method);
8387 g_assert_not_reached ();
8391 case MONO_WRAPPER_CASTCLASS: {
8392 append_mangled_wrapper_subtype (s, info->subtype);
8395 case MONO_WRAPPER_RUNTIME_INVOKE: {
8396 append_mangled_wrapper_subtype (s, info->subtype);
8397 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8398 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8399 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8400 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8403 case MONO_WRAPPER_DELEGATE_INVOKE:
8404 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8405 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8406 if (method->is_inflated) {
8407 /* These wrappers are identified by their class */
8408 g_string_append_printf (s, "i_");
8409 success = success && append_mangled_klass (s, method->klass);
8411 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8413 g_string_append_printf (s, "u_");
8414 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8415 append_mangled_wrapper_subtype (s, info->subtype);
8416 g_string_append_printf (s, "u_sigstart");
8420 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8422 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8423 success = success && append_mangled_klass (s, method->klass);
8427 g_assert_not_reached ();
8429 return success && append_mangled_signature (s, mono_method_signature (method));
8433 append_mangled_context (GString *str, MonoGenericContext *context)
8435 GString *res = g_string_new ("");
8437 g_string_append_printf (res, "gens_");
8438 g_string_append (res, "00");
8440 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8441 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8444 if (context->class_inst)
8445 mono_ginst_get_desc (res, context->class_inst);
8446 if (context->method_inst) {
8447 if (context->class_inst)
8448 g_string_append (res, "11");
8449 mono_ginst_get_desc (res, context->method_inst);
8451 g_string_append_printf (str, "gens_%s", res->str);
8455 append_mangled_method (GString *s, MonoMethod *method)
8457 if (method->wrapper_type)
8458 return append_mangled_wrapper (s, method);
8460 g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8462 if (method->is_inflated) {
8463 g_string_append_printf (s, "inflated_");
8464 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8465 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8467 append_mangled_context (s, &imethod->context);
8468 g_string_append_printf (s, "_declared_by_");
8469 append_mangled_method (s, imethod->declaring);
8470 } else if (method->is_generic) {
8471 g_string_append_printf (s, "generic_");
8472 append_mangled_klass (s, method->klass);
8473 g_string_append_printf (s, "_%s_", method->name);
8475 MonoGenericContainer *container = mono_method_get_generic_container (method);
8476 g_string_append_printf (s, "_%s");
8477 append_mangled_context (s, &container->context);
8479 return append_mangled_signature (s, mono_method_signature (method));
8481 g_string_append_printf (s, "_");
8482 append_mangled_klass (s, method->klass);
8483 g_string_append_printf (s, "_%s_", method->name);
8484 if (!append_mangled_signature (s, mono_method_signature (method))) {
8485 g_string_free (s, TRUE);
8494 * mono_aot_get_mangled_method_name:
8496 * Return a unique mangled name for METHOD, or NULL.
8499 mono_aot_get_mangled_method_name (MonoMethod *method)
8501 GString *s = g_string_new ("aot_");
8502 if (!append_mangled_method (s, method)) {
8503 g_string_free (s, TRUE);
8506 char *out = g_string_free (s, FALSE);
8507 // Scrub method and class names
8508 char *cleaned = sanitize_mangled_string (out);
8515 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8517 return is_direct_callable (llvm_acfg, NULL, patch_info);
8521 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8523 MonoPltEntry *plt_entry;
8525 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8526 plt_entry->llvm_used = FALSE;
8530 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8532 const char *sym = NULL;
8534 if (llvm_acfg->aot_opts.direct_icalls) {
8535 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8536 /* Call to a C function implementing a jit icall */
8537 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8538 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8539 MonoMethod *method = (MonoMethod *)data;
8540 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8541 sym = mono_lookup_icall_symbol (method);
8542 else if (llvm_acfg->aot_opts.direct_pinvoke)
8543 sym = get_pinvoke_import (llvm_acfg, method);
8546 return g_strdup (sym);
8552 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8554 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8555 MonoPltEntry *plt_entry;
8556 const char *sym = NULL;
8559 ji->data.target = data;
8561 if (!can_encode_patch (llvm_acfg, ji))
8564 if (llvm_acfg->aot_opts.direct_icalls) {
8565 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8566 /* Call to a C function implementing a jit icall */
8567 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8568 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8569 MonoMethod *method = (MonoMethod *)data;
8570 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8571 sym = mono_lookup_icall_symbol (method);
8574 return g_strdup (sym);
8577 plt_entry = get_plt_entry (llvm_acfg, ji);
8578 plt_entry->llvm_used = TRUE;
8580 #if defined(TARGET_MACH)
8581 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8583 return g_strdup_printf (plt_entry->llvm_symbol);
8588 mono_aot_get_method_index (MonoMethod *method)
8590 g_assert (llvm_acfg);
8591 return get_method_index (llvm_acfg, method);
8595 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8599 mono_acfg_lock (llvm_acfg);
8600 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8601 mono_acfg_unlock (llvm_acfg);
8607 execute_system (const char * command)
8611 #if defined(HOST_WIN32) && defined(HAVE_SYSTEM)
8612 // We need an extra set of quotes around the whole command to properly handle commands
8613 // with spaces since internally the command is called through "cmd /c.
8614 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8616 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8617 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8618 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8619 status = _wsystem (wstr);
8622 g_free (quoted_command);
8623 #elif defined (HAVE_SYSTEM)
8624 status = system (command);
8626 g_assert_not_reached ();
8637 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8641 emit_llvm_file (MonoAotCompile *acfg)
8643 char *command, *opts, *tempbc, *optbc, *output_fname;
8645 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8646 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8647 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8649 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8650 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8653 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8656 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8657 * a lot of time, and doesn't seem to save much space.
8658 * The following optimizations cannot be enabled:
8660 * - 'jump-threading' changes our blockaddress references to int constants.
8661 * - 'basiccg' fails because it contains:
8662 * if (CS && !isa<IntrinsicInst>(II)) {
8663 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8664 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8665 * The opt list below was produced by taking the output of:
8666 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8667 * then removing tailcallelim + the global opts.
8668 * strip-dead-prototypes deletes unused intrinsics definitions.
8670 /* The dse pass is disabled because of #13734 and #17616 */
8672 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8673 * // If we have no DataLayout information around, then the size of the store
8674 * // is inferrable from the pointee type. If they are the same type, then
8675 * // we know that the store is safe.
8676 * if (AA.getDataLayout() == 0 &&
8677 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8678 * return OverwriteComplete;
8679 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8681 if (acfg->aot_opts.llvm_only)
8682 // FIXME: This doesn't work yet
8683 opts = g_strdup ("");
8685 #if LLVM_API_VERSION > 100
8686 opts = g_strdup ("-O2 -disable-tail-calls");
8688 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");
8690 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8691 aot_printf (acfg, "Executing opt: %s\n", command);
8692 if (execute_system (command) != 0)
8696 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8697 /* Nothing else to do */
8700 if (acfg->aot_opts.llvm_only) {
8701 /* Use the stock clang from xcode */
8703 command = g_strdup_printf ("clang++ -fexceptions -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);
8705 aot_printf (acfg, "Executing clang: %s\n", command);
8706 if (execute_system (command) != 0)
8711 if (!acfg->llc_args)
8712 acfg->llc_args = g_string_new ("");
8714 /* Verbose asm slows down llc greatly */
8715 g_string_append (acfg->llc_args, " -asm-verbose=false");
8717 if (acfg->aot_opts.mtriple)
8718 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8720 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8722 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8724 #if LLVM_API_VERSION > 100
8725 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8728 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8729 /* ios requires PIC code now */
8730 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8732 if (llvm_acfg->aot_opts.static_link)
8733 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8735 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8738 if (acfg->llvm_owriter) {
8739 /* Emit an object file directly */
8740 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8741 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8743 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8745 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8746 g_free (output_fname);
8748 aot_printf (acfg, "Executing llc: %s\n", command);
8750 if (execute_system (command) != 0)
8757 emit_code (MonoAotCompile *acfg)
8759 int oindex, i, prev_index;
8760 gboolean saved_unbox_info = FALSE;
8761 char symbol [MAX_SYMBOL_SIZE];
8763 if (acfg->aot_opts.llvm_only)
8766 #if defined(TARGET_POWERPC64)
8767 sprintf (symbol, ".Lgot_addr");
8768 emit_section_change (acfg, ".text", 0);
8769 emit_alignment (acfg, 8);
8770 emit_label (acfg, symbol);
8771 emit_pointer (acfg, acfg->got_symbol);
8775 * This global symbol is used to compute the address of each method using the
8776 * code_offsets array. It is also used to compute the memory ranges occupied by
8777 * AOT code, so it must be equal to the address of the first emitted method.
8779 emit_section_change (acfg, ".text", 0);
8780 emit_alignment_code (acfg, 8);
8781 emit_info_symbol (acfg, "jit_code_start");
8784 * Emit some padding so the local symbol for the first method doesn't have the
8785 * same address as 'methods'.
8787 emit_padding (acfg, 16);
8789 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8793 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8795 cfg = acfg->cfgs [i];
8800 method = cfg->orig_method;
8802 /* Emit unbox trampoline */
8803 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8804 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8806 emit_section_change (acfg, ".text", 0);
8808 if (acfg->thumb_mixed && cfg->compile_llvm) {
8809 emit_set_thumb_mode (acfg);
8810 fprintf (acfg->fp, "\n.thumb_func\n");
8813 emit_label (acfg, symbol);
8815 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8817 if (acfg->thumb_mixed && cfg->compile_llvm)
8818 emit_set_arm_mode (acfg);
8820 if (!saved_unbox_info) {
8821 char user_symbol [128];
8823 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8825 emit_label (acfg, "ut_end");
8827 unwind_ops = mono_unwind_get_cie_program ();
8828 save_unwind_info (acfg, user_symbol, unwind_ops);
8829 mono_free_unwind_info (unwind_ops);
8831 /* Save the unbox trampoline size */
8832 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8834 saved_unbox_info = TRUE;
8838 if (cfg->compile_llvm)
8839 acfg->stats.llvm_count ++;
8841 emit_method_code (acfg, cfg);
8844 emit_section_change (acfg, ".text", 0);
8845 emit_alignment_code (acfg, 8);
8846 emit_info_symbol (acfg, "jit_code_end");
8848 /* To distinguish it from the next symbol */
8849 emit_padding (acfg, 4);
8852 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8853 * from optimizing them away, since it doesn't see that code_offsets references them.
8854 * JITted methods don't need this since they are referenced using assembler local
8856 * FIXME: This is why write-symbols doesn't work on OSX ?
8858 if (acfg->llvm && acfg->need_no_dead_strip) {
8859 fprintf (acfg->fp, "\n");
8860 for (i = 0; i < acfg->nmethods; ++i) {
8861 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8862 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8867 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8868 * This is PIE code, and the linker can update it if needed.
8871 sprintf (symbol, "method_addresses");
8872 emit_section_change (acfg, ".text", 1);
8873 emit_alignment_code (acfg, 8);
8874 emit_info_symbol (acfg, symbol);
8875 if (acfg->aot_opts.write_symbols)
8876 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8877 emit_unset_mode (acfg);
8878 if (acfg->need_no_dead_strip)
8879 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8881 for (i = 0; i < acfg->nmethods; ++i) {
8882 #ifdef MONO_ARCH_AOT_SUPPORTED
8885 if (acfg->cfgs [i]) {
8886 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8888 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8893 sprintf (symbol, "method_addresses_end");
8894 emit_label (acfg, symbol);
8897 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8898 sprintf (symbol, "unbox_trampolines");
8899 emit_section_change (acfg, RODATA_SECT, 0);
8900 emit_alignment (acfg, 8);
8901 emit_info_symbol (acfg, symbol);
8904 for (i = 0; i < acfg->nmethods; ++i) {
8909 cfg = acfg->cfgs [i];
8913 method = cfg->orig_method;
8915 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8916 index = get_method_index (acfg, method);
8918 emit_int32 (acfg, index);
8919 /* Make sure the table is sorted by index */
8920 g_assert (index > prev_index);
8924 sprintf (symbol, "unbox_trampolines_end");
8925 emit_info_symbol (acfg, symbol);
8926 emit_int32 (acfg, 0);
8928 /* Emit a separate table with the trampoline addresses/offsets */
8929 sprintf (symbol, "unbox_trampoline_addresses");
8930 emit_section_change (acfg, ".text", 0);
8931 emit_alignment_code (acfg, 8);
8932 emit_info_symbol (acfg, symbol);
8934 for (i = 0; i < acfg->nmethods; ++i) {
8939 cfg = acfg->cfgs [i];
8943 method = cfg->orig_method;
8945 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8946 #ifdef MONO_ARCH_AOT_SUPPORTED
8949 index = get_method_index (acfg, method);
8950 sprintf (symbol, "ut_%d", index);
8952 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8956 emit_int32 (acfg, 0);
8960 emit_info (MonoAotCompile *acfg)
8965 offsets = g_new0 (gint32, acfg->nmethods);
8967 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8968 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8970 if (acfg->cfgs [i]) {
8971 emit_method_info (acfg, acfg->cfgs [i]);
8972 offsets [i] = acfg->cfgs [i]->method_info_offset;
8978 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8983 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8985 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8986 #define mix(a,b,c) { \
8987 a -= c; a ^= rot(c, 4); c += b; \
8988 b -= a; b ^= rot(a, 6); a += c; \
8989 c -= b; c ^= rot(b, 8); b += a; \
8990 a -= c; a ^= rot(c,16); c += b; \
8991 b -= a; b ^= rot(a,19); a += c; \
8992 c -= b; c ^= rot(b, 4); b += a; \
8994 #define final(a,b,c) { \
8995 c ^= b; c -= rot(b,14); \
8996 a ^= c; a -= rot(c,11); \
8997 b ^= a; b -= rot(a,25); \
8998 c ^= b; c -= rot(b,16); \
8999 a ^= c; a -= rot(c,4); \
9000 b ^= a; b -= rot(a,14); \
9001 c ^= b; c -= rot(b,24); \
9005 mono_aot_type_hash (MonoType *t1)
9007 guint hash = t1->type;
9009 hash |= t1->byref << 6; /* do not collide with t1->type values */
9011 case MONO_TYPE_VALUETYPE:
9012 case MONO_TYPE_CLASS:
9013 case MONO_TYPE_SZARRAY:
9014 /* check if the distribution is good enough */
9015 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9017 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9018 case MONO_TYPE_ARRAY:
9019 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9020 case MONO_TYPE_GENERICINST:
9021 return ((hash << 5) - hash) ^ 0;
9028 * mono_aot_method_hash:
9030 * Return a hash code for methods which only depends on metadata.
9033 mono_aot_method_hash (MonoMethod *method)
9035 MonoMethodSignature *sig;
9039 guint32 *hashes_start, *hashes;
9041 MonoGenericInst *class_ginst = NULL;
9042 MonoGenericInst *ginst = NULL;
9044 /* Similar to the hash in mono_method_get_imt_slot () */
9046 sig = mono_method_signature (method);
9048 if (mono_class_is_ginst (method->klass))
9049 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9050 if (method->is_inflated)
9051 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9053 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9054 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9055 hashes = hashes_start;
9057 /* Some wrappers are assigned to random classes */
9058 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9059 klass = method->klass;
9061 klass = mono_defaults.object_class;
9063 if (!method->wrapper_type) {
9066 if (mono_class_is_ginst (klass))
9067 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9069 full_name = mono_type_full_name (&klass->byval_arg);
9071 hashes [0] = mono_metadata_str_hash (full_name);
9075 hashes [0] = mono_metadata_str_hash (klass->name);
9076 hashes [1] = mono_metadata_str_hash (klass->name_space);
9078 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9079 /* The method name includes a stringified pointer */
9082 hashes [2] = mono_metadata_str_hash (method->name);
9083 hashes [3] = method->wrapper_type;
9084 hashes [4] = mono_aot_type_hash (sig->ret);
9086 for (i = 0; i < sig->param_count; i++) {
9087 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9090 for (i = 0; i < class_ginst->type_argc; ++i)
9091 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9094 for (i = 0; i < ginst->type_argc; ++i)
9095 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9097 g_assert (hindex == hashes_count);
9099 /* Setup internal state */
9100 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9102 /* Handle most of the hashes */
9103 while (hashes_count > 3) {
9112 /* Handle the last 3 hashes (all the case statements fall through) */
9113 switch (hashes_count) {
9114 case 3 : c += hashes [2];
9115 case 2 : b += hashes [1];
9116 case 1 : a += hashes [0];
9118 case 0: /* nothing left to add */
9122 g_free (hashes_start);
9131 * mono_aot_get_array_helper_from_wrapper;
9133 * Get the helper method in Array called by an array wrapper method.
9136 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9140 MonoGenericContext ctx;
9141 MonoType *args [16];
9142 char *mname, *iname, *s, *s2, *helper_name = NULL;
9144 prefix = "System.Collections.Generic";
9145 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9146 s2 = strstr (s, "`1.");
9152 //printf ("X: %s %s\n", iname, mname);
9154 if (!strcmp (iname, "IList"))
9155 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9157 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9158 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9160 g_free (helper_name);
9163 if (m->is_generic) {
9165 memset (&ctx, 0, sizeof (ctx));
9166 args [0] = &method->klass->element_class->byval_arg;
9167 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9168 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
9169 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9175 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9177 typedef struct HashEntry {
9178 guint32 key, value, index;
9179 struct HashEntry *next;
9183 * emit_extra_methods:
9185 * Emit methods which are not in the METHOD table, like wrappers.
9188 emit_extra_methods (MonoAotCompile *acfg)
9190 int i, table_size, buf_size;
9192 guint32 *info_offsets;
9195 HashEntry *entry, *new_entry;
9196 int nmethods, max_chain_length;
9199 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9201 /* Emit method info */
9203 for (i = 0; i < acfg->extra_methods->len; ++i) {
9204 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9205 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9211 p = buf = (guint8 *)g_malloc (buf_size);
9215 method = cfg->method_to_register;
9217 encode_method_ref (acfg, method, p, &p);
9219 g_assert ((p - buf) < buf_size);
9221 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9226 * Construct a chained hash table for mapping indexes in extra_method_info to
9229 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9230 table = g_ptr_array_sized_new (table_size);
9231 for (i = 0; i < table_size; ++i)
9232 g_ptr_array_add (table, NULL);
9233 chain_lengths = g_new0 (int, table_size);
9234 max_chain_length = 0;
9235 for (i = 0; i < acfg->extra_methods->len; ++i) {
9236 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9237 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9243 key = info_offsets [i];
9244 value = get_method_index (acfg, method);
9246 hash = mono_aot_method_hash (method) % table_size;
9247 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9249 chain_lengths [hash] ++;
9250 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9252 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9253 new_entry->key = key;
9254 new_entry->value = value;
9256 entry = (HashEntry *)g_ptr_array_index (table, hash);
9257 if (entry == NULL) {
9258 new_entry->index = hash;
9259 g_ptr_array_index (table, hash) = new_entry;
9262 entry = entry->next;
9264 entry->next = new_entry;
9265 new_entry->index = table->len;
9266 g_ptr_array_add (table, new_entry);
9269 g_free (chain_lengths);
9271 //printf ("MAX: %d\n", max_chain_length);
9273 buf_size = table->len * 12 + 4;
9274 p = buf = (guint8 *)g_malloc (buf_size);
9275 encode_int (table_size, p, &p);
9277 for (i = 0; i < table->len; ++i) {
9278 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9280 if (entry == NULL) {
9281 encode_int (0, p, &p);
9282 encode_int (0, p, &p);
9283 encode_int (0, p, &p);
9285 //g_assert (entry->key > 0);
9286 encode_int (entry->key, p, &p);
9287 encode_int (entry->value, p, &p);
9289 encode_int (entry->next->index, p, &p);
9291 encode_int (0, p, &p);
9294 g_assert (p - buf <= buf_size);
9296 /* Emit the table */
9297 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9302 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9303 * This is used by mono_aot_find_jit_info ().
9305 buf_size = acfg->extra_methods->len * 8 + 4;
9306 p = buf = (guint8 *)g_malloc (buf_size);
9307 encode_int (acfg->extra_methods->len, p, &p);
9308 for (i = 0; i < acfg->extra_methods->len; ++i) {
9309 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9311 encode_int (get_method_index (acfg, method), p, &p);
9312 encode_int (info_offsets [i], p, &p);
9314 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9317 g_free (info_offsets);
9318 g_ptr_array_free (table, TRUE);
9322 generate_aotid (guint8* aotid)
9324 gpointer rand_handle;
9328 rand_handle = mono_rand_init (NULL, 0);
9330 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
9331 mono_error_assert_ok (&error);
9333 mono_rand_close (rand_handle);
9337 emit_exception_info (MonoAotCompile *acfg)
9341 SeqPointData sp_data;
9342 gboolean seq_points_to_file = FALSE;
9344 offsets = g_new0 (gint32, acfg->nmethods);
9345 for (i = 0; i < acfg->nmethods; ++i) {
9346 if (acfg->cfgs [i]) {
9347 MonoCompile *cfg = acfg->cfgs [i];
9349 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9350 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9351 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9352 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9353 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9355 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9356 offsets [i] = cfg->ex_info_offset;
9358 if (method_seq_points_to_file) {
9359 if (!seq_points_to_file) {
9360 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9361 seq_points_to_file = TRUE;
9363 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9370 if (seq_points_to_file) {
9371 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9372 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9373 char *image_basename = g_path_get_basename (acfg->image->name);
9374 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9375 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9377 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9378 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9382 mono_seq_point_data_write (&sp_data, aot_file_path);
9383 mono_seq_point_data_free (&sp_data);
9387 g_free (image_basename);
9389 g_free (aot_file_path);
9392 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9397 emit_unwind_info (MonoAotCompile *acfg)
9402 if (acfg->aot_opts.llvm_only) {
9403 g_assert (acfg->unwind_ops->len == 0);
9408 * The unwind info contains a lot of duplicates so we emit each unique
9409 * entry once, and only store the offset from the start of the table in the
9413 sprintf (symbol, "unwind_info");
9414 emit_section_change (acfg, RODATA_SECT, 1);
9415 emit_alignment (acfg, 8);
9416 emit_info_symbol (acfg, symbol);
9418 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9419 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9420 guint8 *unwind_info;
9421 guint32 unwind_info_len;
9425 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9428 encode_value (unwind_info_len, p, &p);
9429 emit_bytes (acfg, buf, p - buf);
9430 emit_bytes (acfg, unwind_info, unwind_info_len);
9432 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9437 emit_class_info (MonoAotCompile *acfg)
9442 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9443 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9444 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9446 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);
9450 typedef struct ClassNameTableEntry {
9451 guint32 token, index;
9452 struct ClassNameTableEntry *next;
9453 } ClassNameTableEntry;
9456 emit_class_name_table (MonoAotCompile *acfg)
9458 int i, table_size, buf_size;
9459 guint32 token, hash;
9464 ClassNameTableEntry *entry, *new_entry;
9467 * Construct a chained hash table for mapping class names to typedef tokens.
9469 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9470 table = g_ptr_array_sized_new (table_size);
9471 for (i = 0; i < table_size; ++i)
9472 g_ptr_array_add (table, NULL);
9473 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9475 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9476 klass = mono_class_get_checked (acfg->image, token, &error);
9478 mono_error_cleanup (&error);
9481 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9482 hash = mono_metadata_str_hash (full_name) % table_size;
9485 /* FIXME: Allocate from the mempool */
9486 new_entry = g_new0 (ClassNameTableEntry, 1);
9487 new_entry->token = token;
9489 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9490 if (entry == NULL) {
9491 new_entry->index = hash;
9492 g_ptr_array_index (table, hash) = new_entry;
9495 entry = entry->next;
9497 entry->next = new_entry;
9498 new_entry->index = table->len;
9499 g_ptr_array_add (table, new_entry);
9503 /* Emit the table */
9504 buf_size = table->len * 4 + 4;
9505 p = buf = (guint8 *)g_malloc0 (buf_size);
9507 /* FIXME: Optimize memory usage */
9508 g_assert (table_size < 65000);
9509 encode_int16 (table_size, p, &p);
9510 g_assert (table->len < 65000);
9511 for (i = 0; i < table->len; ++i) {
9512 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9514 if (entry == NULL) {
9515 encode_int16 (0, p, &p);
9516 encode_int16 (0, p, &p);
9518 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9520 encode_int16 (entry->next->index, p, &p);
9522 encode_int16 (0, p, &p);
9526 g_assert (p - buf <= buf_size);
9527 g_ptr_array_free (table, TRUE);
9529 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9535 emit_image_table (MonoAotCompile *acfg)
9541 * The image table is small but referenced in a lot of places.
9542 * So we emit it at once, and reference its elements by an index.
9544 buf_size = acfg->image_table->len * 28 + 4;
9545 for (i = 0; i < acfg->image_table->len; i++) {
9546 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9547 MonoAssemblyName *aname = &image->assembly->aname;
9549 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9552 buf = p = (guint8 *)g_malloc0 (buf_size);
9553 encode_int (acfg->image_table->len, p, &p);
9554 for (i = 0; i < acfg->image_table->len; i++) {
9555 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9556 MonoAssemblyName *aname = &image->assembly->aname;
9558 /* FIXME: Support multi-module assemblies */
9559 g_assert (image->assembly->image == image);
9561 encode_string (image->assembly_name, p, &p);
9562 encode_string (image->guid, p, &p);
9563 encode_string (aname->culture ? aname->culture : "", p, &p);
9564 encode_string ((const char*)aname->public_key_token, p, &p);
9566 while (GPOINTER_TO_UINT (p) % 8 != 0)
9569 encode_int (aname->flags, p, &p);
9570 encode_int (aname->major, p, &p);
9571 encode_int (aname->minor, p, &p);
9572 encode_int (aname->build, p, &p);
9573 encode_int (aname->revision, p, &p);
9575 g_assert (p - buf <= buf_size);
9577 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9583 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9585 int i, first_plt_got_patch = 0, buf_size;
9587 guint32 *got_info_offsets;
9588 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9590 /* Add the patches needed by the PLT to the GOT */
9592 acfg->plt_got_offset_base = acfg->got_offset;
9593 first_plt_got_patch = info->got_patches->len;
9594 for (i = 1; i < acfg->plt_offset; ++i) {
9595 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9597 g_ptr_array_add (info->got_patches, plt_entry->ji);
9599 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9602 acfg->got_offset += acfg->plt_offset;
9607 * - optimize offsets table.
9608 * - reduce number of exported symbols.
9609 * - emit info for a klass only once.
9610 * - determine when a method uses a GOT slot which is guaranteed to be already
9612 * - clean up and document the code.
9613 * - use String.Empty in class libs.
9616 /* Encode info required to decode shared GOT entries */
9617 buf_size = info->got_patches->len * 128;
9618 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9619 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9621 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9623 if (acfg->plt_offset)
9624 acfg->plt_got_info_offsets [0] = 0;
9626 for (i = 0; i < info->got_patches->len; ++i) {
9627 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9632 encode_value (ji->type, p, &p);
9634 encode_patch (acfg, ji, p, &p);
9635 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9636 g_assert (p - buf <= buf_size);
9637 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9639 if (!llvm && i >= first_plt_got_patch)
9640 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9641 acfg->stats.got_info_size += p - buf;
9644 /* Emit got_info_offsets table */
9646 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9647 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);
9651 emit_got (MonoAotCompile *acfg)
9653 char symbol [MAX_SYMBOL_SIZE];
9655 if (acfg->aot_opts.llvm_only)
9658 /* Don't make GOT global so accesses to it don't need relocations */
9659 sprintf (symbol, "%s", acfg->got_symbol);
9662 emit_unset_mode (acfg);
9663 fprintf (acfg->fp, ".section __DATA, __bss\n");
9664 emit_alignment (acfg, 8);
9666 emit_info_symbol (acfg, "jit_got");
9667 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9669 emit_section_change (acfg, ".bss", 0);
9670 emit_alignment (acfg, 8);
9671 if (acfg->aot_opts.write_symbols)
9672 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9673 emit_label (acfg, symbol);
9675 emit_info_symbol (acfg, "jit_got");
9676 if (acfg->got_offset > 0)
9677 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9680 sprintf (symbol, "got_end");
9681 emit_label (acfg, symbol);
9684 typedef struct GlobalsTableEntry {
9685 guint32 value, index;
9686 struct GlobalsTableEntry *next;
9687 } GlobalsTableEntry;
9689 #ifdef TARGET_WIN32_MSVC
9690 #define DLL_ENTRY_POINT "DllMain"
9693 emit_library_info (MonoAotCompile *acfg)
9695 // Only include for shared libraries linked directly from generated object.
9696 if (link_shared_library (acfg)) {
9698 char symbol [MAX_SYMBOL_SIZE];
9700 // Ask linker to export all global symbols.
9701 emit_section_change (acfg, ".drectve", 0);
9702 for (guint i = 0; i < acfg->globals->len; ++i) {
9703 name = (char *)g_ptr_array_index (acfg->globals, i);
9704 g_assert (name != NULL);
9705 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9706 emit_string (acfg, symbol);
9709 // Emit DLLMain function, needed by MSVC linker for DLL's.
9710 // NOTE, DllMain should not go into exports above.
9711 emit_section_change (acfg, ".text", 0);
9712 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9713 emit_label (acfg, DLL_ENTRY_POINT);
9715 // Simple implementation of DLLMain, just returning TRUE.
9716 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9717 fprintf (acfg->fp, "movl $1, %%eax\n");
9718 fprintf (acfg->fp, "ret\n");
9720 // Inform linker about our dll entry function.
9721 emit_section_change (acfg, ".drectve", 0);
9722 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9730 emit_library_info (MonoAotCompile *acfg)
9737 emit_globals (MonoAotCompile *acfg)
9743 GlobalsTableEntry *entry, *new_entry;
9745 if (!acfg->aot_opts.static_link)
9748 if (acfg->aot_opts.llvm_only) {
9749 g_assert (acfg->globals->len == 0);
9754 * When static linking, we emit a table containing our globals.
9758 * Construct a chained hash table for mapping global names to their index in
9759 * the globals table.
9761 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9762 table = g_ptr_array_sized_new (table_size);
9763 for (i = 0; i < table_size; ++i)
9764 g_ptr_array_add (table, NULL);
9765 for (i = 0; i < acfg->globals->len; ++i) {
9766 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9768 hash = mono_metadata_str_hash (name) % table_size;
9770 /* FIXME: Allocate from the mempool */
9771 new_entry = g_new0 (GlobalsTableEntry, 1);
9772 new_entry->value = i;
9774 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9775 if (entry == NULL) {
9776 new_entry->index = hash;
9777 g_ptr_array_index (table, hash) = new_entry;
9780 entry = entry->next;
9782 entry->next = new_entry;
9783 new_entry->index = table->len;
9784 g_ptr_array_add (table, new_entry);
9788 /* Emit the table */
9789 sprintf (symbol, ".Lglobals_hash");
9790 emit_section_change (acfg, RODATA_SECT, 0);
9791 emit_alignment (acfg, 8);
9792 emit_label (acfg, symbol);
9794 /* FIXME: Optimize memory usage */
9795 g_assert (table_size < 65000);
9796 emit_int16 (acfg, table_size);
9797 for (i = 0; i < table->len; ++i) {
9798 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9800 if (entry == NULL) {
9801 emit_int16 (acfg, 0);
9802 emit_int16 (acfg, 0);
9804 emit_int16 (acfg, entry->value + 1);
9806 emit_int16 (acfg, entry->next->index);
9808 emit_int16 (acfg, 0);
9812 /* Emit the names */
9813 for (i = 0; i < acfg->globals->len; ++i) {
9814 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9816 sprintf (symbol, "name_%d", i);
9817 emit_section_change (acfg, RODATA_SECT, 1);
9819 emit_alignment (acfg, 4);
9821 emit_label (acfg, symbol);
9822 emit_string (acfg, name);
9825 /* Emit the globals table */
9826 sprintf (symbol, "globals");
9827 emit_section_change (acfg, ".data", 0);
9828 /* This is not a global, since it is accessed by the init function */
9829 emit_alignment (acfg, 8);
9830 emit_info_symbol (acfg, symbol);
9832 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9833 emit_pointer (acfg, symbol);
9835 for (i = 0; i < acfg->globals->len; ++i) {
9836 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9838 sprintf (symbol, "name_%d", i);
9839 emit_pointer (acfg, symbol);
9841 g_assert (strlen (name) < sizeof (symbol));
9842 sprintf (symbol, "%s", name);
9843 emit_pointer (acfg, symbol);
9845 /* Null terminate the table */
9846 emit_int32 (acfg, 0);
9847 emit_int32 (acfg, 0);
9851 emit_mem_end (MonoAotCompile *acfg)
9855 if (acfg->aot_opts.llvm_only)
9858 sprintf (symbol, "mem_end");
9859 emit_section_change (acfg, ".text", 1);
9860 emit_alignment_code (acfg, 8);
9861 emit_label (acfg, symbol);
9865 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9869 info->version = MONO_AOT_FILE_VERSION;
9870 info->plt_got_offset_base = acfg->plt_got_offset_base;
9871 info->got_size = acfg->got_offset * sizeof (gpointer);
9872 info->plt_size = acfg->plt_offset;
9873 info->nmethods = acfg->nmethods;
9874 info->flags = acfg->flags;
9875 info->opts = acfg->opts;
9876 info->simd_opts = acfg->simd_opts;
9877 info->gc_name_index = acfg->gc_name_offset;
9878 info->datafile_size = acfg->datafile_offset;
9879 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9880 info->table_offsets [i] = acfg->table_offsets [i];
9881 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9882 info->num_trampolines [i] = acfg->num_trampolines [i];
9883 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9884 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9885 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9886 info->trampoline_size [i] = acfg->trampoline_size [i];
9887 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9889 info->double_align = MONO_ABI_ALIGNOF (double);
9890 info->long_align = MONO_ABI_ALIGNOF (gint64);
9891 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9892 info->tramp_page_size = acfg->tramp_page_size;
9893 info->nshared_got_entries = acfg->nshared_got_entries;
9894 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9895 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9897 memcpy(&info->aotid, acfg->image->aotid, 16);
9901 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9903 char symbol [MAX_SYMBOL_SIZE];
9905 const char **symbols;
9907 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9909 symbols [sindex ++] = acfg->got_symbol;
9911 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9912 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9914 symbols [sindex ++] = NULL;
9915 symbols [sindex ++] = NULL;
9917 /* llvm_get_method */
9918 symbols [sindex ++] = NULL;
9919 /* llvm_get_unbox_tramp */
9920 symbols [sindex ++] = NULL;
9921 if (!acfg->aot_opts.llvm_only) {
9922 symbols [sindex ++] = "jit_code_start";
9923 symbols [sindex ++] = "jit_code_end";
9924 symbols [sindex ++] = "method_addresses";
9926 symbols [sindex ++] = NULL;
9927 symbols [sindex ++] = NULL;
9928 symbols [sindex ++] = NULL;
9930 if (acfg->data_outfile) {
9931 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9932 symbols [sindex ++] = NULL;
9934 symbols [sindex ++] = "blob";
9935 symbols [sindex ++] = "class_name_table";
9936 symbols [sindex ++] = "class_info_offsets";
9937 symbols [sindex ++] = "method_info_offsets";
9938 symbols [sindex ++] = "ex_info_offsets";
9939 symbols [sindex ++] = "extra_method_info_offsets";
9940 symbols [sindex ++] = "extra_method_table";
9941 symbols [sindex ++] = "got_info_offsets";
9943 symbols [sindex ++] = "llvm_got_info_offsets";
9945 symbols [sindex ++] = NULL;
9946 symbols [sindex ++] = "image_table";
9948 symbols [sindex ++] = "mem_end";
9949 symbols [sindex ++] = "assembly_guid";
9950 symbols [sindex ++] = "runtime_version";
9951 if (acfg->num_trampoline_got_entries) {
9952 symbols [sindex ++] = "specific_trampolines";
9953 symbols [sindex ++] = "static_rgctx_trampolines";
9954 symbols [sindex ++] = "imt_trampolines";
9955 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9957 symbols [sindex ++] = NULL;
9958 symbols [sindex ++] = NULL;
9959 symbols [sindex ++] = NULL;
9960 symbols [sindex ++] = NULL;
9962 if (acfg->aot_opts.static_link) {
9963 symbols [sindex ++] = "globals";
9965 symbols [sindex ++] = NULL;
9967 symbols [sindex ++] = "assembly_name";
9968 symbols [sindex ++] = "plt";
9969 symbols [sindex ++] = "plt_end";
9970 symbols [sindex ++] = "unwind_info";
9971 if (!acfg->aot_opts.llvm_only) {
9972 symbols [sindex ++] = "unbox_trampolines";
9973 symbols [sindex ++] = "unbox_trampolines_end";
9974 symbols [sindex ++] = "unbox_trampoline_addresses";
9976 symbols [sindex ++] = NULL;
9977 symbols [sindex ++] = NULL;
9978 symbols [sindex ++] = NULL;
9981 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9983 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9984 emit_section_change (acfg, ".data", 0);
9985 emit_alignment (acfg, 8);
9986 emit_label (acfg, symbol);
9987 if (!acfg->aot_opts.static_link)
9988 emit_global (acfg, symbol, FALSE);
9990 /* The data emitted here must match MonoAotFileInfo. */
9992 emit_int32 (acfg, info->version);
9993 emit_int32 (acfg, info->dummy);
9996 * We emit pointers to our data structures instead of emitting global symbols which
9997 * point to them, to reduce the number of globals, and because using globals leads to
9998 * various problems (i.e. arm/thumb).
10000 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10001 emit_pointer (acfg, symbols [i]);
10003 emit_int32 (acfg, info->plt_got_offset_base);
10004 emit_int32 (acfg, info->got_size);
10005 emit_int32 (acfg, info->plt_size);
10006 emit_int32 (acfg, info->nmethods);
10007 emit_int32 (acfg, info->flags);
10008 emit_int32 (acfg, info->opts);
10009 emit_int32 (acfg, info->simd_opts);
10010 emit_int32 (acfg, info->gc_name_index);
10011 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10012 emit_int32 (acfg, info->double_align);
10013 emit_int32 (acfg, info->long_align);
10014 emit_int32 (acfg, info->generic_tramp_num);
10015 emit_int32 (acfg, info->tramp_page_size);
10016 emit_int32 (acfg, info->nshared_got_entries);
10017 emit_int32 (acfg, info->datafile_size);
10019 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10020 emit_int32 (acfg, info->table_offsets [i]);
10021 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10022 emit_int32 (acfg, info->num_trampolines [i]);
10023 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10024 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10025 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10026 emit_int32 (acfg, info->trampoline_size [i]);
10027 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10028 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10030 emit_bytes (acfg, info->aotid, 16);
10032 if (acfg->aot_opts.static_link) {
10033 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10034 emit_alignment (acfg, sizeof (gpointer));
10035 emit_label (acfg, acfg->static_linking_symbol);
10036 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10041 * Emit a structure containing all the information not stored elsewhere.
10044 emit_file_info (MonoAotCompile *acfg)
10047 MonoAotFileInfo *info;
10049 if (acfg->aot_opts.bind_to_runtime_version) {
10050 build_info = mono_get_runtime_build_info ();
10051 emit_string_symbol (acfg, "runtime_version", build_info);
10052 g_free (build_info);
10054 emit_string_symbol (acfg, "runtime_version", "");
10057 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10059 /* Emit a string holding the assembly name */
10060 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10062 info = g_new0 (MonoAotFileInfo, 1);
10063 init_aot_file_info (acfg, info);
10065 if (acfg->aot_opts.static_link) {
10066 char symbol [MAX_SYMBOL_SIZE];
10070 * Emit a global symbol which can be passed by an embedding app to
10071 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10074 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10076 /* Get rid of characters which cannot occur in symbols */
10078 for (p = symbol; *p; ++p) {
10079 if (!(isalnum (*p) || *p == '_'))
10082 acfg->static_linking_symbol = g_strdup (symbol);
10086 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10088 emit_aot_file_info (acfg, info);
10092 emit_blob (MonoAotCompile *acfg)
10094 acfg->blob_closed = TRUE;
10096 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10100 emit_objc_selectors (MonoAotCompile *acfg)
10105 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10110 * cat > foo.m << EOF
10113 * return @selector(print:);
10118 mono_img_writer_emit_unset_mode (acfg->w);
10119 g_assert (acfg->fp);
10120 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10121 fprintf (acfg->fp, ".align 3\n");
10122 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10123 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10124 emit_label (acfg, symbol);
10125 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10126 emit_pointer (acfg, symbol);
10129 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10130 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10131 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10132 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10135 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10136 fprintf (acfg->fp, ".align 3\n");
10137 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10138 fprintf (acfg->fp, ".long 0\n");
10139 fprintf (acfg->fp, ".long 16\n");
10143 emit_dwarf_info (MonoAotCompile *acfg)
10145 #ifdef EMIT_DWARF_INFO
10147 char symbol2 [128];
10149 /* DIEs for methods */
10150 for (i = 0; i < acfg->nmethods; ++i) {
10151 MonoCompile *cfg = acfg->cfgs [i];
10156 // FIXME: LLVM doesn't define .Lme_...
10157 if (cfg->compile_llvm)
10160 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10162 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 ()));
10168 collect_methods (MonoAotCompile *acfg)
10171 MonoImage *image = acfg->image;
10173 /* Collect methods */
10174 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10176 MonoMethod *method;
10177 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10179 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10182 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
10183 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10184 mono_error_cleanup (&error);
10188 /* Load all methods eagerly to skip the slower lazy loading code */
10189 mono_class_setup_methods (method->klass);
10191 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10192 /* Compile the wrapper instead */
10193 /* We do this here instead of add_wrappers () because it is easy to do it here */
10194 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10198 /* FIXME: Some mscorlib methods don't have debug info */
10200 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10201 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10202 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10203 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10204 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10205 if (!mono_debug_lookup_method (method)) {
10206 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10213 if (method->is_generic || mono_class_is_gtd (method->klass))
10214 /* Compile the ref shared version instead */
10215 method = mini_get_shared_method (method);
10217 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10218 add_method_with_index (acfg, method, i, FALSE);
10219 acfg->method_index ++;
10222 /* gsharedvt methods */
10223 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10225 MonoMethod *method;
10226 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10228 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10231 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10232 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
10234 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10235 MonoMethod *gshared;
10237 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10238 add_extra_method (acfg, gshared);
10242 if (mono_aot_mode_is_full (&acfg->aot_opts))
10243 add_generic_instances (acfg);
10245 if (mono_aot_mode_is_full (&acfg->aot_opts))
10246 add_wrappers (acfg);
10251 compile_methods (MonoAotCompile *acfg)
10253 int i, methods_len;
10255 if (acfg->aot_opts.nthreads > 0) {
10258 GPtrArray *threads;
10259 MonoThreadHandle *thread_handle;
10260 gpointer *user_data;
10261 MonoMethod **methods;
10263 methods_len = acfg->methods->len;
10265 len = acfg->methods->len / acfg->aot_opts.nthreads;
10266 g_assert (len > 0);
10268 * Partition the list of methods into fragments, and hand it to threads to
10271 threads = g_ptr_array_new ();
10272 /* Make a copy since acfg->methods is modified by compile_method () */
10273 methods = g_new0 (MonoMethod*, methods_len);
10274 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
10275 for (i = 0; i < methods_len; ++i)
10276 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
10278 while (i < methods_len) {
10280 MonoInternalThread *thread;
10282 frag = g_ptr_array_new ();
10283 for (j = 0; j < len; ++j) {
10284 if (i < methods_len) {
10285 g_ptr_array_add (frag, methods [i]);
10290 user_data = g_new0 (gpointer, 3);
10291 user_data [0] = acfg;
10292 user_data [1] = frag;
10294 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
10295 mono_error_assert_ok (&error);
10297 thread_handle = mono_threads_open_thread_handle (thread->handle);
10298 g_ptr_array_add (threads, thread_handle);
10302 for (i = 0; i < threads->len; ++i) {
10303 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
10304 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
10310 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
10311 for (i = methods_len; i < acfg->methods->len; ++i) {
10312 /* This can add new methods to acfg->methods */
10313 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
10318 compile_asm (MonoAotCompile *acfg)
10320 char *command, *objfile;
10321 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
10322 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
10323 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
10325 #ifdef TARGET_WIN32_MSVC
10326 #define AS_OPTIONS "-c -x assembler"
10327 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
10328 #define AS_OPTIONS "--64"
10329 #elif defined(TARGET_POWERPC64)
10330 #define AS_OPTIONS "-a64 -mppc64"
10331 #elif defined(sparc) && SIZEOF_VOID_P == 8
10332 #define AS_OPTIONS "-xarch=v9"
10333 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10334 #define AS_OPTIONS "-arch i386"
10336 #define AS_OPTIONS ""
10339 #ifdef __native_client_codegen__
10340 #if defined(TARGET_AMD64)
10341 #define AS_NAME "nacl64-as"
10343 #define AS_NAME "nacl-as"
10345 #elif defined(TARGET_OSX)
10346 #define AS_NAME "clang"
10347 #elif defined(TARGET_WIN32_MSVC)
10348 #define AS_NAME "clang.exe"
10350 #define AS_NAME "as"
10353 #ifdef TARGET_WIN32_MSVC
10354 #define AS_OBJECT_FILE_SUFFIX "obj"
10356 #define AS_OBJECT_FILE_SUFFIX "o"
10360 #define LD_NAME "ld"
10361 #define LD_OPTIONS "-shared -G"
10362 #elif defined(__ppc__) && defined(TARGET_MACH)
10363 #define LD_NAME "gcc"
10364 #define LD_OPTIONS "-dynamiclib"
10365 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10366 #define LD_NAME "clang"
10367 #define LD_OPTIONS "--shared"
10368 #elif defined(TARGET_WIN32_MSVC)
10369 #define LD_NAME "link.exe"
10370 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
10371 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10372 #define LD_NAME "gcc"
10373 #define LD_OPTIONS "-shared"
10374 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10375 #define LD_NAME "clang"
10376 #define LD_OPTIONS "-m32 -dynamiclib"
10377 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10378 #define LD_NAME "gcc"
10379 #define LD_OPTIONS "--shared"
10380 #elif defined(TARGET_POWERPC64)
10381 #define LD_OPTIONS "-m elf64ppc"
10385 #define LD_OPTIONS ""
10388 if (acfg->aot_opts.asm_only) {
10389 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10390 if (acfg->aot_opts.static_link)
10391 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10393 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10397 if (acfg->aot_opts.static_link) {
10398 if (acfg->aot_opts.outfile)
10399 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10401 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
10403 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
10407 g_string_append (acfg->as_args, "-c -x assembler");
10410 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10411 acfg->as_args ? acfg->as_args->str : "",
10412 wrap_path (objfile), wrap_path (acfg->tmpfname));
10413 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10414 if (execute_system (command) != 0) {
10420 if (acfg->llvm && !acfg->llvm_owriter) {
10421 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10422 acfg->as_args ? acfg->as_args->str : "",
10423 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10424 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10425 if (execute_system (command) != 0) {
10434 if (acfg->aot_opts.static_link) {
10435 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10436 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10441 if (acfg->aot_opts.outfile)
10442 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10444 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10446 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10449 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10451 llvm_ofile = g_strdup ("");
10454 /* replace the ; flags separators with spaces */
10455 g_strdelimit (ld_flags, ";", ' ');
10457 if (acfg->aot_opts.llvm_only)
10458 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10460 #ifdef TARGET_WIN32_MSVC
10461 g_assert (tmp_outfile_name != NULL);
10462 g_assert (objfile != NULL);
10463 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10464 ld_flags, tmp_outfile_name, objfile);
10465 #elif defined(LD_NAME)
10466 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10467 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10468 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10471 if (acfg->aot_opts.tool_prefix) {
10472 /* Cross compiling */
10473 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10474 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10475 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10477 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10478 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10479 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10481 if (acfg->aot_opts.llvm_only) {
10482 command = g_strdup_printf ("clang++ %s", args);
10484 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10489 aot_printf (acfg, "Executing the native linker: %s\n", command);
10490 if (execute_system (command) != 0) {
10491 g_free (tmp_outfile_name);
10492 g_free (outfile_name);
10501 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10502 printf ("Stripping the binary: %s\n", com);
10503 execute_system (com);
10506 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10508 * gas generates 'mapping symbols' each time code and data is mixed, which
10509 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10511 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10512 aot_printf (acfg, "Stripping the binary: %s\n", command);
10513 if (execute_system (command) != 0) {
10514 g_free (tmp_outfile_name);
10515 g_free (outfile_name);
10522 if (0 != rename (tmp_outfile_name, outfile_name)) {
10523 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10524 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10525 unlink (outfile_name);
10526 rename (tmp_outfile_name, outfile_name);
10530 #if defined(TARGET_MACH)
10531 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10532 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10533 if (execute_system (command) != 0) {
10538 if (!acfg->aot_opts.save_temps)
10541 g_free (tmp_outfile_name);
10542 g_free (outfile_name);
10545 if (acfg->aot_opts.save_temps)
10546 aot_printf (acfg, "Retained input file.\n");
10548 unlink (acfg->tmpfname);
10554 profread_byte (FILE *infile)
10559 res = fread (&i, 1, 1, infile);
10560 g_assert (res == 1);
10565 profread_int (FILE *infile)
10569 res = fread (&i, 4, 1, infile);
10570 g_assert (res == 1);
10575 profread_string (FILE *infile)
10581 len = profread_int (infile);
10582 if (len + 1 > 1024)
10583 pbuf = g_malloc (len + 1);
10586 res = fread (pbuf, 1, len, infile);
10587 g_assert (res == len);
10590 return g_strdup (buf);
10596 load_profile_file (MonoAotCompile *acfg, char *filename)
10600 int res, len, version;
10603 infile = fopen (filename, "r");
10605 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10609 printf ("Using profile data file '%s'\n", filename);
10611 sprintf (magic, AOT_PROFILER_MAGIC);
10612 len = strlen (magic);
10613 res = fread (buf, 1, len, infile);
10614 magic [len] = '\0';
10616 if ((res != len) || strcmp (buf, magic) != 0) {
10617 printf ("Profile file has wrong header: '%s'.\n", buf);
10621 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10622 version = profread_int (infile);
10623 if (version != expected_version) {
10624 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10629 ProfileData *data = g_new0 (ProfileData, 1);
10630 data->images = g_hash_table_new (NULL, NULL);
10631 data->classes = g_hash_table_new (NULL, NULL);
10632 data->ginsts = g_hash_table_new (NULL, NULL);
10633 data->methods = g_hash_table_new (NULL, NULL);
10636 int type = profread_byte (infile);
10637 int id = profread_int (infile);
10639 if (type == AOTPROF_RECORD_NONE)
10643 case AOTPROF_RECORD_IMAGE: {
10644 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10645 idata->name = profread_string (infile);
10646 char *mvid = profread_string (infile);
10648 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10651 case AOTPROF_RECORD_GINST: {
10653 int len = profread_int (infile);
10655 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10657 gdata->argv = g_new0 (ClassProfileData*, len);
10659 for (i = 0; i < len; ++i) {
10660 int class_id = profread_int (infile);
10662 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10663 g_assert (gdata->argv [i]);
10665 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10668 case AOTPROF_RECORD_TYPE: {
10669 int type = profread_byte (infile);
10672 case MONO_TYPE_CLASS: {
10673 int image_id = profread_int (infile);
10674 int ginst_id = profread_int (infile);
10675 char *class_name = profread_string (infile);
10677 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10680 char *p = strrchr (class_name, '.');
10684 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10685 cdata->image = image;
10686 cdata->ns = g_strdup (class_name);
10687 cdata->name = g_strdup (p + 1);
10689 if (ginst_id != -1) {
10690 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10691 g_assert (cdata->inst);
10693 g_free (class_name);
10695 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10699 case MONO_TYPE_SZARRAY: {
10700 int elem_id = profread_int (infile);
10706 g_assert_not_reached ();
10711 case AOTPROF_RECORD_METHOD: {
10712 int class_id = profread_int (infile);
10713 int ginst_id = profread_int (infile);
10714 int param_count = profread_int (infile);
10715 char *method_name = profread_string (infile);
10716 char *sig = profread_string (infile);
10718 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10721 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10723 mdata->klass = klass;
10724 mdata->name = method_name;
10725 mdata->signature = sig;
10726 mdata->param_count = param_count;
10728 if (ginst_id != -1) {
10729 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10730 g_assert (mdata->inst);
10732 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10736 printf ("%d\n", type);
10737 g_assert_not_reached ();
10743 acfg->profile_data = g_list_append (acfg->profile_data, data);
10747 resolve_class (ClassProfileData *cdata);
10750 resolve_ginst (GInstProfileData *inst_data)
10754 if (inst_data->inst)
10757 for (i = 0; i < inst_data->argc; ++i) {
10758 resolve_class (inst_data->argv [i]);
10759 if (!inst_data->argv [i]->klass)
10762 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10763 for (i = 0; i < inst_data->argc; ++i)
10764 args [i] = &inst_data->argv [i]->klass->byval_arg;
10766 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10770 resolve_class (ClassProfileData *cdata)
10775 if (!cdata->image->image)
10778 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10780 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10784 resolve_ginst (cdata->inst);
10785 if (!cdata->inst->inst)
10787 MonoGenericContext ctx;
10789 memset (&ctx, 0, sizeof (ctx));
10790 ctx.class_inst = cdata->inst->inst;
10791 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10793 cdata->klass = klass;
10798 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10801 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10803 GHashTableIter iter;
10804 gpointer key, value;
10811 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10812 g_hash_table_iter_init (&iter, data->images);
10813 while (g_hash_table_iter_next (&iter, &key, &value)) {
10814 ImageProfileData *idata = (ImageProfileData*)value;
10816 for (i = 0; i < assemblies->len; ++i) {
10817 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10819 if (!strcmp (ass->aname.name, idata->name)) {
10820 idata->image = ass->image;
10825 g_ptr_array_free (assemblies, TRUE);
10828 g_hash_table_iter_init (&iter, data->classes);
10829 while (g_hash_table_iter_next (&iter, &key, &value)) {
10830 ClassProfileData *cdata = (ClassProfileData*)value;
10832 if (!cdata->image->image) {
10833 if (acfg->aot_opts.verbose)
10834 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10838 resolve_class (cdata);
10841 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10846 g_hash_table_iter_init (&iter, data->methods);
10847 while (g_hash_table_iter_next (&iter, &key, &value)) {
10848 MethodProfileData *mdata = (MethodProfileData*)value;
10853 resolve_class (mdata->klass);
10854 klass = mdata->klass->klass;
10856 if (acfg->aot_opts.verbose)
10857 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10861 while ((m = mono_class_get_methods (klass, &miter))) {
10864 if (strcmp (m->name, mdata->name))
10866 MonoMethodSignature *sig = mono_method_signature (m);
10869 if (sig->param_count != mdata->param_count)
10872 resolve_ginst (mdata->inst);
10873 if (!mdata->inst->inst)
10875 MonoGenericContext ctx;
10877 memset (&ctx, 0, sizeof (ctx));
10878 ctx.method_inst = mdata->inst->inst;
10880 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10883 sig = mono_method_signature_checked (m, &error);
10884 if (!is_ok (&error)) {
10885 mono_error_cleanup (&error);
10889 char *sig_str = mono_signature_full_name (sig);
10890 gboolean match = !strcmp (sig_str, mdata->signature);
10895 //printf ("%s\n", mono_method_full_name (m, 1));
10899 if (!mdata->method) {
10900 if (acfg->aot_opts.verbose)
10901 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10907 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10911 for (i = 0; i < inst->type_argc; ++i) {
10912 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10913 if (k->image == image)
10915 if (mono_class_is_ginst (k)) {
10916 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10917 if (inst_references_image (kinst, image))
10925 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10929 for (i = 0; i < inst->type_argc; ++i) {
10930 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10931 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10938 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10940 GHashTableIter iter;
10941 gpointer key, value;
10947 if (acfg->aot_opts.profile_only) {
10948 /* Add methods referenced by the profile */
10949 g_hash_table_iter_init (&iter, data->methods);
10950 while (g_hash_table_iter_next (&iter, &key, &value)) {
10951 MethodProfileData *mdata = (MethodProfileData*)value;
10952 MonoMethod *m = mdata->method;
10956 if (m->is_inflated)
10958 add_extra_method (acfg, m);
10959 g_hash_table_insert (acfg->profile_methods, m, m);
10965 * Add method instances 'related' to this assembly to the AOT image.
10967 g_hash_table_iter_init (&iter, data->methods);
10968 while (g_hash_table_iter_next (&iter, &key, &value)) {
10969 MethodProfileData *mdata = (MethodProfileData*)value;
10970 MonoMethod *m = mdata->method;
10971 MonoGenericContext *ctx;
10975 if (!m->is_inflated)
10978 ctx = mono_method_get_context (m);
10979 /* For simplicity, add instances which reference the assembly we are compiling */
10980 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10981 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10982 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10983 //printf ("%s\n", mono_method_full_name (m, TRUE));
10984 add_extra_method (acfg, m);
10986 } else if (m->klass->image == acfg->image &&
10987 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
10988 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
10989 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10990 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
10991 //printf ("%s\n", mono_method_full_name (m, TRUE));
10992 add_extra_method (acfg, m);
10996 * FIXME: We might skip some instances, for example:
10997 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
10998 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11002 printf ("Added %d methods from profile.\n", count);
11006 init_got_info (GotInfo *info)
11010 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11011 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11012 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11013 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11014 info->got_patches = g_ptr_array_new ();
11017 static MonoAotCompile*
11018 acfg_create (MonoAssembly *ass, guint32 opts)
11020 MonoImage *image = ass->image;
11021 MonoAotCompile *acfg;
11023 acfg = g_new0 (MonoAotCompile, 1);
11024 acfg->methods = g_ptr_array_new ();
11025 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11026 acfg->method_depth = g_hash_table_new (NULL, NULL);
11027 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11028 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11029 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11030 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11031 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11032 acfg->image_hash = g_hash_table_new (NULL, NULL);
11033 acfg->image_table = g_ptr_array_new ();
11034 acfg->globals = g_ptr_array_new ();
11035 acfg->image = image;
11037 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11038 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11039 acfg->mempool = mono_mempool_new ();
11040 acfg->extra_methods = g_ptr_array_new ();
11041 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11042 acfg->unwind_ops = g_ptr_array_new ();
11043 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11044 acfg->method_order = g_ptr_array_new ();
11045 acfg->export_names = g_hash_table_new (NULL, NULL);
11046 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11047 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11048 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11049 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11050 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11051 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11052 mono_os_mutex_init_recursive (&acfg->mutex);
11054 init_got_info (&acfg->got_info);
11055 init_got_info (&acfg->llvm_got_info);
11061 got_info_free (GotInfo *info)
11065 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11066 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11067 g_free (info->patch_to_got_offset_by_type);
11068 g_hash_table_destroy (info->patch_to_got_offset);
11069 g_ptr_array_free (info->got_patches, TRUE);
11073 acfg_free (MonoAotCompile *acfg)
11077 mono_img_writer_destroy (acfg->w);
11078 for (i = 0; i < acfg->nmethods; ++i)
11079 if (acfg->cfgs [i])
11080 mono_destroy_compile (acfg->cfgs [i]);
11082 g_free (acfg->cfgs);
11084 g_free (acfg->static_linking_symbol);
11085 g_free (acfg->got_symbol);
11086 g_free (acfg->plt_symbol);
11087 g_ptr_array_free (acfg->methods, TRUE);
11088 g_ptr_array_free (acfg->image_table, TRUE);
11089 g_ptr_array_free (acfg->globals, TRUE);
11090 g_ptr_array_free (acfg->unwind_ops, TRUE);
11091 g_hash_table_destroy (acfg->method_indexes);
11092 g_hash_table_destroy (acfg->method_depth);
11093 g_hash_table_destroy (acfg->plt_offset_to_entry);
11094 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11095 if (acfg->patch_to_plt_entry [i])
11096 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11098 g_free (acfg->patch_to_plt_entry);
11099 g_hash_table_destroy (acfg->method_to_cfg);
11100 g_hash_table_destroy (acfg->token_info_hash);
11101 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11102 g_hash_table_destroy (acfg->image_hash);
11103 g_hash_table_destroy (acfg->unwind_info_offsets);
11104 g_hash_table_destroy (acfg->method_label_hash);
11105 if (acfg->typespec_classes)
11106 g_hash_table_destroy (acfg->typespec_classes);
11107 g_hash_table_destroy (acfg->export_names);
11108 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11109 g_hash_table_destroy (acfg->klass_blob_hash);
11110 g_hash_table_destroy (acfg->method_blob_hash);
11111 got_info_free (&acfg->got_info);
11112 got_info_free (&acfg->llvm_got_info);
11113 mono_mempool_destroy (acfg->mempool);
11117 #define WRAPPER(e,n) n,
11118 static const char* const
11119 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11120 #include "mono/metadata/wrapper-types.h"
11124 static G_GNUC_UNUSED const char*
11125 get_wrapper_type_name (int type)
11127 return wrapper_type_names [type];
11133 static void aot_dump (MonoAotCompile *acfg)
11139 mono_json_writer_init (&writer);
11141 mono_json_writer_object_begin(&writer);
11144 mono_json_writer_indent (&writer);
11145 mono_json_writer_object_key(&writer, "methods");
11146 mono_json_writer_array_begin (&writer);
11149 for (i = 0; i < acfg->nmethods; ++i) {
11151 MonoMethod *method;
11154 cfg = acfg->cfgs [i];
11158 method = cfg->orig_method;
11160 mono_json_writer_indent (&writer);
11161 mono_json_writer_object_begin(&writer);
11163 mono_json_writer_indent (&writer);
11164 mono_json_writer_object_key(&writer, "name");
11165 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11167 mono_json_writer_indent (&writer);
11168 mono_json_writer_object_key(&writer, "signature");
11169 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11171 mono_json_writer_indent (&writer);
11172 mono_json_writer_object_key(&writer, "code_size");
11173 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11175 klass = method->klass;
11177 mono_json_writer_indent (&writer);
11178 mono_json_writer_object_key(&writer, "class");
11179 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11181 mono_json_writer_indent (&writer);
11182 mono_json_writer_object_key(&writer, "namespace");
11183 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11185 mono_json_writer_indent (&writer);
11186 mono_json_writer_object_key(&writer, "wrapper_type");
11187 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11189 mono_json_writer_indent_pop (&writer);
11190 mono_json_writer_indent (&writer);
11191 mono_json_writer_object_end (&writer);
11192 mono_json_writer_printf (&writer, ",\n");
11195 mono_json_writer_indent_pop (&writer);
11196 mono_json_writer_indent (&writer);
11197 mono_json_writer_array_end (&writer);
11198 mono_json_writer_printf (&writer, ",\n");
11202 mono_json_writer_indent_push (&writer);
11203 mono_json_writer_indent (&writer);
11204 mono_json_writer_object_key(&writer, "plt");
11205 mono_json_writer_array_begin (&writer);
11207 for (i = 0; i < acfg->plt_offset; ++i) {
11208 MonoPltEntry *plt_entry = NULL;
11213 * The first plt entry is unused.
11217 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11218 ji = plt_entry->ji;
11220 mono_json_writer_indent (&writer);
11221 mono_json_writer_printf (&writer, "{ ");
11222 mono_json_writer_object_key(&writer, "symbol");
11223 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11226 mono_json_writer_indent_pop (&writer);
11227 mono_json_writer_indent (&writer);
11228 mono_json_writer_array_end (&writer);
11229 mono_json_writer_printf (&writer, ",\n");
11234 mono_json_writer_indent_push (&writer);
11235 mono_json_writer_indent (&writer);
11236 mono_json_writer_object_key(&writer, "got");
11237 mono_json_writer_array_begin (&writer);
11239 mono_json_writer_indent_push (&writer);
11240 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11241 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11243 mono_json_writer_indent (&writer);
11244 mono_json_writer_printf (&writer, "{ ");
11245 mono_json_writer_object_key(&writer, "patch_name");
11246 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11249 mono_json_writer_indent_pop (&writer);
11250 mono_json_writer_indent (&writer);
11251 mono_json_writer_array_end (&writer);
11252 mono_json_writer_printf (&writer, ",\n");
11255 mono_json_writer_indent_pop (&writer);
11256 mono_json_writer_indent (&writer);
11257 mono_json_writer_object_end (&writer);
11259 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11260 dumpfile = fopen (dumpname, "w+");
11263 fprintf (dumpfile, "%s", writer.text->str);
11266 mono_json_writer_destroy (&writer);
11269 static const char *preinited_jit_icalls[] = {
11270 "mono_aot_init_llvm_method",
11271 "mono_aot_init_gshared_method_this",
11272 "mono_aot_init_gshared_method_mrgctx",
11273 "mono_aot_init_gshared_method_vtable",
11274 "mono_llvm_throw_corlib_exception",
11275 "mono_init_vtable_slot",
11276 "mono_helper_ldstr_mscorlib"
11280 add_preinit_got_slots (MonoAotCompile *acfg)
11286 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
11287 * during method initialization etc.
11290 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11291 ji->type = MONO_PATCH_INFO_IMAGE;
11292 ji->data.image = acfg->image;
11293 get_got_offset (acfg, FALSE, ji);
11294 get_got_offset (acfg, TRUE, ji);
11296 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11297 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
11298 get_got_offset (acfg, FALSE, ji);
11299 get_got_offset (acfg, TRUE, ji);
11301 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11302 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
11303 get_got_offset (acfg, FALSE, ji);
11304 get_got_offset (acfg, TRUE, ji);
11306 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11307 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
11308 get_got_offset (acfg, FALSE, ji);
11309 get_got_offset (acfg, TRUE, ji);
11311 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11312 ji->type = MONO_PATCH_INFO_AOT_MODULE;
11313 get_got_offset (acfg, FALSE, ji);
11314 get_got_offset (acfg, TRUE, ji);
11316 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11317 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
11318 get_got_offset (acfg, FALSE, ji);
11319 get_got_offset (acfg, TRUE, ji);
11321 for (i = 0; i < TLS_KEY_NUM; i++) {
11322 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11323 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
11324 ji->data.index = i;
11325 get_got_offset (acfg, FALSE, ji);
11326 get_got_offset (acfg, TRUE, ji);
11328 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11329 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
11330 ji->data.index = i;
11331 get_got_offset (acfg, FALSE, ji);
11332 get_got_offset (acfg, TRUE, ji);
11335 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11336 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
11337 get_got_offset (acfg, FALSE, ji);
11338 get_got_offset (acfg, TRUE, ji);
11340 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
11341 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
11342 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11343 ji->data.name = preinited_jit_icalls [i];
11344 get_got_offset (acfg, FALSE, ji);
11345 get_got_offset (acfg, TRUE, ji);
11348 acfg->nshared_got_entries = acfg->got_offset;
11352 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11354 MonoImage *image = ass->image;
11357 MonoAotCompile *acfg;
11358 char *outfile_name, *tmp_outfile_name, *p;
11359 char llvm_stats_msg [256];
11363 acfg = acfg_create (ass, opts);
11365 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
11366 acfg->aot_opts.write_symbols = TRUE;
11367 acfg->aot_opts.ntrampolines = 4096;
11368 acfg->aot_opts.nrgctx_trampolines = 4096;
11369 acfg->aot_opts.nimt_trampolines = 512;
11370 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
11371 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
11372 acfg->aot_opts.llvm_path = g_strdup ("");
11373 acfg->aot_opts.temp_path = g_strdup ("");
11375 acfg->aot_opts.use_trampolines_page = TRUE;
11378 mono_aot_parse_options (aot_options, &acfg->aot_opts);
11380 if (acfg->aot_opts.logfile) {
11381 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
11384 if (acfg->aot_opts.data_outfile) {
11385 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
11386 if (!acfg->data_outfile) {
11387 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
11390 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
11393 //acfg->aot_opts.print_skipped_methods = TRUE;
11395 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
11396 if (acfg->opts & MONO_OPT_GSHAREDVT) {
11397 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
11400 if (acfg->aot_opts.llvm_only) {
11401 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
11405 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11406 acfg->opts |= MONO_OPT_GSHAREDVT;
11409 #if !defined(ENABLE_LLVM)
11410 if (acfg->aot_opts.llvm_only) {
11411 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11416 if (acfg->opts & MONO_OPT_GSHAREDVT)
11417 mono_set_generic_sharing_vt_supported (TRUE);
11419 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11421 generate_aotid ((guint8*) &acfg->image->aotid);
11423 char *aotid = mono_guid_to_string (acfg->image->aotid);
11424 aot_printf (acfg, "AOTID %s\n", aotid);
11427 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11428 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11429 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11434 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11435 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11439 if (acfg->aot_opts.static_link)
11440 acfg->aot_opts.asm_writer = TRUE;
11442 if (acfg->aot_opts.soft_debug) {
11443 MonoDebugOptions *opt = mini_get_debug_options ();
11445 opt->mdb_optimizations = TRUE;
11446 opt->gen_sdb_seq_points = TRUE;
11448 if (!mono_debug_enabled ()) {
11449 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11452 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11455 if (mono_use_llvm || acfg->aot_opts.llvm) {
11457 acfg->aot_opts.asm_writer = TRUE;
11458 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11460 if (acfg->aot_opts.soft_debug) {
11461 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11467 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11468 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11473 if (mono_aot_mode_is_full (&acfg->aot_opts))
11474 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11476 if (mono_threads_is_coop_enabled ())
11477 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11479 if (acfg->aot_opts.instances_logfile_path) {
11480 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11481 if (!acfg->instances_logfile) {
11482 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11487 if (acfg->aot_opts.profile_files) {
11490 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11491 load_profile_file (acfg, (char*)l->data);
11498 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11499 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11503 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11504 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11505 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11507 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11508 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11509 if (acfg->opts & MONO_OPT_GSHAREDVT)
11510 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11513 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11517 if (mono_use_llvm || acfg->aot_opts.llvm) {
11520 * Emit all LLVM code into a separate assembly/object file and link with it
11523 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11524 acfg->llvm_owriter = TRUE;
11525 } else if (acfg->aot_opts.llvm_outfile) {
11526 int len = strlen (acfg->aot_opts.llvm_outfile);
11528 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11529 acfg->llvm_owriter = TRUE;
11533 if (acfg->llvm && acfg->thumb_mixed)
11534 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11535 if (acfg->aot_opts.llvm_only)
11536 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11538 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11539 /* Get rid of characters which cannot occur in symbols */
11540 for (p = acfg->assembly_name_sym; *p; ++p) {
11541 if (!(isalnum (*p) || *p == '_'))
11545 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11546 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11547 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11549 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11550 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11553 acfg->method_index = 1;
11555 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11556 mono_set_partial_sharing_supported (TRUE);
11558 res = collect_methods (acfg);
11565 for (l = acfg->profile_data; l; l = l->next)
11566 resolve_profile_data (acfg, (ProfileData*)l->data);
11567 for (l = acfg->profile_data; l; l = l->next)
11568 add_profile_instances (acfg, (ProfileData*)l->data);
11571 acfg->cfgs_size = acfg->methods->len + 32;
11572 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11574 /* PLT offset 0 is reserved for the PLT trampoline */
11575 acfg->plt_offset = 1;
11576 add_preinit_got_slots (acfg);
11581 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11587 compile_methods (acfg);
11591 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11597 if (acfg->aot_opts.asm_only) {
11598 if (acfg->aot_opts.outfile) {
11599 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11600 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11602 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11603 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11605 g_assert (acfg->aot_opts.llvm_outfile);
11606 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11607 if (acfg->llvm_owriter)
11608 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11610 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11612 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11613 g_strdup_printf ("%s", "temp") :
11614 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11616 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11617 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11618 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11623 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11624 if (acfg->aot_opts.outfile)
11625 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11627 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11628 acfg->fp = fopen (acfg->tmpfname, "w+");
11630 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11631 acfg->fp = fdopen (i, "w+");
11633 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11634 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11638 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11640 tmp_outfile_name = NULL;
11641 outfile_name = NULL;
11643 /* Compute symbols for methods */
11644 for (i = 0; i < acfg->nmethods; ++i) {
11645 if (acfg->cfgs [i]) {
11646 MonoCompile *cfg = acfg->cfgs [i];
11647 int method_index = get_method_index (acfg, cfg->orig_method);
11649 if (COMPILE_LLVM (cfg))
11650 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11651 else if (acfg->global_symbols || acfg->llvm)
11652 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11654 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11655 cfg->asm_debug_symbol = cfg->asm_symbol;
11659 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11661 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11663 acfg->gas_line_numbers = TRUE;
11666 #ifdef EMIT_DWARF_INFO
11667 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11668 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11669 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11672 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11674 #endif /* EMIT_DWARF_INFO */
11677 mono_img_writer_emit_start (acfg->w);
11680 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11686 emit_extra_methods (acfg);
11688 emit_trampolines (acfg);
11690 emit_class_name_table (acfg);
11692 emit_got_info (acfg, FALSE);
11694 emit_got_info (acfg, TRUE);
11696 emit_exception_info (acfg);
11698 emit_unwind_info (acfg);
11700 emit_class_info (acfg);
11704 emit_image_table (acfg);
11710 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11713 const char *gc_name = mono_gc_get_gc_name ();
11714 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11719 emit_objc_selectors (acfg);
11721 emit_globals (acfg);
11723 emit_file_info (acfg);
11725 emit_library_info (acfg);
11728 emit_dwarf_info (acfg);
11729 mono_dwarf_writer_close (acfg->dwarf);
11732 emit_mem_end (acfg);
11734 if (acfg->need_pt_gnu_stack) {
11735 /* This is required so the .so doesn't have an executable stack */
11736 /* The bin writer already emits this */
11737 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11740 if (acfg->aot_opts.data_outfile)
11741 fclose (acfg->data_outfile);
11747 res = emit_llvm_file (acfg);
11755 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11758 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11760 strcpy (llvm_stats_msg, "");
11762 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;
11764 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",
11765 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11766 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11767 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11768 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11769 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11770 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,
11771 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11772 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11773 (int)(acfg->got_offset * sizeof (gpointer)));
11774 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11775 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11777 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11778 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11779 if (acfg->stats.genericcount)
11780 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11781 if (acfg->stats.abscount)
11782 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11783 if (acfg->stats.lmfcount)
11784 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11785 if (acfg->stats.ocount)
11786 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11790 res = mono_img_writer_emit_writeout (acfg->w);
11795 res = compile_asm (acfg);
11802 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11804 if (acfg->aot_opts.stats) {
11807 aot_printf (acfg, "GOT slot distribution:\n");
11808 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11809 if (acfg->stats.got_slot_types [i])
11810 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]);
11811 aot_printf (acfg, "\nMethod stats:\n");
11812 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11813 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11814 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11815 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11818 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);
11820 if (acfg->aot_opts.dump_json)
11833 mono_aot_readonly_field_override (MonoClassField *field)
11839 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11845 mono_aot_is_shared_got_offset (int offset)