2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
7 * Johan Lorensson (lateralusx.github@gmail.com)
9 * (C) 2002 Ximian, Inc.
10 * Copyright 2003-2011 Novell, Inc
11 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <sys/types.h>
36 #include <mono/metadata/abi-details.h>
37 #include <mono/metadata/tabledefs.h>
38 #include <mono/metadata/class.h>
39 #include <mono/metadata/object.h>
40 #include <mono/metadata/tokentype.h>
41 #include <mono/metadata/appdomain.h>
42 #include <mono/metadata/debug-helpers.h>
43 #include <mono/metadata/assembly.h>
44 #include <mono/metadata/metadata-internals.h>
45 #include <mono/metadata/reflection-internals.h>
46 #include <mono/metadata/marshal.h>
47 #include <mono/metadata/gc-internals.h>
48 #include <mono/metadata/mempool-internals.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/threads-types.h>
51 #include <mono/utils/mono-logger-internals.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-time.h>
54 #include <mono/utils/mono-mmap.h>
55 #include <mono/utils/mono-rand.h>
56 #include <mono/utils/json.h>
57 #include <mono/utils/mono-threads-coop.h>
58 #include <mono/profiler/mono-profiler-aot.h>
59 #include <mono/io-layer/io-layer.h>
61 #include "aot-compiler.h"
62 #include "seq-points.h"
63 #include "image-writer.h"
64 #include "dwarfwriter.h"
66 #include "mini-llvm.h"
68 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
71 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
72 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
73 #define TARGET_X86_64_WIN32_MSVC
76 #if defined(TARGET_X86_64_WIN32_MSVC)
77 #define TARGET_WIN32_MSVC
80 #if defined(__linux__) || defined(__native_client_codegen__)
81 #define RODATA_SECT ".rodata"
82 #elif defined(TARGET_MACH)
83 #define RODATA_SECT ".section __TEXT, __const"
84 #elif defined(TARGET_WIN32_MSVC)
85 #define RODATA_SECT ".rdata"
87 #define RODATA_SECT ".text"
90 #define TV_DECLARE(name) gint64 name
91 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
92 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
94 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
95 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
96 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
103 typedef struct ClassProfileData ClassProfileData;
107 ClassProfileData **argv;
108 MonoGenericInst *inst;
111 struct ClassProfileData {
112 ImageProfileData *image;
114 GInstProfileData *inst;
119 ClassProfileData *klass;
124 GInstProfileData *inst;
129 GHashTable *images, *classes, *ginsts, *methods;
132 /* predefined values for static readonly fields without needed to run the .cctor */
133 typedef struct _ReadOnlyValue ReadOnlyValue;
134 struct _ReadOnlyValue {
137 int type; /* to be used later for typechecking to prevent user errors */
146 static ReadOnlyValue *readonly_values;
148 typedef struct MonoAotOptions {
152 GList *profile_files;
154 gboolean write_symbols;
155 gboolean metadata_only;
156 gboolean bind_to_runtime_version;
159 gboolean static_link;
163 gboolean dwarf_debug;
165 gboolean log_generics;
166 gboolean log_instances;
167 gboolean gen_msym_dir;
168 char *gen_msym_dir_path;
169 gboolean direct_pinvoke;
170 gboolean direct_icalls;
171 gboolean no_direct_calls;
172 gboolean use_trampolines_page;
173 gboolean no_instances;
179 int nrgctx_trampolines;
180 int nimt_trampolines;
181 int ngsharedvt_arg_trampolines;
182 int nrgctx_fetch_trampolines;
183 gboolean print_skipped_methods;
191 char *instances_logfile_path;
198 METHOD_CAT_GSHAREDVT,
204 typedef struct MonoAotStats {
205 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
206 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
207 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
208 int got_slots, offsets_size;
209 int method_categories [METHOD_CAT_NUM];
210 int got_slot_types [MONO_PATCH_INFO_NUM];
211 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
212 int jit_time, gen_time, link_time;
215 typedef struct GotInfo {
216 GHashTable *patch_to_got_offset;
217 GHashTable **patch_to_got_offset_by_type;
218 GPtrArray *got_patches;
221 typedef struct MonoAotCompile {
224 GHashTable *method_indexes;
225 GHashTable *method_depth;
228 GHashTable **patch_to_plt_entry;
229 GHashTable *plt_offset_to_entry;
230 //GHashTable *patch_to_got_offset;
231 //GHashTable **patch_to_got_offset_by_type;
232 //GPtrArray *got_patches;
233 GotInfo got_info, llvm_got_info;
234 GHashTable *image_hash;
235 GHashTable *method_to_cfg;
236 GHashTable *token_info_hash;
237 GHashTable *method_to_pinvoke_import;
238 GPtrArray *extra_methods;
239 GPtrArray *image_table;
241 GPtrArray *method_order;
242 GHashTable *export_names;
243 /* Maps MonoClass* -> blob offset */
244 GHashTable *klass_blob_hash;
245 /* Maps MonoMethod* -> blob offset */
246 GHashTable *method_blob_hash;
247 GHashTable *gsharedvt_in_signatures;
248 GHashTable *gsharedvt_out_signatures;
249 guint32 *plt_got_info_offsets;
250 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
251 /* Number of GOT entries reserved for trampolines */
252 guint32 num_trampoline_got_entries;
253 guint32 tramp_page_size;
255 guint32 table_offsets [MONO_AOT_TABLE_NUM];
256 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
257 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
258 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
259 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
261 MonoAotOptions aot_opts;
265 MonoMemPool *mempool;
268 char *static_linking_symbol;
270 gboolean gas_line_numbers;
271 /* Whenever to emit an object file directly from llc */
272 gboolean llvm_owriter;
273 gboolean llvm_owriter_supported;
275 MonoDwarfWriter *dwarf;
282 GHashTable *unwind_info_offsets;
283 GPtrArray *unwind_ops;
284 guint32 unwind_info_offset;
287 char *llvm_got_symbol;
289 char *llvm_eh_frame_symbol;
290 GHashTable *method_label_hash;
291 const char *temp_prefix;
292 const char *user_symbol_prefix;
293 const char *llvm_label_prefix;
294 const char *inst_directive;
296 guint32 label_generator;
298 gboolean has_jitted_code;
299 MonoAotFileFlags flags;
300 MonoDynamicStream blob;
301 gboolean blob_closed;
302 GHashTable *typespec_classes;
305 char *assembly_name_sym;
306 GHashTable *plt_entry_debug_sym_cache;
307 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
308 GHashTable *ginst_hash;
309 GHashTable *dwarf_ln_filenames;
310 gboolean global_symbols;
311 int objc_selector_index, objc_selector_index_2;
312 GPtrArray *objc_selectors;
313 GHashTable *objc_selector_to_index;
316 FILE *instances_logfile;
324 char *symbol, *llvm_symbol, *debug_sym;
326 gboolean jit_used, llvm_used;
329 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
330 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
332 /* This points to the current acfg in LLVM mode */
333 static MonoAotCompile *llvm_acfg;
335 #ifdef HAVE_ARRAY_ELEM_INIT
336 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
337 #define MSGSTRFIELD1(line) str##line
338 static const struct msgstr_t {
339 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
340 #include "patch-info.h"
343 #define PATCH_INFO(a,b) b,
344 #include "patch-info.h"
347 static const gint16 opidx [] = {
348 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
349 #include "patch-info.h"
353 static G_GNUC_UNUSED const char*
354 get_patch_name (int info)
356 return (const char*)&opstr + opidx [info];
360 #define PATCH_INFO(a,b) b,
361 static const char* const
362 patch_types [MONO_PATCH_INFO_NUM + 1] = {
363 #include "patch-info.h"
367 static G_GNUC_UNUSED const char*
368 get_patch_name (int info)
370 return patch_types [info];
376 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
379 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
382 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
385 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
388 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
394 output = acfg->logfile;
398 va_start (args, format);
399 vfprintf (output, format, args);
404 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
410 output = acfg->logfile;
414 va_start (args, format);
415 vfprintf (output, format, args);
420 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
425 if (mono_error_ok (error))
429 output = acfg->logfile;
433 va_start (args, format);
434 vfprintf (output, format, args);
436 mono_error_cleanup (error);
438 g_error ("FullAOT cannot continue if there are loader errors");
441 /* Wrappers around the image writer functions */
443 #define MAX_SYMBOL_SIZE 256
445 static inline const char *
446 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
448 gsize needed_size = length;
450 g_assert (NULL != symbol);
451 g_assert (NULL != mangled_symbol);
452 g_assert (0 != length);
454 #if defined(TARGET_WIN32) && defined(TARGET_X86)
455 if (symbol && '_' != symbol [0]) {
456 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
458 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
461 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
464 g_assert (0 <= needed_size && needed_size < length);
465 return mangled_symbol;
469 mangle_symbol_alloc (const char * symbol)
471 g_assert (NULL != symbol);
473 #if defined(TARGET_WIN32) && defined(TARGET_X86)
474 if (symbol && '_' != symbol [0]) {
475 return g_strdup_printf ("_%s", symbol);
478 return g_strdup_printf ("%s", symbol);
481 return g_strdup_printf ("%s", symbol);
486 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
488 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
491 #if defined(TARGET_WIN32) && defined(TARGET_X86)
494 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
496 const char * mangled_symbol_name = name;
497 char * mangled_symbol_name_alloc = NULL;
500 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
501 mangled_symbol_name = mangled_symbol_name_alloc;
504 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
505 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
507 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
509 if (NULL != mangled_symbol_name_alloc) {
510 g_free (mangled_symbol_name_alloc);
517 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
519 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
525 emit_label (MonoAotCompile *acfg, const char *name)
527 mono_img_writer_emit_label (acfg->w, name);
531 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
533 mono_img_writer_emit_bytes (acfg->w, buf, size);
537 emit_string (MonoAotCompile *acfg, const char *value)
539 mono_img_writer_emit_string (acfg->w, value);
543 emit_line (MonoAotCompile *acfg)
545 mono_img_writer_emit_line (acfg->w);
549 emit_alignment (MonoAotCompile *acfg, int size)
551 mono_img_writer_emit_alignment (acfg->w, size);
555 emit_alignment_code (MonoAotCompile *acfg, int size)
557 if (acfg->align_pad_value)
558 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
560 mono_img_writer_emit_alignment (acfg->w, size);
564 emit_padding (MonoAotCompile *acfg, int size)
569 if (acfg->align_pad_value) {
570 for (i = 0; i < 16; ++i)
571 buf [i] = acfg->align_pad_value;
573 memset (buf, 0, sizeof (buf));
576 for (i = 0; i < size; i += 16) {
578 emit_bytes (acfg, buf, size - i);
580 emit_bytes (acfg, buf, 16);
585 emit_pointer (MonoAotCompile *acfg, const char *target)
587 mono_img_writer_emit_pointer (acfg->w, target);
591 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
593 if (prefix [0] != '\0') {
594 char *s = g_strdup_printf ("%s%s", prefix, target);
595 mono_img_writer_emit_pointer (acfg->w, s);
598 mono_img_writer_emit_pointer (acfg->w, target);
603 emit_int16 (MonoAotCompile *acfg, int value)
605 mono_img_writer_emit_int16 (acfg->w, value);
609 emit_int32 (MonoAotCompile *acfg, int value)
611 mono_img_writer_emit_int32 (acfg->w, value);
615 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
617 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
621 emit_zero_bytes (MonoAotCompile *acfg, int num)
623 mono_img_writer_emit_zero_bytes (acfg->w, num);
627 emit_byte (MonoAotCompile *acfg, guint8 val)
629 mono_img_writer_emit_byte (acfg->w, val);
632 #if defined(TARGET_WIN32) && defined(TARGET_X86)
634 static G_GNUC_UNUSED void
635 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
637 const char * mangled_symbol_name = name;
638 char * mangled_symbol_name_alloc = NULL;
640 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
641 mangled_symbol_name = mangled_symbol_name_alloc;
643 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
644 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
646 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
648 if (NULL != mangled_symbol_name_alloc) {
649 g_free (mangled_symbol_name_alloc);
655 static G_GNUC_UNUSED void
656 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
658 mono_img_writer_emit_global (acfg->w, name, func);
663 static inline gboolean
664 link_shared_library (MonoAotCompile *acfg)
666 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
669 static inline gboolean
670 add_to_global_symbol_table (MonoAotCompile *acfg)
672 #ifdef TARGET_WIN32_MSVC
673 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
675 return acfg->aot_opts.no_dlsym;
680 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
682 if (add_to_global_symbol_table (acfg))
683 g_ptr_array_add (acfg->globals, g_strdup (name));
685 if (acfg->aot_opts.no_dlsym) {
686 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
688 emit_global_inner (acfg, name, func);
693 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
695 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
698 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
700 emit_info_symbol (MonoAotCompile *acfg, const char *name)
702 char symbol [MAX_SYMBOL_SIZE];
705 emit_label (acfg, name);
706 /* LLVM generated code references this */
707 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
708 emit_label (acfg, symbol);
709 emit_global_inner (acfg, symbol, FALSE);
711 emit_label (acfg, name);
716 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
719 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
723 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
725 /* On apple, all symbols need to be aligned to avoid warnings from ld */
726 emit_alignment (acfg, 4);
728 mono_img_writer_emit_label (acfg->w, name);
729 mono_img_writer_emit_string (acfg->w, value);
732 static G_GNUC_UNUSED void
733 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
736 guint8 b = value & 0x7f;
738 if (value != 0) /* more bytes to come */
744 static G_GNUC_UNUSED void
745 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
748 gboolean negative = (value < 0);
755 /* the following is unnecessary if the
756 * implementation of >>= uses an arithmetic rather
757 * than logical shift for a signed left operand
761 value |= - ((gint64)1 <<(size - 7));
762 /* sign bit of byte is second high order bit (0x40) */
763 if ((value == 0 && !(byte & 0x40)) ||
764 (value == -1 && (byte & 0x40)))
768 emit_byte (acfg, byte);
772 static G_GNUC_UNUSED void
773 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
778 guint8 b = value & 0x7f;
780 if (value != 0) /* more bytes to come */
788 static G_GNUC_UNUSED void
789 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
792 gboolean negative = (value < 0);
800 /* the following is unnecessary if the
801 * implementation of >>= uses an arithmetic rather
802 * than logical shift for a signed left operand
806 value |= - (1 <<(size - 7));
807 /* sign bit of byte is second high order bit (0x40) */
808 if ((value == 0 && !(byte & 0x40)) ||
809 (value == -1 && (byte & 0x40)))
820 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
823 buf [0] = (val >> 0) & 0xff;
824 buf [1] = (val >> 8) & 0xff;
825 buf [2] = (val >> 16) & 0xff;
826 buf [3] = (val >> 24) & 0xff;
832 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
834 buf [0] = (val >> 0) & 0xff;
835 buf [1] = (val >> 8) & 0xff;
841 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
843 int len = strlen (s);
845 memcpy (buf, s, len + 1);
846 *endbuf = buf + len + 1;
850 emit_unset_mode (MonoAotCompile *acfg)
852 mono_img_writer_emit_unset_mode (acfg->w);
855 static G_GNUC_UNUSED void
856 emit_set_thumb_mode (MonoAotCompile *acfg)
858 emit_unset_mode (acfg);
859 fprintf (acfg->fp, ".code 16\n");
862 static G_GNUC_UNUSED void
863 emit_set_arm_mode (MonoAotCompile *acfg)
865 emit_unset_mode (acfg);
866 fprintf (acfg->fp, ".code 32\n");
870 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
875 g_assert (size % 4 == 0);
876 emit_unset_mode (acfg);
877 for (i = 0; i < size; i += 4)
878 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
880 emit_bytes (acfg, buf, size);
884 /* ARCHITECTURE SPECIFIC CODE */
886 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
887 #define EMIT_DWARF_INFO 1
890 #ifdef TARGET_WIN32_MSVC
891 #undef EMIT_DWARF_INFO
894 #if defined(TARGET_ARM)
895 #define AOT_FUNC_ALIGNMENT 4
897 #define AOT_FUNC_ALIGNMENT 16
900 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
901 #define PPC_LD_OP "ld"
902 #define PPC_LDX_OP "ldx"
904 #define PPC_LD_OP "lwz"
905 #define PPC_LDX_OP "lwzx"
908 #ifdef TARGET_X86_64_WIN32_MSVC
909 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
911 #define AOT_TARGET_STR "AMD64"
916 #define AOT_TARGET_STR "ARM (MACH)"
918 #define AOT_TARGET_STR "ARM (!MACH)"
924 #define AOT_TARGET_STR "ARM64 (MACH)"
926 #define AOT_TARGET_STR "ARM64 (!MACH)"
930 #ifdef TARGET_POWERPC64
931 #ifdef __mono_ilp32__
932 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
934 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
937 #ifdef TARGET_POWERPC
938 #ifdef __mono_ilp32__
939 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
941 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
948 #define AOT_TARGET_STR "X86 (WIN32)"
949 #elif defined(__native_client_codegen__)
950 #define AOT_TARGET_STR "X86 (native client codegen)"
952 #define AOT_TARGET_STR "X86 (!native client codegen)"
956 #ifndef AOT_TARGET_STR
957 #define AOT_TARGET_STR ""
961 arch_init (MonoAotCompile *acfg)
963 acfg->llc_args = g_string_new ("");
964 acfg->as_args = g_string_new ("");
965 acfg->llvm_owriter_supported = TRUE;
968 * The prefix LLVM likes to put in front of symbol names on darwin.
969 * The mach-os specs require this for globals, but LLVM puts them in front of all
970 * symbols. We need to handle this, since we need to refer to LLVM generated
973 acfg->llvm_label_prefix = "";
974 acfg->user_symbol_prefix = "";
976 #if defined(TARGET_X86)
977 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
980 #if defined(TARGET_AMD64)
981 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
983 acfg->align_pad_value = 0x90;
987 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
988 g_string_append (acfg->llc_args, "-mattr=+v6");
990 #if defined(ARM_FPU_VFP_HARD)
991 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
992 g_string_append (acfg->as_args, " -mfpu=vfp3");
993 #elif defined(ARM_FPU_VFP)
994 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
995 g_string_append (acfg->as_args, " -mfpu=vfp3");
997 g_string_append (acfg->llc_args, " -soft-float");
1000 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1001 acfg->thumb_mixed = TRUE;
1003 if (acfg->aot_opts.mtriple)
1004 mono_arch_set_target (acfg->aot_opts.mtriple);
1008 acfg->inst_directive = ".inst";
1009 if (acfg->aot_opts.mtriple)
1010 mono_arch_set_target (acfg->aot_opts.mtriple);
1014 acfg->user_symbol_prefix = "_";
1015 acfg->llvm_label_prefix = "_";
1016 acfg->inst_directive = ".word";
1017 acfg->need_no_dead_strip = TRUE;
1018 acfg->aot_opts.gnu_asm = TRUE;
1021 #if defined(__linux__) && !defined(TARGET_ARM)
1022 acfg->need_pt_gnu_stack = TRUE;
1026 acfg->global_symbols = TRUE;
1029 #ifdef TARGET_ANDROID
1030 acfg->llvm_owriter_supported = FALSE;
1037 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1039 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1043 g_assert (acfg->fp);
1044 emit_unset_mode (acfg);
1046 offset = (int)(got_slot * sizeof (gpointer));
1048 /* clang's integrated assembler */
1049 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1050 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1051 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1054 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1055 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1056 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1061 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1065 g_assert (acfg->fp);
1066 emit_unset_mode (acfg);
1068 /* ldr rt, target */
1069 reg = arm_get_ldr_lit_reg (code);
1071 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1072 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1073 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1079 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1081 g_assert (acfg->fp);
1082 emit_unset_mode (acfg);
1083 if (ji && ji->relocation == MONO_R_ARM64_B) {
1084 fprintf (acfg->fp, "b %s\n", target);
1087 g_assert (ji->relocation == MONO_R_ARM64_BL);
1088 fprintf (acfg->fp, "bl %s\n", target);
1094 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1098 /* ldr rt, target */
1099 reg = arm_get_ldr_lit_reg (code);
1100 arm64_emit_load_got_slot (acfg, reg, got_slot);
1105 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1107 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1108 fprintf (acfg->fp, "br x16\n");
1109 /* Used by mono_aot_get_plt_info_offset () */
1110 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1114 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1120 /* The common code */
1123 /* The trampoline address is in IP0 */
1124 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1125 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1126 /* Compute the data slot address */
1127 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1128 /* Trampoline argument */
1129 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1131 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1132 arm_brx (code, ARMREG_IP0);
1135 emit_code_bytes (acfg, buf, code - buf);
1141 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1147 count = (pagesize - common_tramp_size) / specific_tramp_size;
1148 for (i = 0; i < count; ++i) {
1150 arm_adrx (code, ARMREG_IP0, code);
1151 /* Branch to the generic code */
1152 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1153 /* This has to be 2 pointers long */
1156 g_assert (code - buf == specific_tramp_size);
1157 emit_code_bytes (acfg, buf, code - buf);
1162 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1166 guint8 *labels [16];
1167 int common_tramp_size;
1168 int specific_tramp_size = 2 * 8;
1172 if (!acfg->aot_opts.use_trampolines_page)
1176 /* Have to match the target pagesize */
1179 pagesize = mono_pagesize ();
1181 acfg->tramp_page_size = pagesize;
1183 /* The specific trampolines */
1184 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1185 emit_alignment (acfg, pagesize);
1186 emit_global (acfg, symbol, TRUE);
1187 emit_label (acfg, symbol);
1189 /* The common code */
1190 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1191 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1193 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1195 /* The rgctx trampolines */
1196 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1197 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1198 emit_alignment (acfg, pagesize);
1199 emit_global (acfg, symbol, TRUE);
1200 emit_label (acfg, symbol);
1202 /* The common code */
1203 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1204 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1206 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1208 /* The gsharedvt arg trampolines */
1209 /* These are the same as the specific trampolines */
1210 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1211 emit_alignment (acfg, pagesize);
1212 emit_global (acfg, symbol, TRUE);
1213 emit_label (acfg, symbol);
1215 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1216 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1218 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1220 /* The IMT trampolines */
1221 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1222 emit_alignment (acfg, pagesize);
1223 emit_global (acfg, symbol, TRUE);
1224 emit_label (acfg, symbol);
1228 /* The trampoline address is in IP0 */
1229 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1230 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1231 /* Compute the data slot address */
1232 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1233 /* Trampoline argument */
1234 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1236 /* Same as arch_emit_imt_trampoline () */
1238 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1239 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1241 arm_bcc (code, ARMCOND_EQ, 0);
1243 /* End-of-loop check */
1245 arm_cbzx (code, ARMREG_IP0, 0);
1248 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1249 arm_b (code, labels [0]);
1252 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1253 /* Load vtable slot addr */
1254 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1255 /* Load vtable slot */
1256 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1257 arm_brx (code, ARMREG_IP0);
1260 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1261 /* Load fail addr */
1262 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1263 arm_brx (code, ARMREG_IP0);
1265 emit_code_bytes (acfg, buf, code - buf);
1267 common_tramp_size = code - buf;
1268 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1270 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1274 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1276 /* Load argument from second GOT slot */
1277 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1278 /* Load generic trampoline address from first GOT slot */
1279 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1280 fprintf (acfg->fp, "br x16\n");
1281 *tramp_size = 7 * 4;
1285 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1287 emit_unset_mode (acfg);
1288 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1289 fprintf (acfg->fp, "b %s\n", call_target);
1293 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1295 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1297 /* Load argument from first GOT slot */
1298 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1299 /* Load generic trampoline address from second GOT slot */
1300 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1301 fprintf (acfg->fp, "br x16\n");
1302 *tramp_size = 7 * 4;
1306 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1309 guint8 *code, *labels [16];
1311 /* Load parameter from GOT slot into ip1 */
1312 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1316 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1317 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1319 arm_bcc (code, ARMCOND_EQ, 0);
1321 /* End-of-loop check */
1323 arm_cbzx (code, ARMREG_IP0, 0);
1326 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1327 arm_b (code, labels [0]);
1330 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1331 /* Load vtable slot addr */
1332 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1333 /* Load vtable slot */
1334 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1335 arm_brx (code, ARMREG_IP0);
1338 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1339 /* Load fail addr */
1340 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1341 arm_brx (code, ARMREG_IP0);
1343 emit_code_bytes (acfg, buf, code - buf);
1345 *tramp_size = code - buf + (3 * 4);
1349 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1351 /* Similar to the specific trampolines, but the address is in the second slot */
1352 /* Load argument from first GOT slot */
1353 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1354 /* Load generic trampoline address from second GOT slot */
1355 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1356 fprintf (acfg->fp, "br x16\n");
1357 *tramp_size = 7 * 4;
1363 #ifdef MONO_ARCH_AOT_SUPPORTED
1365 * arch_emit_direct_call:
1367 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1371 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1373 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1374 /* Need to make sure this is exactly 5 bytes long */
1375 emit_unset_mode (acfg);
1376 fprintf (acfg->fp, "call %s\n", target);
1378 #elif defined(TARGET_ARM)
1379 emit_unset_mode (acfg);
1381 fprintf (acfg->fp, "blx %s\n", target);
1383 fprintf (acfg->fp, "bl %s\n", target);
1385 #elif defined(TARGET_ARM64)
1386 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1387 #elif defined(TARGET_POWERPC)
1388 emit_unset_mode (acfg);
1389 fprintf (acfg->fp, "bl %s\n", target);
1392 g_assert_not_reached ();
1399 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1401 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1402 * in in the 2. slot of every GOT, and require every method to place the GOT
1403 * address in r30, even when it doesn't access the GOT otherwise. This way,
1404 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1409 * PPC64 uses function descriptors which greatly complicate all code, since
1410 * these are used very inconsistently in the runtime. Some functions like
1411 * mono_compile_method () return ftn descriptors, while others like the
1412 * trampoline creation functions do not.
1413 * We assume that all GOT slots contain function descriptors, and create
1414 * descriptors in aot-runtime.c when needed.
1415 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1416 * from function descriptors, we could do the same, but it would require
1417 * rewriting all the ppc/aot code to handle function descriptors properly.
1418 * So instead, we use the same approach as on PPC32.
1419 * This is a horrible mess, but fixing it would probably lead to an even bigger
1425 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1428 #ifdef MONO_ARCH_AOT_SUPPORTED
1430 * arch_emit_got_offset:
1432 * The memory pointed to by CODE should hold native code for computing the GOT
1433 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1434 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1437 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1439 #if defined(TARGET_POWERPC64)
1440 emit_unset_mode (acfg);
1442 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1443 * unsupported relocations. So we store the got address into the .Lgot_addr
1444 * symbol which is in the text segment, compute its address, and load it.
1446 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1447 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1448 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1449 fprintf (acfg->fp, "add 30, 30, 0\n");
1450 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1451 acfg->label_generator ++;
1453 #elif defined(TARGET_POWERPC)
1454 emit_unset_mode (acfg);
1455 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1456 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1457 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1458 acfg->label_generator ++;
1461 guint32 offset = mono_arch_get_patch_offset (code);
1462 emit_bytes (acfg, code, offset);
1463 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1465 *code_size = offset + 4;
1470 * arch_emit_got_access:
1472 * The memory pointed to by CODE should hold native code for loading a GOT
1473 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1474 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1477 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1480 /* mov reg, got+offset(%rip) */
1482 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1486 /* Decode reg, see amd64_mov_reg_membase () */
1487 rex_r = code [0] & AMD64_REX_R;
1488 g_assert (code [0] == 0x49 + rex_r);
1489 g_assert (code [1] == 0x8b);
1490 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1492 emit_unset_mode (acfg);
1493 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1496 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1497 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1498 *code_size = mono_arch_get_patch_offset (code) + 4;
1500 #elif defined(TARGET_X86)
1501 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1502 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1503 *code_size = mono_arch_get_patch_offset (code) + 4;
1504 #elif defined(TARGET_ARM)
1505 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1506 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1507 *code_size = mono_arch_get_patch_offset (code) + 4;
1508 #elif defined(TARGET_ARM64)
1509 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1510 arm64_emit_got_access (acfg, code, got_slot, code_size);
1511 #elif defined(TARGET_POWERPC)
1515 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1517 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1518 g_assert (code - buf == 8);
1519 emit_bytes (acfg, buf, code - buf);
1520 *code_size = code - buf;
1523 g_assert_not_reached ();
1529 #ifdef MONO_ARCH_AOT_SUPPORTED
1531 * arch_emit_objc_selector_ref:
1533 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1536 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1538 #if defined(TARGET_ARM)
1539 char symbol1 [MAX_SYMBOL_SIZE];
1540 char symbol2 [MAX_SYMBOL_SIZE];
1541 int lindex = acfg->objc_selector_index_2 ++;
1543 /* Emit ldr.imm/b */
1544 emit_bytes (acfg, code, 8);
1546 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1547 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1549 emit_label (acfg, symbol1);
1550 mono_img_writer_emit_unset_mode (acfg->w);
1551 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1554 #elif defined(TARGET_ARM64)
1555 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1557 g_assert_not_reached ();
1563 * arch_emit_plt_entry:
1565 * Emit code for the PLT entry.
1566 * The plt entry should look like this:
1567 * <indirect jump to GOT_SYMBOL + OFFSET>
1568 * <INFO_OFFSET embedded into the instruction stream>
1571 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1573 #if defined(TARGET_X86)
1574 /* jmp *<offset>(%ebx) */
1575 emit_byte (acfg, 0xff);
1576 emit_byte (acfg, 0xa3);
1577 emit_int32 (acfg, offset);
1578 /* Used by mono_aot_get_plt_info_offset */
1579 emit_int32 (acfg, info_offset);
1580 #elif defined(TARGET_AMD64)
1581 emit_unset_mode (acfg);
1582 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1583 /* Used by mono_aot_get_plt_info_offset */
1584 emit_int32 (acfg, info_offset);
1585 acfg->stats.plt_size += 10;
1586 #elif defined(TARGET_ARM)
1591 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1592 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1593 emit_bytes (acfg, buf, code - buf);
1594 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1595 /* Used by mono_aot_get_plt_info_offset */
1596 emit_int32 (acfg, info_offset);
1597 #elif defined(TARGET_ARM64)
1598 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1599 #elif defined(TARGET_POWERPC)
1600 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1601 emit_unset_mode (acfg);
1602 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1603 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1604 fprintf (acfg->fp, "add 11, 11, 30\n");
1605 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1606 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1607 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1608 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1610 fprintf (acfg->fp, "mtctr 11\n");
1611 fprintf (acfg->fp, "bctr\n");
1612 emit_int32 (acfg, info_offset);
1614 g_assert_not_reached ();
1619 * arch_emit_llvm_plt_entry:
1621 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1622 * This is only needed on arm to handle thumb interop.
1625 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1627 #if defined(TARGET_ARM)
1628 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1629 /* The caller already transitioned to thumb */
1630 /* The code below should be 12 bytes long */
1631 /* clang has trouble encoding these instructions, so emit the binary */
1633 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1634 /* thumb can't encode ld pc, [pc, ip] */
1635 fprintf (acfg->fp, "add ip, pc, ip\n");
1636 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1637 fprintf (acfg->fp, "bx ip\n");
1639 emit_set_thumb_mode (acfg);
1640 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1641 fprintf (acfg->fp, ".2byte 0x44fc\n");
1642 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1643 fprintf (acfg->fp, ".2byte 0x4760\n");
1644 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1645 emit_int32 (acfg, info_offset);
1646 emit_unset_mode (acfg);
1647 emit_set_arm_mode (acfg);
1649 g_assert_not_reached ();
1653 /* Save unwind_info in the module and emit the offset to the information at symbol */
1654 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1656 guint32 uw_offset, encoded_len;
1659 emit_section_change (acfg, RODATA_SECT, 0);
1660 emit_global (acfg, symbol, FALSE);
1661 emit_label (acfg, symbol);
1663 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1664 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1666 emit_int32 (acfg, uw_offset);
1670 * arch_emit_specific_trampoline_pages:
1672 * Emits a page full of trampolines: each trampoline uses its own address to
1673 * lookup both the generic trampoline code and the data argument.
1674 * This page can be remapped in process multiple times so we can get an
1675 * unlimited number of trampolines.
1676 * Specifically this implementation uses the following trick: two memory pages
1677 * are allocated, with the first containing the data and the second containing the trampolines.
1678 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1679 * implementation does all the lifting.
1680 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1681 * on the arm 32 bit system.
1684 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1686 #if defined(TARGET_ARM)
1689 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1691 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1692 GSList *unwind_ops = NULL;
1693 #define COMMON_TRAMP_SIZE 16
1694 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1695 int imm8, rot_amount;
1698 if (!acfg->aot_opts.use_trampolines_page)
1701 acfg->tramp_page_size = pagesize;
1703 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1704 emit_alignment (acfg, pagesize);
1705 emit_global (acfg, symbol, TRUE);
1706 emit_label (acfg, symbol);
1708 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1710 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1711 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1712 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1713 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1715 g_assert (code - buf == COMMON_TRAMP_SIZE);
1718 emit_bytes (acfg, buf, code - buf);
1720 for (i = 0; i < count; ++i) {
1722 ARM_PUSH (code, 0x5fff);
1724 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1725 g_assert (code - buf == 8);
1726 emit_bytes (acfg, buf, code - buf);
1729 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1730 * the instruction pointer address, so the generic trampoline at the start of the page
1731 * subtracts 4096 to get to the data page and loads the values
1732 * We again fit the generic trampiline in 16 bytes.
1734 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1735 emit_global (acfg, symbol, TRUE);
1736 emit_label (acfg, symbol);
1738 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1739 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1740 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1741 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1743 g_assert (code - buf == COMMON_TRAMP_SIZE);
1746 emit_bytes (acfg, buf, code - buf);
1748 for (i = 0; i < count; ++i) {
1750 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1752 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1753 g_assert (code - buf == 8);
1754 emit_bytes (acfg, buf, code - buf);
1758 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1760 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1761 emit_global (acfg, symbol, TRUE);
1762 emit_label (acfg, symbol);
1764 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1765 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1766 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1767 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1768 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1769 g_assert (code - buf == COMMON_TRAMP_SIZE);
1771 emit_bytes (acfg, buf, code - buf);
1773 for (i = 0; i < count; ++i) {
1775 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1777 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1778 g_assert (code - buf == 8);
1779 emit_bytes (acfg, buf, code - buf);
1782 /* now the imt trampolines: each specific trampolines puts in the ip register
1783 * the instruction pointer address, so the generic trampoline at the start of the page
1784 * subtracts 4096 to get to the data page and loads the values
1786 #define IMT_TRAMP_SIZE 72
1787 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1788 emit_global (acfg, symbol, TRUE);
1789 emit_label (acfg, symbol);
1791 /* Need at least two free registers, plus a slot for storing the pc */
1792 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1794 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1795 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1796 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1798 /* The IMT method is in v5, r0 has the imt array address */
1801 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1802 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1803 imt_found_check = code;
1804 ARM_B_COND (code, ARMCOND_EQ, 0);
1806 /* End-of-loop check */
1807 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1808 loop_end_check = code;
1809 ARM_B_COND (code, ARMCOND_EQ, 0);
1812 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1813 loop_branch_back = code;
1815 arm_patch (loop_branch_back, loop_start);
1818 arm_patch (imt_found_check, code);
1819 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1820 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1821 /* Save it to the third stack slot */
1822 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1823 /* Restore the registers and branch */
1824 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1827 arm_patch (loop_end_check, code);
1828 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1829 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1830 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1834 g_assert (code - buf == IMT_TRAMP_SIZE);
1835 emit_bytes (acfg, buf, code - buf);
1837 for (i = 0; i < count; ++i) {
1839 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1841 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1842 g_assert (code - buf == 8);
1843 emit_bytes (acfg, buf, code - buf);
1846 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1847 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1848 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1849 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1851 /* Unwind info for specifc trampolines */
1852 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1853 /* We unwind to the original caller, from the stack, since lr is clobbered */
1854 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1855 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1856 save_unwind_info (acfg, symbol, unwind_ops);
1857 mono_free_unwind_info (unwind_ops);
1859 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1860 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1861 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1862 save_unwind_info (acfg, symbol, unwind_ops);
1863 mono_free_unwind_info (unwind_ops);
1865 /* Unwind info for rgctx trampolines */
1866 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1867 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1868 save_unwind_info (acfg, symbol, unwind_ops);
1870 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1871 save_unwind_info (acfg, symbol, unwind_ops);
1872 mono_free_unwind_info (unwind_ops);
1874 /* Unwind info for gsharedvt trampolines */
1875 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1876 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1877 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1878 save_unwind_info (acfg, symbol, unwind_ops);
1879 mono_free_unwind_info (unwind_ops);
1881 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1882 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1883 save_unwind_info (acfg, symbol, unwind_ops);
1884 mono_free_unwind_info (unwind_ops);
1886 /* Unwind info for imt trampolines */
1887 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1888 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1889 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1890 save_unwind_info (acfg, symbol, unwind_ops);
1891 mono_free_unwind_info (unwind_ops);
1893 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1894 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1895 save_unwind_info (acfg, symbol, unwind_ops);
1896 mono_free_unwind_info (unwind_ops);
1897 #elif defined(TARGET_ARM64)
1898 arm64_emit_specific_trampoline_pages (acfg);
1903 * arch_emit_specific_trampoline:
1905 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1906 * two GOT slots which contain the generic trampoline address and the trampoline
1907 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1910 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1913 * The trampolines created here are variations of the specific
1914 * trampolines created in mono_arch_create_specific_trampoline (). The
1916 * - the generic trampoline address is taken from a got slot.
1917 * - the offset of the got slot where the trampoline argument is stored
1918 * is embedded in the instruction stream, and the generic trampoline
1919 * can load the argument by loading the offset, adding it to the
1920 * address of the trampoline to get the address of the got slot, and
1921 * loading the argument from there.
1922 * - all the trampolines should be of the same length.
1924 #if defined(TARGET_AMD64)
1925 /* This should be exactly 8 bytes long */
1927 /* call *<offset>(%rip) */
1929 emit_unset_mode (acfg);
1930 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1931 emit_zero_bytes (acfg, 2);
1933 emit_byte (acfg, '\x41');
1934 emit_byte (acfg, '\xff');
1935 emit_byte (acfg, '\x15');
1936 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1937 emit_zero_bytes (acfg, 1);
1939 #elif defined(TARGET_ARM)
1943 /* This should be exactly 20 bytes long */
1946 ARM_PUSH (code, 0x5fff);
1947 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1948 /* Load the value from the GOT */
1949 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1951 ARM_BLX_REG (code, ARMREG_R1);
1953 g_assert (code - buf == 16);
1956 emit_bytes (acfg, buf, code - buf);
1958 * Only one offset is needed, since the second one would be equal to the
1961 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1962 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1963 #elif defined(TARGET_ARM64)
1964 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1965 #elif defined(TARGET_POWERPC)
1973 * PPC has no ip relative addressing, so we need to compute the address
1974 * of the mscorlib got. That is slow and complex, so instead, we store it
1975 * in the second got slot of every aot image. The caller already computed
1976 * the address of its got and placed it into r30.
1978 emit_unset_mode (acfg);
1979 /* Load mscorlib got address */
1980 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1981 /* Load generic trampoline address */
1982 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1983 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1984 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1985 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1986 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1988 fprintf (acfg->fp, "mtctr 11\n");
1989 /* Load trampoline argument */
1990 /* On ppc, we pass it normally to the generic trampoline */
1991 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1992 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1993 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1994 /* Branch to generic trampoline */
1995 fprintf (acfg->fp, "bctr\n");
1997 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1998 *tramp_size = 10 * 4;
2000 *tramp_size = 9 * 4;
2002 #elif defined(TARGET_X86)
2006 /* Similar to the PPC code above */
2008 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2011 /* Load mscorlib got address */
2012 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2013 /* Push trampoline argument */
2014 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2015 /* Load generic trampoline address */
2016 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2017 /* Branch to generic trampoline */
2018 x86_jump_reg (code, X86_ECX);
2020 emit_bytes (acfg, buf, code - buf);
2023 g_assert (code - buf == *tramp_size);
2025 g_assert_not_reached ();
2030 * arch_emit_unbox_trampoline:
2032 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2033 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2036 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2038 #if defined(TARGET_AMD64)
2043 this_reg = mono_arch_get_this_arg_reg (NULL);
2045 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2047 emit_bytes (acfg, buf, code - buf);
2050 emit_unset_mode (acfg);
2051 fprintf (acfg->fp, "jmp %s\n", call_target);
2053 emit_byte (acfg, '\xe9');
2054 emit_symbol_diff (acfg, call_target, ".", -4);
2056 #elif defined(TARGET_X86)
2063 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2065 emit_bytes (acfg, buf, code - buf);
2068 emit_byte (acfg, '\xe9');
2069 emit_symbol_diff (acfg, call_target, ".", -4);
2070 #elif defined(TARGET_ARM)
2074 if (acfg->thumb_mixed && cfg->compile_llvm) {
2075 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2076 fprintf (acfg->fp, "b %s\n", call_target);
2077 fprintf (acfg->fp, ".arm\n");
2078 fprintf (acfg->fp, ".align 2\n");
2084 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2086 emit_bytes (acfg, buf, code - buf);
2087 /* jump to method */
2088 if (acfg->thumb_mixed && cfg->compile_llvm)
2089 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2091 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2092 #elif defined(TARGET_ARM64)
2093 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2094 #elif defined(TARGET_POWERPC)
2097 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2098 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2100 g_assert_not_reached ();
2105 * arch_emit_static_rgctx_trampoline:
2107 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2108 * two GOT slots which contain the rgctx argument, and the method to jump to.
2109 * TRAMP_SIZE is set to the size of the emitted trampoline.
2110 * These kinds of trampolines cannot be enumerated statically, since there could
2111 * be one trampoline per method instantiation, so we emit the same code for all
2112 * trampolines, and parameterize them using two GOT slots.
2115 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2117 #if defined(TARGET_AMD64)
2118 /* This should be exactly 13 bytes long */
2122 emit_unset_mode (acfg);
2123 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2124 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2126 /* mov <OFFSET>(%rip), %r10 */
2127 emit_byte (acfg, '\x4d');
2128 emit_byte (acfg, '\x8b');
2129 emit_byte (acfg, '\x15');
2130 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2132 /* jmp *<offset>(%rip) */
2133 emit_byte (acfg, '\xff');
2134 emit_byte (acfg, '\x25');
2135 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2137 #elif defined(TARGET_ARM)
2141 /* This should be exactly 24 bytes long */
2144 /* Load rgctx value */
2145 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2146 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2147 /* Load branch addr + branch */
2148 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2149 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2151 g_assert (code - buf == 16);
2154 emit_bytes (acfg, buf, code - buf);
2155 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2156 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2157 #elif defined(TARGET_ARM64)
2158 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2159 #elif defined(TARGET_POWERPC)
2167 * PPC has no ip relative addressing, so we need to compute the address
2168 * of the mscorlib got. That is slow and complex, so instead, we store it
2169 * in the second got slot of every aot image. The caller already computed
2170 * the address of its got and placed it into r30.
2172 emit_unset_mode (acfg);
2173 /* Load mscorlib got address */
2174 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2176 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2177 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2178 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2179 /* Load target address */
2180 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2181 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2182 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2183 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2184 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2185 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2187 fprintf (acfg->fp, "mtctr 11\n");
2188 /* Branch to the target address */
2189 fprintf (acfg->fp, "bctr\n");
2191 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2192 *tramp_size = 11 * 4;
2194 *tramp_size = 9 * 4;
2197 #elif defined(TARGET_X86)
2201 /* Similar to the PPC code above */
2203 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2206 /* Load mscorlib got address */
2207 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2209 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2210 /* Branch to the target address */
2211 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2213 emit_bytes (acfg, buf, code - buf);
2216 g_assert (code - buf == *tramp_size);
2218 g_assert_not_reached ();
2223 * arch_emit_imt_trampoline:
2225 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2226 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2227 * key is the IMT key, and ptr holds the address of a memory location holding
2228 * the address to branch to if the IMT arg matches the key. The array is
2229 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2231 * TRAMP_SIZE is set to the size of the emitted trampoline.
2234 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2236 #if defined(TARGET_AMD64)
2238 guint8 *labels [16];
2240 guint8 *mov_buf_ptr = mov_buf;
2242 const int kSizeOfMove = 7;
2244 code = buf = (guint8 *)g_malloc (256);
2246 /* FIXME: Optimize this, i.e. use binary search etc. */
2247 /* Maybe move the body into a separate function (slower, but much smaller) */
2249 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2252 emit_unset_mode (acfg);
2253 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2257 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2259 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2262 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2264 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2267 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2268 amd64_jump_code (code, labels [0]);
2271 mono_amd64_patch (labels [2], code);
2272 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2273 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2276 mono_amd64_patch (labels [1], code);
2277 /* Load fail tramp */
2278 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2279 /* Check if there is a fail tramp */
2280 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2282 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2283 /* Jump to fail tramp */
2284 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2287 mono_amd64_patch (labels [3], code);
2288 x86_breakpoint (code);
2291 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2292 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2293 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2294 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2295 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2296 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2298 emit_bytes (acfg, buf, code - buf);
2300 *tramp_size = code - buf + kSizeOfMove;
2304 #elif defined(TARGET_X86)
2306 guint8 *labels [16];
2308 code = buf = g_malloc (256);
2310 /* Allocate a temporary stack slot */
2311 x86_push_reg (code, X86_EAX);
2313 x86_push_reg (code, X86_EAX);
2315 /* Load mscorlib got address */
2316 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2318 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2321 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2323 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2326 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2328 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2331 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2332 x86_jump_code (code, labels [0]);
2335 mono_x86_patch (labels [2], code);
2336 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2337 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2338 /* Save the target address to the temporary stack location */
2339 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2341 x86_pop_reg (code, X86_EAX);
2342 /* Jump to the target address */
2346 mono_x86_patch (labels [1], code);
2347 /* Load fail tramp */
2348 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2349 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2351 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2352 /* Jump to fail tramp */
2353 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2354 x86_pop_reg (code, X86_EAX);
2358 mono_x86_patch (labels [3], code);
2359 x86_breakpoint (code);
2361 emit_bytes (acfg, buf, code - buf);
2363 *tramp_size = code - buf;
2367 #elif defined(TARGET_ARM)
2369 guint8 *code, *code2, *labels [16];
2373 /* The IMT method is in v5 */
2375 /* Need at least two free registers, plus a slot for storing the pc */
2376 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2378 /* Load the parameter from the GOT */
2379 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2380 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2383 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2384 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2386 ARM_B_COND (code, ARMCOND_EQ, 0);
2388 /* End-of-loop check */
2389 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2391 ARM_B_COND (code, ARMCOND_EQ, 0);
2394 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2397 arm_patch (labels [4], labels [1]);
2400 arm_patch (labels [2], code);
2401 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2402 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2403 /* Save it to the third stack slot */
2404 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2405 /* Restore the registers and branch */
2406 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2409 arm_patch (labels [3], code);
2410 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2411 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2412 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2416 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2418 emit_bytes (acfg, buf, code - buf);
2419 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2421 *tramp_size = code - buf + 4;
2422 #elif defined(TARGET_ARM64)
2423 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2424 #elif defined(TARGET_POWERPC)
2426 guint8 *code, *labels [16];
2430 /* Load the mscorlib got address */
2431 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2432 /* Load the parameter from the GOT */
2433 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2434 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2436 /* Load and check key */
2438 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2439 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2441 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2443 /* End-of-loop check */
2444 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2446 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2449 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2452 mono_ppc_patch (labels [4], labels [1]);
2455 mono_ppc_patch (labels [2], code);
2456 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2457 /* r12 now contains the value of the vtable slot */
2458 /* this is not a function descriptor on ppc64 */
2459 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2460 ppc_mtctr (code, ppc_r12);
2461 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2464 mono_ppc_patch (labels [3], code);
2468 *tramp_size = code - buf;
2470 emit_bytes (acfg, buf, code - buf);
2472 g_assert_not_reached ();
2477 #if defined (TARGET_AMD64)
2480 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2483 g_assert (acfg->fp);
2484 emit_unset_mode (acfg);
2486 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2493 * arch_emit_gsharedvt_arg_trampoline:
2495 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2496 * two GOT slots which contain the argument, and the code to jump to.
2497 * TRAMP_SIZE is set to the size of the emitted trampoline.
2498 * These kinds of trampolines cannot be enumerated statically, since there could
2499 * be one trampoline per method instantiation, so we emit the same code for all
2500 * trampolines, and parameterize them using two GOT slots.
2503 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2505 #if defined(TARGET_X86)
2509 /* Similar to the PPC code above */
2511 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2514 /* Load mscorlib got address */
2515 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2517 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2518 /* Branch to the target address */
2519 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2521 emit_bytes (acfg, buf, code - buf);
2524 g_assert (code - buf == *tramp_size);
2525 #elif defined(TARGET_ARM)
2529 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2530 /* Similar to arch_emit_specific_trampoline () */
2533 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2534 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2535 /* Load the arg value from the GOT */
2536 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2537 /* Load the addr from the GOT */
2538 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2540 ARM_BX (code, ARMREG_R1);
2542 g_assert (code - buf == 20);
2545 emit_bytes (acfg, buf, code - buf);
2546 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2547 #elif defined(TARGET_ARM64)
2548 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2549 #elif defined (TARGET_AMD64)
2551 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2552 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2553 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2554 fprintf (acfg->fp, "jmp *%%r11\n");
2558 g_assert_not_reached ();
2562 /* END OF ARCH SPECIFIC CODE */
2565 mono_get_field_token (MonoClassField *field)
2567 MonoClass *klass = field->parent;
2570 int fcount = mono_class_get_field_count (klass);
2571 for (i = 0; i < fcount; ++i) {
2572 if (field == &klass->fields [i])
2573 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2576 g_assert_not_reached ();
2581 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2585 //printf ("ENCODE: %d 0x%x.\n", value, value);
2588 * Same encoding as the one used in the metadata, extended to handle values
2589 * greater than 0x1fffffff.
2591 if ((value >= 0) && (value <= 127))
2593 else if ((value >= 0) && (value <= 16383)) {
2594 p [0] = 0x80 | (value >> 8);
2595 p [1] = value & 0xff;
2597 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2598 p [0] = (value >> 24) | 0xc0;
2599 p [1] = (value >> 16) & 0xff;
2600 p [2] = (value >> 8) & 0xff;
2601 p [3] = value & 0xff;
2606 p [1] = (value >> 24) & 0xff;
2607 p [2] = (value >> 16) & 0xff;
2608 p [3] = (value >> 8) & 0xff;
2609 p [4] = value & 0xff;
2617 stream_init (MonoDynamicStream *sh)
2620 sh->alloc_size = 4096;
2621 sh->data = (char *)g_malloc (4096);
2623 /* So offsets are > 0 */
2629 make_room_in_stream (MonoDynamicStream *stream, int size)
2631 if (size <= stream->alloc_size)
2634 while (stream->alloc_size <= size) {
2635 if (stream->alloc_size < 4096)
2636 stream->alloc_size = 4096;
2638 stream->alloc_size *= 2;
2641 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2645 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2649 make_room_in_stream (stream, stream->index + len);
2650 memcpy (stream->data + stream->index, data, len);
2651 idx = stream->index;
2652 stream->index += len;
2659 * Add data to the binary blob inside the aot image. Returns the offset inside the
2660 * blob where the data was stored.
2663 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2665 g_assert (!acfg->blob_closed);
2667 if (acfg->blob.alloc_size == 0)
2668 stream_init (&acfg->blob);
2670 return add_stream_data (&acfg->blob, (char*)data, data_len);
2674 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2679 if (acfg->blob.alloc_size == 0)
2680 stream_init (&acfg->blob);
2682 count = acfg->blob.index % align;
2684 /* we assume the stream data will be aligned */
2686 add_stream_data (&acfg->blob, buf, 4 - count);
2688 return add_stream_data (&acfg->blob, (char*)data, data_len);
2691 /* Emit a table of data into the aot image */
2693 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2695 if (acfg->data_outfile) {
2696 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2697 fwrite (data,1, size, acfg->data_outfile);
2698 acfg->datafile_offset += size;
2699 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2700 int align = 8 - size % 8;
2701 acfg->datafile_offset += align;
2702 guint8 align_buf [16];
2703 memset (&align_buf, 0, sizeof (align_buf));
2704 fwrite (align_buf, align, 1, acfg->data_outfile);
2705 } else if (acfg->llvm) {
2706 mono_llvm_emit_aot_data (symbol, data, size);
2708 emit_section_change (acfg, RODATA_SECT, 0);
2709 emit_alignment (acfg, 8);
2710 emit_label (acfg, symbol);
2711 emit_bytes (acfg, data, size);
2716 * emit_offset_table:
2718 * Emit a table of increasing offsets in a compact form using differential encoding.
2719 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2720 * group size, the more compact the table becomes, but the slower it becomes to compute
2721 * a given entry. Returns the size of the table.
2724 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2726 gint32 current_offset;
2727 int i, buf_size, ngroups, index_entry_size;
2729 guint8 *data_p, *data_buf;
2730 guint32 *index_offsets;
2732 ngroups = (noffsets + (group_size - 1)) / group_size;
2734 index_offsets = g_new0 (guint32, ngroups);
2736 buf_size = noffsets * 4;
2737 p = buf = (guint8 *)g_malloc0 (buf_size);
2740 for (i = 0; i < noffsets; ++i) {
2741 //printf ("D: %d -> %d\n", i, offsets [i]);
2742 if ((i % group_size) == 0) {
2743 index_offsets [i / group_size] = p - buf;
2744 /* Emit the full value for these entries */
2745 encode_value (offsets [i], p, &p);
2747 /* The offsets are allowed to be non-increasing */
2748 //g_assert (offsets [i] >= current_offset);
2749 encode_value (offsets [i] - current_offset, p, &p);
2751 current_offset = offsets [i];
2756 if (ngroups && index_offsets [ngroups - 1] < 65000)
2757 index_entry_size = 2;
2759 index_entry_size = 4;
2761 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2762 p = buf = (guint8 *)g_malloc0 (buf_size);
2764 /* Emit the header */
2765 encode_int (noffsets, p, &p);
2766 encode_int (group_size, p, &p);
2767 encode_int (ngroups, p, &p);
2768 encode_int (index_entry_size, p, &p);
2770 /* Emit the index */
2771 for (i = 0; i < ngroups; ++i) {
2772 if (index_entry_size == 2)
2773 encode_int16 (index_offsets [i], p, &p);
2775 encode_int (index_offsets [i], p, &p);
2778 memcpy (p, data_buf, data_p - data_buf);
2779 p += data_p - data_buf;
2781 g_assert (p - buf <= buf_size);
2783 emit_aot_data (acfg, table, symbol, buf, p - buf);
2788 return (int)(p - buf);
2792 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2796 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2800 index = g_hash_table_size (cfg->image_hash);
2801 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2802 g_ptr_array_add (cfg->image_table, image);
2808 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2811 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2813 /* FIXME: Search referenced images as well */
2814 if (!acfg->typespec_classes) {
2815 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2816 for (i = 0; i < len; i++) {
2818 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2819 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2820 if (!is_ok (&error)) {
2821 mono_error_cleanup (&error);
2824 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2827 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2831 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2834 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2837 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2840 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2843 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2848 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2852 if (mono_class_is_ginst (klass)) {
2854 g_assert (klass->type_token);
2856 /* Find a typespec for a class if possible */
2857 token = find_typespec_for_class (acfg, klass);
2859 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2860 encode_value (token, p, &p);
2862 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2863 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2864 static int count = 0;
2867 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2868 encode_klass_ref (acfg, gclass, p, &p);
2869 encode_ginst (acfg, inst, p, &p);
2873 } else if (klass->type_token) {
2874 int iindex = get_image_index (acfg, klass->image);
2876 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2878 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2879 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2881 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2882 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2883 encode_value (get_image_index (acfg, klass->image), p, &p);
2885 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2886 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2887 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2889 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2891 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2892 if (par->gshared_constraint) {
2893 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2894 encode_type (acfg, par->gshared_constraint, p, &p);
2895 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2897 encode_value (klass->byval_arg.type, p, &p);
2898 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2900 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2902 if (!container->is_anonymous) {
2903 encode_value (container->is_method, p, &p);
2904 if (container->is_method)
2905 encode_method_ref (acfg, container->owner.method, p, &p);
2907 encode_klass_ref (acfg, container->owner.klass, p, &p);
2910 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2911 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2912 encode_type (acfg, &klass->byval_arg, p, &p);
2915 g_assert (klass->rank > 0);
2916 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2917 encode_value (klass->rank, p, &p);
2918 encode_klass_ref (acfg, klass->element_class, p, &p);
2926 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2927 * standard metadata encoding.
2930 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2932 gboolean shared = FALSE;
2935 * The encoding of generic instances is large so emit them only once.
2937 if (mono_class_is_ginst (klass)) {
2939 g_assert (klass->type_token);
2941 /* Find a typespec for a class if possible */
2942 token = find_typespec_for_class (acfg, klass);
2945 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2950 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2954 buf2 = (guint8 *)g_malloc (1024);
2957 encode_klass_ref_inner (acfg, klass, p, &p);
2958 g_assert (p - buf2 < 1024);
2960 offset = add_to_blob (acfg, buf2, p - buf2);
2963 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2969 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2970 encode_value (offset, p, &p);
2975 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2979 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2981 guint32 token = mono_get_field_token (field);
2984 encode_klass_ref (cfg, field->parent, p, &p);
2985 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2986 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2991 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2996 encode_value (inst->type_argc, p, &p);
2997 for (i = 0; i < inst->type_argc; ++i)
2998 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3003 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3006 MonoGenericInst *inst;
3008 inst = context->class_inst;
3010 g_assert (inst->type_argc);
3011 encode_ginst (acfg, inst, p, &p);
3013 encode_value (0, p, &p);
3015 inst = context->method_inst;
3017 g_assert (inst->type_argc);
3018 encode_ginst (acfg, inst, p, &p);
3020 encode_value (0, p, &p);
3026 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3030 g_assert (t->num_mods == 0);
3031 /* t->attrs can be ignored */
3032 //g_assert (t->attrs == 0);
3035 *p = MONO_TYPE_PINNED;
3039 *p = MONO_TYPE_BYREF;
3047 case MONO_TYPE_VOID:
3048 case MONO_TYPE_BOOLEAN:
3049 case MONO_TYPE_CHAR:
3062 case MONO_TYPE_STRING:
3063 case MONO_TYPE_OBJECT:
3064 case MONO_TYPE_TYPEDBYREF:
3066 case MONO_TYPE_VALUETYPE:
3067 case MONO_TYPE_CLASS:
3068 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3070 case MONO_TYPE_SZARRAY:
3071 encode_klass_ref (acfg, t->data.klass, p, &p);
3074 encode_type (acfg, t->data.type, p, &p);
3076 case MONO_TYPE_GENERICINST: {
3077 MonoClass *gclass = t->data.generic_class->container_class;
3078 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3080 encode_klass_ref (acfg, gclass, p, &p);
3081 encode_ginst (acfg, inst, p, &p);
3084 case MONO_TYPE_ARRAY: {
3085 MonoArrayType *array = t->data.array;
3088 encode_klass_ref (acfg, array->eklass, p, &p);
3089 encode_value (array->rank, p, &p);
3090 encode_value (array->numsizes, p, &p);
3091 for (i = 0; i < array->numsizes; ++i)
3092 encode_value (array->sizes [i], p, &p);
3093 encode_value (array->numlobounds, p, &p);
3094 for (i = 0; i < array->numlobounds; ++i)
3095 encode_value (array->lobounds [i], p, &p);
3099 case MONO_TYPE_MVAR:
3100 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3103 g_assert_not_reached ();
3110 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3116 /* Similar to the metadata encoding */
3117 if (sig->generic_param_count)
3121 if (sig->explicit_this)
3123 flags |= (sig->call_convention & 0x0F);
3127 if (sig->generic_param_count)
3128 encode_value (sig->generic_param_count, p, &p);
3129 encode_value (sig->param_count, p, &p);
3131 encode_type (acfg, sig->ret, p, &p);
3132 for (i = 0; i < sig->param_count; ++i) {
3133 if (sig->sentinelpos == i) {
3134 *p = MONO_TYPE_SENTINEL;
3137 encode_type (acfg, sig->params [i], p, &p);
3143 #define MAX_IMAGE_INDEX 250
3146 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3148 guint32 image_index = get_image_index (acfg, method->klass->image);
3149 guint32 token = method->token;
3150 MonoJumpInfoToken *ji;
3154 * The encoding for most methods is as follows:
3155 * - image index encoded as a leb128
3156 * - token index encoded as a leb128
3157 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3158 * types of method encodings.
3161 /* Mark methods which can't use aot trampolines because they need the further
3162 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3164 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3165 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3166 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3168 if (method->wrapper_type) {
3169 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3171 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3173 encode_value (method->wrapper_type, p, &p);
3175 switch (method->wrapper_type) {
3176 case MONO_WRAPPER_REMOTING_INVOKE:
3177 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3178 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3181 m = mono_marshal_method_from_wrapper (method);
3183 encode_method_ref (acfg, m, p, &p);
3186 case MONO_WRAPPER_PROXY_ISINST:
3187 case MONO_WRAPPER_LDFLD:
3188 case MONO_WRAPPER_LDFLDA:
3189 case MONO_WRAPPER_STFLD: {
3191 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3194 case MONO_WRAPPER_ALLOC: {
3195 /* The GC name is saved once in MonoAotFileInfo */
3196 g_assert (info->d.alloc.alloc_type != -1);
3197 encode_value (info->d.alloc.alloc_type, p, &p);
3200 case MONO_WRAPPER_WRITE_BARRIER: {
3204 case MONO_WRAPPER_STELEMREF: {
3206 encode_value (info->subtype, p, &p);
3207 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3208 encode_value (info->d.virtual_stelemref.kind, p, &p);
3211 case MONO_WRAPPER_UNKNOWN: {
3213 encode_value (info->subtype, p, &p);
3214 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3215 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3216 encode_klass_ref (acfg, method->klass, p, &p);
3217 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3218 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3219 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3220 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3221 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3222 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3223 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3224 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3227 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3229 encode_value (info->subtype, p, &p);
3230 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3231 strcpy ((char*)p, method->name);
3232 p += strlen (method->name) + 1;
3233 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3234 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3236 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3237 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3241 case MONO_WRAPPER_SYNCHRONIZED: {
3244 m = mono_marshal_method_from_wrapper (method);
3246 g_assert (m != method);
3247 encode_method_ref (acfg, m, p, &p);
3250 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3252 encode_value (info->subtype, p, &p);
3254 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3255 encode_value (info->d.element_addr.rank, p, &p);
3256 encode_value (info->d.element_addr.elem_size, p, &p);
3257 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3258 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3260 g_assert_not_reached ();
3264 case MONO_WRAPPER_CASTCLASS: {
3266 encode_value (info->subtype, p, &p);
3269 case MONO_WRAPPER_RUNTIME_INVOKE: {
3271 encode_value (info->subtype, p, &p);
3272 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3273 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3274 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3275 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3278 case MONO_WRAPPER_DELEGATE_INVOKE:
3279 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3280 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3281 if (method->is_inflated) {
3282 /* These wrappers are identified by their class */
3283 encode_value (1, p, &p);
3284 encode_klass_ref (acfg, method->klass, p, &p);
3286 MonoMethodSignature *sig = mono_method_signature (method);
3287 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3289 encode_value (0, p, &p);
3290 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3291 encode_value (info ? info->subtype : 0, p, &p);
3292 encode_signature (acfg, sig, p, &p);
3296 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3298 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3299 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3303 g_assert_not_reached ();
3305 } else if (mono_method_signature (method)->is_inflated) {
3307 * This is a generic method, find the original token which referenced it and
3309 * Obtain the token from information recorded by the JIT.
3311 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3313 image_index = get_image_index (acfg, ji->image);
3314 g_assert (image_index < MAX_IMAGE_INDEX);
3317 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3318 encode_value (image_index, p, &p);
3319 encode_value (token, p, &p);
3321 MonoMethod *declaring;
3322 MonoGenericContext *context = mono_method_get_context (method);
3324 g_assert (method->is_inflated);
3325 declaring = ((MonoMethodInflated*)method)->declaring;
3328 * This might be a non-generic method of a generic instance, which
3329 * doesn't have a token since the reference is generated by the JIT
3330 * like Nullable:Box/Unbox, or by generic sharing.
3332 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3333 /* Encode the klass */
3334 encode_klass_ref (acfg, method->klass, p, &p);
3335 /* Encode the method */
3336 image_index = get_image_index (acfg, method->klass->image);
3337 g_assert (image_index < MAX_IMAGE_INDEX);
3338 g_assert (declaring->token);
3339 token = declaring->token;
3340 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3341 encode_value (image_index, p, &p);
3342 encode_value (token, p, &p);
3343 encode_generic_context (acfg, context, p, &p);
3345 } else if (token == 0) {
3346 /* This might be a method of a constructed type like int[,].Set */
3347 /* Obtain the token from information recorded by the JIT */
3348 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3350 image_index = get_image_index (acfg, ji->image);
3351 g_assert (image_index < MAX_IMAGE_INDEX);
3354 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3355 encode_value (image_index, p, &p);
3356 encode_value (token, p, &p);
3359 g_assert (method->klass->rank);
3361 /* Encode directly */
3362 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3363 encode_klass_ref (acfg, method->klass, p, &p);
3364 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3365 encode_value (0, p, &p);
3366 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3367 encode_value (1, p, &p);
3368 else if (!strcmp (method->name, "Get"))
3369 encode_value (2, p, &p);
3370 else if (!strcmp (method->name, "Address"))
3371 encode_value (3, p, &p);
3372 else if (!strcmp (method->name, "Set"))
3373 encode_value (4, p, &p);
3375 g_assert_not_reached ();
3378 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3380 if (image_index >= MONO_AOT_METHODREF_MIN) {
3381 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3382 encode_value (image_index, p, &p);
3383 encode_value (mono_metadata_token_index (token), p, &p);
3385 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3392 compare_patches (gconstpointer a, gconstpointer b)
3396 i = (*(MonoJumpInfo**)a)->ip.i;
3397 j = (*(MonoJumpInfo**)b)->ip.i;
3408 static G_GNUC_UNUSED char*
3409 patch_to_string (MonoJumpInfo *patch_info)
3413 str = g_string_new ("");
3415 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3417 switch (patch_info->type) {
3418 case MONO_PATCH_INFO_VTABLE:
3419 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3424 g_string_append_printf (str, ")");
3425 return g_string_free (str, FALSE);
3431 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3434 static inline gboolean
3435 is_plt_patch (MonoJumpInfo *patch_info)
3437 switch (patch_info->type) {
3438 case MONO_PATCH_INFO_METHOD:
3439 case MONO_PATCH_INFO_INTERNAL_METHOD:
3440 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3441 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3442 case MONO_PATCH_INFO_RGCTX_FETCH:
3452 * Return the symbol identifying the plt entry PLT_OFFSET.
3455 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3459 * The Apple linker reorganizes object files, so it doesn't like branches to local
3460 * labels, since those have no relocations.
3462 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3464 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3471 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3473 static MonoPltEntry*
3474 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3477 gboolean synchronized = FALSE;
3478 static int synchronized_symbol_idx;
3480 if (!is_plt_patch (patch_info))
3483 if (!acfg->patch_to_plt_entry [patch_info->type])
3484 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3485 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3487 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3489 * Allocate a separate PLT slot for each such patch, since some plt
3490 * entries will refer to the method itself, and some will refer to the
3494 synchronized = TRUE;
3498 MonoJumpInfo *new_ji;
3500 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3502 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3503 res->plt_offset = acfg->plt_offset;
3505 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3506 if (acfg->aot_opts.write_symbols)
3507 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3509 /* Avoid duplicate symbols because we don't cache */
3510 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3512 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3513 synchronized_symbol_idx ++;
3516 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3518 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3520 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3522 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3524 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3525 //mono_print_ji (patch_info); printf ("\n");
3526 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3528 acfg->plt_offset ++;
3537 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3538 * JI could be found if it exists, otherwise allocates a new one.
3541 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3544 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3546 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3548 return got_offset - 1;
3551 got_offset = acfg->llvm_got_offset;
3552 acfg->llvm_got_offset ++;
3554 got_offset = acfg->got_offset;
3555 acfg->got_offset ++;
3558 acfg->stats.got_slots ++;
3559 acfg->stats.got_slot_types [ji->type] ++;
3561 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3562 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3563 g_ptr_array_add (info->got_patches, ji);
3568 /* Add a method to the list of methods which need to be emitted */
3570 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3573 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3574 g_ptr_array_add (acfg->methods, method);
3575 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3576 acfg->nmethods = acfg->methods->len + 1;
3579 if (method->wrapper_type || extra)
3580 g_ptr_array_add (acfg->extra_methods, method);
3584 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3586 /* One instantiation with valuetypes is generated for each async method */
3587 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3594 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3596 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3604 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3608 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3612 index = acfg->method_index;
3613 add_method_with_index (acfg, method, index, extra);
3615 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3617 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3619 acfg->method_index ++;
3625 add_method (MonoAotCompile *acfg, MonoMethod *method)
3627 return add_method_full (acfg, method, FALSE, 0);
3631 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3633 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3634 method = mini_get_shared_method (method);
3635 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3636 /* Use the gsharedvt version */
3637 method = mini_get_shared_method_full (method, TRUE, TRUE);
3639 if (acfg->aot_opts.log_generics)
3640 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3642 add_method_full (acfg, method, TRUE, depth);
3646 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3648 add_extra_method_with_depth (acfg, method, 0);
3652 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3654 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3655 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3656 MonoMethod *wrapper;
3662 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3663 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3666 add_method (acfg, wrapper);
3670 get_runtime_invoke_sig (MonoMethodSignature *sig)
3672 MonoMethodBuilder *mb;
3675 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3676 m = mono_mb_create_method (mb, sig, 16);
3677 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3683 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3685 return mono_marshal_get_runtime_invoke (method, virtual_);
3689 can_marshal_struct (MonoClass *klass)
3691 MonoClassField *field;
3692 gboolean can_marshal = TRUE;
3693 gpointer iter = NULL;
3694 MonoMarshalType *info;
3697 if (mono_class_is_auto_layout (klass))
3700 info = mono_marshal_load_type_info (klass);
3702 /* Only allow a few field types to avoid asserts in the marshalling code */
3703 while ((field = mono_class_get_fields (klass, &iter))) {
3704 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3707 switch (field->type->type) {
3712 case MONO_TYPE_BOOLEAN:
3715 case MONO_TYPE_CHAR:
3723 case MONO_TYPE_STRING:
3725 case MONO_TYPE_VALUETYPE:
3726 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3727 can_marshal = FALSE;
3729 case MONO_TYPE_SZARRAY: {
3730 gboolean has_mspec = FALSE;
3733 for (i = 0; i < info->num_fields; ++i) {
3734 if (info->fields [i].field == field && info->fields [i].mspec)
3739 can_marshal = FALSE;
3743 can_marshal = FALSE;
3749 /* Its hard to compute whenever these can be marshalled or not */
3750 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3757 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3759 /* Create a vtype instantiation */
3760 MonoGenericContext shared_context;
3762 MonoGenericInst *inst;
3763 MonoGenericContainer *container;
3764 MonoClass **constraints;
3767 memset (ctx, 0, sizeof (MonoGenericContext));
3769 if (mono_class_is_gtd (method->klass)) {
3770 shared_context = mono_class_get_generic_container (method->klass)->context;
3771 inst = shared_context.class_inst;
3773 args = g_new0 (MonoType*, inst->type_argc);
3774 for (i = 0; i < inst->type_argc; ++i) {
3775 args [i] = &mono_defaults.int_class->byval_arg;
3777 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3779 if (method->is_generic) {
3780 container = mono_method_get_generic_container (method);
3781 shared_context = container->context;
3782 inst = shared_context.method_inst;
3784 args = g_new0 (MonoType*, inst->type_argc);
3785 for (i = 0; i < container->type_argc; ++i) {
3786 MonoGenericParamInfo *info = &container->type_params [i].info;
3787 gboolean ref_only = FALSE;
3789 if (info && info->constraints) {
3790 constraints = info->constraints;
3792 while (*constraints) {
3793 MonoClass *cklass = *constraints;
3794 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3795 /* Inflaring the method with our vtype would not be valid */
3802 args [i] = &mono_defaults.object_class->byval_arg;
3804 args [i] = &mono_defaults.int_class->byval_arg;
3806 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3811 add_wrappers (MonoAotCompile *acfg)
3813 MonoMethod *method, *m;
3815 MonoMethodSignature *sig, *csig;
3819 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3820 * so there is only one wrapper of a given type, or inlining their contents into their
3823 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3826 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3827 gboolean skip = FALSE;
3829 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3830 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3832 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3833 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3834 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3837 /* Skip methods which can not be handled by get_runtime_invoke () */
3838 sig = mono_method_signature (method);
3841 if ((sig->ret->type == MONO_TYPE_PTR) ||
3842 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3844 if (mono_class_is_open_constructed_type (sig->ret))
3847 for (j = 0; j < sig->param_count; j++) {
3848 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3850 if (mono_class_is_open_constructed_type (sig->params [j]))
3854 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3855 if (!mono_class_is_contextbound (method->klass)) {
3856 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3857 gboolean has_nullable = FALSE;
3859 for (j = 0; j < sig->param_count; j++) {
3860 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3861 has_nullable = TRUE;
3864 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3865 /* Supported by the dynamic runtime-invoke wrapper */
3869 mono_arch_dyn_call_free (info);
3873 if (acfg->aot_opts.llvm_only)
3874 /* Supported by the gsharedvt based runtime-invoke wrapper */
3878 //printf ("%s\n", mono_method_full_name (method, TRUE));
3879 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3883 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3886 /* Runtime invoke wrappers */
3888 /* void runtime-invoke () [.cctor] */
3889 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3890 csig->ret = &mono_defaults.void_class->byval_arg;
3891 add_method (acfg, get_runtime_invoke_sig (csig));
3893 /* void runtime-invoke () [Finalize] */
3894 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3896 csig->ret = &mono_defaults.void_class->byval_arg;
3897 add_method (acfg, get_runtime_invoke_sig (csig));
3899 /* void runtime-invoke (string) [exception ctor] */
3900 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3902 csig->ret = &mono_defaults.void_class->byval_arg;
3903 csig->params [0] = &mono_defaults.string_class->byval_arg;
3904 add_method (acfg, get_runtime_invoke_sig (csig));
3906 /* void runtime-invoke (string, string) [exception ctor] */
3907 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3909 csig->ret = &mono_defaults.void_class->byval_arg;
3910 csig->params [0] = &mono_defaults.string_class->byval_arg;
3911 csig->params [1] = &mono_defaults.string_class->byval_arg;
3912 add_method (acfg, get_runtime_invoke_sig (csig));
3914 /* string runtime-invoke () [Exception.ToString ()] */
3915 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3917 csig->ret = &mono_defaults.string_class->byval_arg;
3918 add_method (acfg, get_runtime_invoke_sig (csig));
3920 /* void runtime-invoke (string, Exception) [exception ctor] */
3921 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3923 csig->ret = &mono_defaults.void_class->byval_arg;
3924 csig->params [0] = &mono_defaults.string_class->byval_arg;
3925 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3926 add_method (acfg, get_runtime_invoke_sig (csig));
3928 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3929 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3931 csig->ret = &(mono_class_load_from_name (
3932 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3933 csig->params [0] = &mono_defaults.string_class->byval_arg;
3934 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3935 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3936 add_method (acfg, get_runtime_invoke_sig (csig));
3938 /* runtime-invoke used by finalizers */
3939 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3941 /* This is used by mono_runtime_capture_context () */
3942 method = mono_get_context_capture_method ();
3944 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3946 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3947 if (!acfg->aot_opts.llvm_only)
3948 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3951 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3952 if (acfg->aot_opts.llvm_only) {
3955 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3956 for (variants = 0; variants < 4; ++variants) {
3957 for (i = 0; i < 16; ++i) {
3958 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3959 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3967 add_method (acfg, mono_marshal_get_stelemref ());
3969 /* Managed Allocators */
3970 nallocators = mono_gc_get_managed_allocator_types ();
3971 for (i = 0; i < nallocators; ++i) {
3972 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3973 add_method (acfg, m);
3974 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3975 add_method (acfg, m);
3978 /* write barriers */
3979 if (mono_gc_is_moving ()) {
3980 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3981 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3984 /* Stelemref wrappers */
3986 MonoMethod **wrappers;
3989 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3990 for (i = 0; i < nwrappers; ++i)
3991 add_method (acfg, wrappers [i]);
3995 /* castclass_with_check wrapper */
3996 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3997 /* isinst_with_check wrapper */
3998 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4000 /* JIT icall wrappers */
4001 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4002 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4006 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4007 * we use the original method instead at runtime.
4008 * Since full-aot doesn't support remoting, this is not a problem.
4011 /* remoting-invoke wrappers */
4012 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4014 MonoMethodSignature *sig;
4016 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4017 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4018 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4020 sig = mono_method_signature (method);
4022 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4023 m = mono_marshal_get_remoting_invoke_with_check (method);
4025 add_method (acfg, m);
4030 /* delegate-invoke wrappers */
4031 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4034 MonoCustomAttrInfo *cattr;
4036 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4037 klass = mono_class_get_checked (acfg->image, token, &error);
4040 mono_error_cleanup (&error);
4044 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4047 if (!mono_class_is_gtd (klass)) {
4048 method = mono_get_delegate_invoke (klass);
4050 m = mono_marshal_get_delegate_invoke (method, NULL);
4052 add_method (acfg, m);
4054 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4056 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4058 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4060 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4062 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4063 if (!is_ok (&error)) {
4064 mono_error_cleanup (&error);
4071 for (j = 0; j < cattr->num_attrs; ++j)
4072 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4074 if (j < cattr->num_attrs) {
4076 MonoMethod *wrapper;
4077 MonoMethod *del_invoke;
4079 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4080 invoke = mono_get_delegate_invoke (klass);
4081 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4082 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4083 add_method (acfg, wrapper);
4084 add_method (acfg, del_invoke);
4087 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4089 MonoGenericContext ctx;
4090 MonoMethod *inst, *gshared;
4093 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4096 method = mono_get_delegate_invoke (klass);
4097 create_gsharedvt_inst (acfg, method, &ctx);
4099 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4100 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4102 m = mono_marshal_get_delegate_invoke (inst, NULL);
4103 g_assert (m->is_inflated);
4105 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4106 add_extra_method (acfg, gshared);
4109 method = mono_get_delegate_begin_invoke (klass);
4111 create_gsharedvt_inst (acfg, method, &ctx);
4113 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4114 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4116 m = mono_marshal_get_delegate_begin_invoke (inst);
4117 g_assert (m->is_inflated);
4119 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4120 add_extra_method (acfg, gshared);
4124 method = mono_get_delegate_end_invoke (klass);
4126 create_gsharedvt_inst (acfg, method, &ctx);
4128 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4129 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4131 m = mono_marshal_get_delegate_end_invoke (inst);
4132 g_assert (m->is_inflated);
4134 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4135 add_extra_method (acfg, gshared);
4140 /* array access wrappers */
4141 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4145 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4146 klass = mono_class_get_checked (acfg->image, token, &error);
4149 mono_error_cleanup (&error);
4153 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4154 MonoMethod *m, *wrapper;
4156 /* Add runtime-invoke wrappers too */
4158 m = mono_class_get_method_from_name (klass, "Get", -1);
4160 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4161 add_extra_method (acfg, wrapper);
4162 if (!acfg->aot_opts.llvm_only)
4163 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4165 m = mono_class_get_method_from_name (klass, "Set", -1);
4167 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4168 add_extra_method (acfg, wrapper);
4169 if (!acfg->aot_opts.llvm_only)
4170 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4174 /* Synchronized wrappers */
4175 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4177 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4178 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4179 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4181 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4182 if (method->is_generic) {
4184 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4186 MonoGenericContext ctx;
4187 MonoMethod *inst, *gshared, *m;
4190 * Create a generic wrapper for a generic instance, and AOT that.
4192 create_gsharedvt_inst (acfg, method, &ctx);
4193 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4194 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4195 m = mono_marshal_get_synchronized_wrapper (inst);
4196 g_assert (m->is_inflated);
4197 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4198 add_method (acfg, gshared);
4200 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4205 /* pinvoke wrappers */
4206 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4209 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4211 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4212 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4214 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4215 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4216 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4219 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4220 if (acfg->aot_opts.llvm_only) {
4221 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4222 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4227 /* native-to-managed wrappers */
4228 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4231 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4232 MonoCustomAttrInfo *cattr;
4235 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4236 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4239 * Only generate native-to-managed wrappers for methods which have an
4240 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4241 * name to avoid defining a new assembly to contain it.
4243 cattr = mono_custom_attrs_from_method_checked (method, &error);
4244 if (!is_ok (&error)) {
4245 char *name = mono_method_get_full_name (method);
4246 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4251 for (j = 0; j < cattr->num_attrs; ++j)
4252 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4254 if (j < cattr->num_attrs) {
4255 MonoCustomAttrEntry *e = &cattr->attrs [j];
4256 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4257 const char *p = (const char*)e->data;
4259 int slen, num_named, named_type;
4263 char *export_name = NULL;
4264 MonoMethod *wrapper;
4266 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4267 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4268 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4269 mono_method_full_name (method, TRUE));
4273 g_assert (sig->param_count == 1);
4274 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4277 * Decode the cattr manually since we can't create objects
4278 * during aot compilation.
4284 /* From load_cattr_value () in reflection.c */
4285 slen = mono_metadata_decode_value (p, &p);
4286 n = (char *)g_memdup (p, slen + 1);
4288 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4290 mono_error_assert_ok (&error);
4293 klass = mono_class_from_mono_type (t);
4294 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4298 num_named = read16 (p);
4301 g_assert (num_named < 2);
4302 if (num_named == 1) {
4306 /* parse ExportSymbol attribute */
4308 named_type = *named;
4310 /* data_type = *named; */
4313 name_len = mono_metadata_decode_blob_size (named, &named);
4314 name = (char *)g_malloc (name_len + 1);
4315 memcpy (name, named, name_len);
4316 name [name_len] = 0;
4319 g_assert (named_type == 0x54);
4320 g_assert (!strcmp (name, "ExportSymbol"));
4322 /* load_cattr_value (), string case */
4323 g_assert (*named != (char)0xff);
4324 slen = mono_metadata_decode_value (named, &named);
4325 export_name = (char *)g_malloc (slen + 1);
4326 memcpy (export_name, named, slen);
4327 export_name [slen] = 0;
4331 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4332 add_method (acfg, wrapper);
4334 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4339 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4340 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4341 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4345 /* StructureToPtr/PtrToStructure wrappers */
4346 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4350 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4351 klass = mono_class_get_checked (acfg->image, token, &error);
4354 mono_error_cleanup (&error);
4358 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4359 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4360 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4361 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4367 has_type_vars (MonoClass *klass)
4369 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4372 return has_type_vars (klass->element_class);
4373 if (mono_class_is_ginst (klass)) {
4374 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4375 if (context->class_inst) {
4378 for (i = 0; i < context->class_inst->type_argc; ++i)
4379 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4383 if (mono_class_is_gtd (klass))
4389 is_vt_inst (MonoGenericInst *inst)
4393 for (i = 0; i < inst->type_argc; ++i) {
4394 MonoType *t = inst->type_argv [i];
4395 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4402 method_has_type_vars (MonoMethod *method)
4404 if (has_type_vars (method->klass))
4407 if (method->is_inflated) {
4408 MonoGenericContext *context = mono_method_get_context (method);
4409 if (context->method_inst) {
4412 for (i = 0; i < context->method_inst->type_argc; ++i)
4413 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4421 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4423 return opts->mode == MONO_AOT_MODE_FULL;
4427 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4429 return opts->mode == MONO_AOT_MODE_HYBRID;
4432 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4435 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4437 /* This might lead to a huge code blowup so only do it if neccesary */
4438 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4441 add_generic_class_with_depth (acfg, klass, 0, ref);
4445 check_type_depth (MonoType *t, int depth)
4453 case MONO_TYPE_GENERICINST: {
4454 MonoGenericClass *gklass = t->data.generic_class;
4455 MonoGenericInst *ginst = gklass->context.class_inst;
4458 for (i = 0; i < ginst->type_argc; ++i) {
4459 if (check_type_depth (ginst->type_argv [i], depth + 1))
4473 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4476 * add_generic_class:
4478 * Add all methods of a generic class.
4481 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4484 MonoClassField *field;
4486 gboolean use_gsharedvt = FALSE;
4488 if (!acfg->ginst_hash)
4489 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4491 mono_class_init (klass);
4493 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4496 if (has_type_vars (klass))
4499 if (!mono_class_is_ginst (klass) && !klass->rank)
4502 if (mono_class_has_failure (klass))
4505 if (!acfg->ginst_hash)
4506 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4508 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4511 if (check_type_depth (&klass->byval_arg, 0))
4514 if (acfg->aot_opts.log_generics)
4515 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4517 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4520 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4521 * Enable this only for some classes since gsharedvt might not support all methods.
4523 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) &&
4524 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4525 use_gsharedvt = TRUE;
4528 while ((method = mono_class_get_methods (klass, &iter))) {
4529 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4531 * This is partial sharing, and we can't handle it yet
4536 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4538 add_types_from_method_header (acfg, method);
4542 if (method->is_generic)
4547 * FIXME: Instances which are referenced by these methods are not added,
4548 * for example Array.Resize<int> for List<int>.Add ().
4550 add_extra_method_with_depth (acfg, method, depth + 1);
4554 while ((field = mono_class_get_fields (klass, &iter))) {
4555 if (field->type->type == MONO_TYPE_GENERICINST)
4556 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4559 if (klass->delegate) {
4560 method = mono_get_delegate_invoke (klass);
4562 method = mono_marshal_get_delegate_invoke (method, NULL);
4564 if (acfg->aot_opts.log_generics)
4565 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4567 add_method (acfg, method);
4570 /* Add superclasses */
4572 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4575 * For ICollection<T>, add instances of the helper methods
4576 * in Array, since a T[] could be cast to ICollection<T>.
4578 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4579 (!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"))) {
4580 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4581 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4585 if (!strcmp (klass->name, "IEnumerator`1"))
4586 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4588 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4590 /* Add the T[]/InternalEnumerator class */
4591 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4596 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4597 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4601 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4602 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4603 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4607 while ((method = mono_class_get_methods (array_class, &iter))) {
4608 if (strstr (method->name, name_prefix)) {
4609 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4611 add_extra_method_with_depth (acfg, m, depth);
4615 g_free (name_prefix);
4618 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4619 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4621 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4622 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4623 MonoGenericContext ctx;
4624 MonoType *args [16];
4626 memset (&ctx, 0, sizeof (ctx));
4628 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4630 args [0] = &tclass->byval_arg;
4631 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4633 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4634 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4636 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4637 MonoClass *gcomparer_inst;
4638 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4639 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4640 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4642 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4646 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4647 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4649 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4650 MonoClass *iface, *gcomparer, *iface_inst;
4651 MonoGenericContext ctx;
4652 MonoType *args [16];
4654 memset (&ctx, 0, sizeof (ctx));
4656 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4658 args [0] = &tclass->byval_arg;
4659 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4661 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4662 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4664 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4665 MonoClass *gcomparer_inst;
4668 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4669 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4670 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4671 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4675 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4676 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4677 MonoClass *enum_comparer;
4678 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4679 MonoGenericContext ctx;
4680 MonoType *args [16];
4682 if (mono_class_is_enum (tclass)) {
4683 MonoClass *enum_comparer_inst;
4686 memset (&ctx, 0, sizeof (ctx));
4687 args [0] = &tclass->byval_arg;
4688 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4690 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4691 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4692 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4693 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4697 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4698 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4699 MonoClass *comparer;
4700 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4701 MonoGenericContext ctx;
4702 MonoType *args [16];
4704 if (mono_class_is_enum (tclass)) {
4705 MonoClass *comparer_inst;
4708 memset (&ctx, 0, sizeof (ctx));
4709 args [0] = &tclass->byval_arg;
4710 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4712 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4713 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4714 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4715 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4721 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4724 MonoGenericContext ctx;
4725 MonoType *args [16];
4727 if (acfg->aot_opts.no_instances)
4730 memset (&ctx, 0, sizeof (ctx));
4732 for (i = 0; i < ninsts; ++i) {
4734 MonoClass *generic_inst;
4735 args [0] = insts [i];
4736 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4737 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4738 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4739 add_generic_class (acfg, generic_inst, force, "");
4744 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4747 MonoMethodHeader *header;
4748 MonoMethodSignature *sig;
4751 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4753 sig = mono_method_signature (method);
4756 for (j = 0; j < sig->param_count; ++j)
4757 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4758 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4761 header = mono_method_get_header_checked (method, &error);
4764 for (j = 0; j < header->num_locals; ++j)
4765 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4766 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4767 mono_metadata_free_mh (header);
4769 mono_error_cleanup (&error); /* FIXME report the error */
4775 * add_generic_instances:
4777 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4780 add_generic_instances (MonoAotCompile *acfg)
4785 MonoGenericContext *context;
4787 if (acfg->aot_opts.no_instances)
4790 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4792 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4793 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4796 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4797 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4798 mono_error_cleanup (&error);
4802 if (method->klass->image != acfg->image)
4805 context = mono_method_get_context (method);
4807 if (context && ((context->class_inst && context->class_inst->is_open)))
4811 * For open methods, create an instantiation which can be passed to the JIT.
4812 * FIXME: Handle class_inst as well.
4814 if (context && context->method_inst && context->method_inst->is_open) {
4816 MonoGenericContext shared_context;
4817 MonoGenericInst *inst;
4818 MonoType **type_argv;
4820 MonoMethod *declaring_method;
4821 gboolean supported = TRUE;
4823 /* Check that the context doesn't contain open constructed types */
4824 if (context->class_inst) {
4825 inst = context->class_inst;
4826 for (i = 0; i < inst->type_argc; ++i) {
4827 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)
4829 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4833 if (context->method_inst) {
4834 inst = context->method_inst;
4835 for (i = 0; i < inst->type_argc; ++i) {
4836 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)
4838 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4846 memset (&shared_context, 0, sizeof (MonoGenericContext));
4848 inst = context->class_inst;
4850 type_argv = g_new0 (MonoType*, inst->type_argc);
4851 for (i = 0; i < inst->type_argc; ++i) {
4852 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)
4853 type_argv [i] = &mono_defaults.object_class->byval_arg;
4855 type_argv [i] = inst->type_argv [i];
4858 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4862 inst = context->method_inst;
4864 type_argv = g_new0 (MonoType*, inst->type_argc);
4865 for (i = 0; i < inst->type_argc; ++i) {
4866 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)
4867 type_argv [i] = &mono_defaults.object_class->byval_arg;
4869 type_argv [i] = inst->type_argv [i];
4872 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4876 if (method->is_generic || mono_class_is_gtd (method->klass))
4877 declaring_method = method;
4879 declaring_method = mono_method_get_declaring_generic_method (method);
4881 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4882 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4886 * If the method is fully sharable, it was already added in place of its
4887 * generic definition.
4889 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4893 * FIXME: Partially shared methods are not shared here, so we end up with
4894 * many identical methods.
4896 add_extra_method (acfg, method);
4899 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4903 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4905 klass = mono_class_get_checked (acfg->image, token, &error);
4906 if (!klass || klass->rank) {
4907 mono_error_cleanup (&error);
4911 add_generic_class (acfg, klass, FALSE, "typespec");
4914 /* Add types of args/locals */
4915 for (i = 0; i < acfg->methods->len; ++i) {
4916 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4917 add_types_from_method_header (acfg, method);
4920 if (acfg->image == mono_defaults.corlib) {
4922 MonoType *insts [256];
4925 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4926 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4927 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4928 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4929 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4930 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4931 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4932 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4933 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4934 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4936 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4938 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4939 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4941 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4942 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4944 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4946 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4948 MonoClass *enum_comparer;
4949 MonoType *insts [16];
4953 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4954 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4955 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4956 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4957 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4958 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4961 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4962 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4963 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4966 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4967 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4968 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4970 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4972 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4973 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4974 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4977 /* Add instances of the array generic interfaces for primitive types */
4978 /* This will add instances of the InternalArray_ helper methods in Array too */
4979 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4981 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4983 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4985 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4987 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4989 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4992 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4993 * used for all instances of GetGenericValueImpl by the AOT runtime.
4996 MonoGenericContext ctx;
4997 MonoType *args [16];
4998 MonoMethod *get_method;
4999 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5001 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5005 memset (&ctx, 0, sizeof (ctx));
5006 args [0] = &mono_defaults.object_class->byval_arg;
5007 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5008 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5009 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5013 /* Same for CompareExchange<T>/Exchange<T> */
5015 MonoGenericContext ctx;
5016 MonoType *args [16];
5018 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5019 gpointer iter = NULL;
5021 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5022 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5024 memset (&ctx, 0, sizeof (ctx));
5025 args [0] = &mono_defaults.object_class->byval_arg;
5026 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5027 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5028 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5033 /* Same for Volatile.Read/Write<T> */
5035 MonoGenericContext ctx;
5036 MonoType *args [16];
5038 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5039 gpointer iter = NULL;
5041 if (volatile_klass) {
5042 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5043 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5045 memset (&ctx, 0, sizeof (ctx));
5046 args [0] = &mono_defaults.object_class->byval_arg;
5047 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5048 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5049 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5055 /* object[] accessor wrappers. */
5056 for (i = 1; i < 4; ++i) {
5057 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5060 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5063 m = mono_marshal_get_array_accessor_wrapper (m);
5064 add_extra_method (acfg, m);
5066 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5069 m = mono_marshal_get_array_accessor_wrapper (m);
5070 add_extra_method (acfg, m);
5072 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5075 m = mono_marshal_get_array_accessor_wrapper (m);
5076 add_extra_method (acfg, m);
5082 * is_direct_callable:
5084 * Return whenever the method identified by JI is directly callable without
5085 * going through the PLT.
5088 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5090 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5091 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5093 gboolean direct_callable = TRUE;
5095 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5096 direct_callable = FALSE;
5097 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5098 // FIXME: Maybe call the wrapper directly ?
5099 direct_callable = FALSE;
5101 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5102 /* Disable this so all calls go through load_method (), see the
5103 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5104 * mono_debugger_agent_init ().
5106 direct_callable = FALSE;
5109 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5110 /* sgen does some initialization when the allocator method is created */
5111 direct_callable = FALSE;
5112 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5113 /* we don't know at compile time whether sgen is concurrent or not */
5114 direct_callable = FALSE;
5116 if (direct_callable)
5119 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5120 if (acfg->aot_opts.direct_pinvoke)
5122 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5123 if (acfg->aot_opts.direct_icalls)
5131 #ifdef MONO_ARCH_AOT_SUPPORTED
5133 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5135 MonoImage *image = method->klass->image;
5136 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5137 MonoTableInfo *tables = image->tables;
5138 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5139 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5140 guint32 im_cols [MONO_IMPLMAP_SIZE];
5143 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5147 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5150 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5152 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5155 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5157 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5163 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5170 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5172 if (a->native_offset == b->native_offset)
5173 return a->il_offset - b->il_offset;
5175 return a->native_offset - b->native_offset;
5179 * compute_line_numbers:
5181 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5184 static MonoDebugSourceLocation**
5185 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5187 MonoDebugMethodInfo *minfo;
5188 MonoDebugLineNumberEntry *ln_array;
5189 MonoDebugSourceLocation *loc;
5190 int i, prev_line, prev_il_offset;
5191 int *native_to_il_offset = NULL;
5192 MonoDebugSourceLocation **res;
5195 minfo = mono_debug_lookup_method (method);
5198 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5199 if (debug_info->code_size != code_size)
5202 g_assert (code_size);
5204 /* Compute the native->IL offset mapping */
5206 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5207 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5209 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5211 native_to_il_offset = g_new0 (int, code_size + 1);
5213 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5215 MonoDebugLineNumberEntry *lne = &ln_array [i];
5218 for (j = 0; j < lne->native_offset; ++j)
5219 native_to_il_offset [j] = -1;
5222 if (i < debug_info->num_line_numbers - 1) {
5223 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5225 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5226 native_to_il_offset [j] = lne->il_offset;
5228 for (j = lne->native_offset; j < code_size; ++j)
5229 native_to_il_offset [j] = lne->il_offset;
5234 /* Compute the native->line number mapping */
5235 res = g_new0 (MonoDebugSourceLocation*, code_size);
5236 prev_il_offset = -1;
5239 for (i = 0; i < code_size; ++i) {
5240 int il_offset = native_to_il_offset [i];
5242 if (il_offset == -1 || il_offset == prev_il_offset)
5244 prev_il_offset = il_offset;
5245 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5246 if (!(loc && loc->source_file))
5248 if (loc->row == prev_line) {
5249 mono_debug_symfile_free_location (loc);
5252 prev_line = loc->row;
5253 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5255 /* This will cover the prolog too */
5265 get_file_index (MonoAotCompile *acfg, const char *source_file)
5269 // FIXME: Free these
5270 if (!acfg->dwarf_ln_filenames)
5271 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5272 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5274 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5275 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5276 emit_unset_mode (acfg);
5277 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5289 * emit_and_reloc_code:
5291 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5292 * is true, calls are made through the GOT too. This is used for emitting trampolines
5293 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5294 * since trampolines are needed to make PTL work.
5297 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5299 int i, pindex, start_index;
5301 MonoJumpInfo *patch_info;
5302 MonoDebugSourceLocation **locs = NULL;
5303 gboolean skip, prologue_end = FALSE;
5304 #ifdef MONO_ARCH_AOT_SUPPORTED
5305 gboolean direct_call, external_call;
5307 const char *direct_call_target = 0;
5308 const char *direct_pinvoke;
5311 if (acfg->gas_line_numbers && method && debug_info) {
5312 locs = compute_line_numbers (method, code_len, debug_info);
5314 int findex = get_file_index (acfg, "<unknown>");
5315 emit_unset_mode (acfg);
5316 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5320 /* Collect and sort relocations */
5321 patches = g_ptr_array_new ();
5322 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5323 g_ptr_array_add (patches, patch_info);
5324 g_ptr_array_sort (patches, compare_patches);
5327 for (i = 0; i < code_len; i += INST_LEN) {
5329 for (pindex = start_index; pindex < patches->len; ++pindex) {
5330 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5331 if (patch_info->ip.i >= i)
5335 if (locs && locs [i]) {
5336 MonoDebugSourceLocation *loc = locs [i];
5338 const char *options;
5340 findex = get_file_index (acfg, loc->source_file);
5341 emit_unset_mode (acfg);
5343 options = " prologue_end";
5346 prologue_end = TRUE;
5347 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5348 mono_debug_symfile_free_location (loc);
5352 #ifdef MONO_ARCH_AOT_SUPPORTED
5353 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5354 start_index = pindex;
5356 switch (patch_info->type) {
5357 case MONO_PATCH_INFO_NONE:
5359 case MONO_PATCH_INFO_GOT_OFFSET: {
5362 arch_emit_got_offset (acfg, code + i, &code_size);
5363 i += code_size - INST_LEN;
5365 patch_info->type = MONO_PATCH_INFO_NONE;
5368 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5369 int code_size, index;
5370 char *selector = (char *)patch_info->data.target;
5372 if (!acfg->objc_selector_to_index)
5373 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5374 if (!acfg->objc_selectors)
5375 acfg->objc_selectors = g_ptr_array_new ();
5376 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5380 index = acfg->objc_selector_index;
5381 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5382 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5383 acfg->objc_selector_index ++;
5386 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5387 i += code_size - INST_LEN;
5389 patch_info->type = MONO_PATCH_INFO_NONE;
5394 * If this patch is a call, try emitting a direct call instead of
5395 * through a PLT entry. This is possible if the called method is in
5396 * the same assembly and requires no initialization.
5398 direct_call = FALSE;
5399 external_call = FALSE;
5400 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5401 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5402 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5403 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5405 direct_call_target = callee_cfg->asm_symbol;
5406 patch_info->type = MONO_PATCH_INFO_NONE;
5407 acfg->stats.direct_calls ++;
5410 acfg->stats.all_calls ++;
5411 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5412 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5413 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5414 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5416 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5417 if (direct_pinvoke) {
5419 g_assert (strlen (direct_pinvoke) < 1000);
5420 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5423 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5424 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5425 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5426 /* Call to a C function implementing a jit icall */
5428 external_call = TRUE;
5429 g_assert (strlen (sym) < 1000);
5430 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5432 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5433 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5434 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5435 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5436 /* Call to a jit icall without a wrapper */
5438 external_call = TRUE;
5439 g_assert (strlen (sym) < 1000);
5440 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5445 patch_info->type = MONO_PATCH_INFO_NONE;
5446 acfg->stats.direct_calls ++;
5449 if (!got_only && !direct_call) {
5450 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5452 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5454 direct_call_target = plt_entry->symbol;
5456 /* Nullify the patch */
5457 patch_info->type = MONO_PATCH_INFO_NONE;
5458 plt_entry->jit_used = TRUE;
5465 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5466 i += call_size - INST_LEN;
5470 got_slot = get_got_offset (acfg, FALSE, patch_info);
5472 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5473 i += code_size - INST_LEN;
5479 #endif /* MONO_ARCH_AOT_SUPPORTED */
5482 /* Find next patch */
5484 for (pindex = start_index; pindex < patches->len; ++pindex) {
5485 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5486 if (patch_info->ip.i >= i)
5490 /* Try to emit multiple bytes at once */
5491 if (pindex < patches->len && patch_info->ip.i > i) {
5494 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5495 if (locs && locs [limit])
5499 emit_code_bytes (acfg, code + i, limit - i);
5500 i = limit - INST_LEN;
5502 emit_code_bytes (acfg, code + i, INST_LEN);
5507 g_ptr_array_free (patches, TRUE);
5514 * Return a modified version of S which only includes characters permissible in symbols.
5517 sanitize_symbol (MonoAotCompile *acfg, char *s)
5519 gboolean process = FALSE;
5528 for (i = 0; i < len; ++i)
5529 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5534 gs = g_string_sized_new (len);
5535 for (i = 0; i < len; ++i) {
5537 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5538 g_string_append_c (gs, c);
5539 } else if (c > 0x7f) {
5540 /* multi-byte utf8 */
5541 g_string_append_printf (gs, "_0x%x", c);
5544 while (c >> 6 == 0x2) {
5545 g_string_append_printf (gs, "%x", c);
5549 g_string_append_printf (gs, "_");
5552 g_string_append_c (gs, '_');
5556 res = mono_mempool_strdup (acfg->mempool, gs->str);
5557 g_string_free (gs, TRUE);
5562 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5564 char *name1, *name2, *cached;
5565 int i, j, len, count;
5566 MonoMethod *cached_method;
5568 name1 = mono_method_full_name (method, TRUE);
5571 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5572 if ((!prefix || !*prefix) && name1 [0] == 'L')
5576 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5577 char adjustedPrefix [MAX_SYMBOL_SIZE];
5578 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5581 len = strlen (name1);
5582 name2 = (char *)malloc (strlen (prefix) + len + 16);
5583 memcpy (name2, prefix, strlen (prefix));
5584 j = strlen (prefix);
5585 for (i = 0; i < len; ++i) {
5586 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5588 } else if (isalnum (name1 [i])) {
5589 name2 [j ++] = name1 [i];
5590 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5592 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5595 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5605 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5606 if (!(cached_method && cached_method != method))
5608 sprintf (name2 + j, "_%d", count);
5612 cached = g_strdup (name2);
5613 g_hash_table_insert (cache, cached, method);
5619 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5624 char *debug_sym = NULL;
5625 char *symbol = NULL;
5626 int func_alignment = AOT_FUNC_ALIGNMENT;
5629 method = cfg->orig_method;
5630 code = cfg->native_code;
5632 method_index = get_method_index (acfg, method);
5633 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5635 /* Make the labels local */
5636 emit_section_change (acfg, ".text", 0);
5637 emit_alignment_code (acfg, func_alignment);
5639 if (acfg->global_symbols && acfg->need_no_dead_strip)
5640 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5642 emit_label (acfg, cfg->asm_symbol);
5644 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5646 * Write a C style symbol for every method, this has two uses:
5647 * - it works on platforms where the dwarf debugging info is not
5649 * - it allows the setting of breakpoints of aot-ed methods.
5651 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5652 cfg->asm_debug_symbol = g_strdup (debug_sym);
5654 if (acfg->need_no_dead_strip)
5655 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5656 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5657 emit_label (acfg, debug_sym);
5660 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5662 /* Emit a global symbol for the method */
5663 emit_global_inner (acfg, export_name, TRUE);
5664 emit_label (acfg, export_name);
5667 if (cfg->verbose_level > 0)
5668 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5670 acfg->stats.code_size += cfg->code_len;
5672 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5674 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 ()));
5678 if (acfg->aot_opts.write_symbols) {
5680 emit_symbol_size (acfg, debug_sym, ".");
5682 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5686 emit_label (acfg, symbol);
5693 * Encode PATCH_INFO into its disk representation.
5696 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5700 switch (patch_info->type) {
5701 case MONO_PATCH_INFO_NONE:
5703 case MONO_PATCH_INFO_IMAGE:
5704 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5706 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5707 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5708 case MONO_PATCH_INFO_GC_NURSERY_START:
5709 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5711 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5712 encode_value (patch_info->data.index, p, &p);
5714 case MONO_PATCH_INFO_METHOD_REL:
5715 encode_value ((gint)patch_info->data.offset, p, &p);
5717 case MONO_PATCH_INFO_SWITCH: {
5718 gpointer *table = (gpointer *)patch_info->data.table->table;
5721 encode_value (patch_info->data.table->table_size, p, &p);
5722 for (k = 0; k < patch_info->data.table->table_size; k++)
5723 encode_value ((int)(gssize)table [k], p, &p);
5726 case MONO_PATCH_INFO_METHODCONST:
5727 case MONO_PATCH_INFO_METHOD:
5728 case MONO_PATCH_INFO_METHOD_JUMP:
5729 case MONO_PATCH_INFO_ICALL_ADDR:
5730 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5731 case MONO_PATCH_INFO_METHOD_RGCTX:
5732 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5733 encode_method_ref (acfg, patch_info->data.method, p, &p);
5735 case MONO_PATCH_INFO_AOT_JIT_INFO:
5736 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5737 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5738 encode_value (patch_info->data.index, p, &p);
5740 case MONO_PATCH_INFO_INTERNAL_METHOD:
5741 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5742 guint32 len = strlen (patch_info->data.name);
5744 encode_value (len, p, &p);
5746 memcpy (p, patch_info->data.name, len);
5751 case MONO_PATCH_INFO_LDSTR: {
5752 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5753 guint32 token = patch_info->data.token->token;
5754 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5755 encode_value (image_index, p, &p);
5756 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5759 case MONO_PATCH_INFO_RVA:
5760 case MONO_PATCH_INFO_DECLSEC:
5761 case MONO_PATCH_INFO_LDTOKEN:
5762 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5763 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5764 encode_value (patch_info->data.token->token, p, &p);
5765 encode_value (patch_info->data.token->has_context, p, &p);
5766 if (patch_info->data.token->has_context)
5767 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5769 case MONO_PATCH_INFO_EXC_NAME: {
5770 MonoClass *ex_class;
5773 mono_class_load_from_name (mono_defaults.exception_class->image,
5774 "System", (const char *)patch_info->data.target);
5775 encode_klass_ref (acfg, ex_class, p, &p);
5778 case MONO_PATCH_INFO_R4:
5779 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5781 case MONO_PATCH_INFO_R8:
5782 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5783 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5785 case MONO_PATCH_INFO_VTABLE:
5786 case MONO_PATCH_INFO_CLASS:
5787 case MONO_PATCH_INFO_IID:
5788 case MONO_PATCH_INFO_ADJUSTED_IID:
5789 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5791 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5792 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5793 if (patch_info->data.del_tramp->method) {
5794 encode_value (1, p, &p);
5795 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5797 encode_value (0, p, &p);
5799 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5801 case MONO_PATCH_INFO_FIELD:
5802 case MONO_PATCH_INFO_SFLDA:
5803 encode_field_info (acfg, patch_info->data.field, p, &p);
5805 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5807 case MONO_PATCH_INFO_RGCTX_FETCH:
5808 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5809 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5814 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5815 * reference the same method, so encode the method only once.
5817 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5819 buf2 = (guint8 *)g_malloc (1024);
5822 encode_method_ref (acfg, entry->method, p2, &p2);
5823 g_assert (p2 - buf2 < 1024);
5825 offset = add_to_blob (acfg, buf2, p2 - buf2);
5828 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5833 encode_value (offset, p, &p);
5834 g_assert ((int)entry->info_type < 256);
5835 g_assert (entry->data->type < 256);
5836 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5837 encode_patch (acfg, entry->data, p, &p);
5840 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5841 case MONO_PATCH_INFO_AOT_MODULE:
5843 case MONO_PATCH_INFO_SIGNATURE:
5844 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5845 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5847 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5848 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5849 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5851 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5852 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5855 encode_method_ref (acfg, info->method, p, &p);
5856 encode_value (info->num_entries, p, &p);
5857 for (i = 0; i < info->num_entries; ++i) {
5858 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5860 encode_value (template_->info_type, p, &p);
5861 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5862 case MONO_PATCH_INFO_CLASS:
5863 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5865 case MONO_PATCH_INFO_FIELD:
5866 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5869 g_assert_not_reached ();
5875 case MONO_PATCH_INFO_LDSTR_LIT: {
5876 const char *s = (const char *)patch_info->data.target;
5877 int len = strlen (s);
5879 encode_value (len, p, &p);
5880 memcpy (p, s, len + 1);
5884 case MONO_PATCH_INFO_VIRT_METHOD:
5885 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5886 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5888 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5889 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5892 g_warning ("unable to handle jump info %d", patch_info->type);
5893 g_assert_not_reached ();
5900 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5903 guint32 pindex, offset;
5904 MonoJumpInfo *patch_info;
5906 encode_value (n_patches, p, &p);
5908 for (pindex = 0; pindex < patches->len; ++pindex) {
5909 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5911 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5915 offset = get_got_offset (acfg, llvm, patch_info);
5916 encode_value (offset, p, &p);
5923 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5926 int pindex, buf_size, n_patches;
5928 MonoJumpInfo *patch_info;
5929 guint32 method_index;
5931 guint32 first_got_offset;
5933 method = cfg->orig_method;
5935 method_index = get_method_index (acfg, method);
5937 /* Sort relocations */
5938 patches = g_ptr_array_new ();
5939 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5940 g_ptr_array_add (patches, patch_info);
5941 g_ptr_array_sort (patches, compare_patches);
5943 first_got_offset = acfg->cfgs [method_index]->got_offset;
5945 /**********************/
5946 /* Encode method info */
5947 /**********************/
5949 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5950 p = buf = (guint8 *)g_malloc (buf_size);
5952 if (mono_class_get_cctor (method->klass)) {
5953 encode_value (1, p, &p);
5954 encode_klass_ref (acfg, method->klass, p, &p);
5956 /* Not needed when loading the method */
5957 encode_value (0, p, &p);
5960 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5963 for (pindex = 0; pindex < patches->len; ++pindex) {
5964 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5966 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5967 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5968 patch_info->type = MONO_PATCH_INFO_NONE;
5973 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5974 /* Stored in a GOT slot initialized at module load time */
5975 patch_info->type = MONO_PATCH_INFO_NONE;
5979 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5980 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5981 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5982 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5983 /* Stored in a GOT slot initialized at module load time */
5984 patch_info->type = MONO_PATCH_INFO_NONE;
5988 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5989 /* Calls are made through the PLT */
5990 patch_info->type = MONO_PATCH_INFO_NONE;
5998 g_assert (cfg->has_got_slots);
6000 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6002 g_ptr_array_free (patches, TRUE);
6004 acfg->stats.info_size += p - buf;
6006 g_assert (p - buf < buf_size);
6008 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6013 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6015 guint32 cache_index;
6018 /* Reuse the unwind module to canonize and store unwind info entries */
6019 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6021 /* Use +/- 1 to distinguish 0s from missing entries */
6022 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6030 * It would be easier to use assembler symbols, but the caller needs an
6033 offset = acfg->unwind_info_offset;
6034 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6035 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6038 encode_value (encoded_len, p, &p);
6040 acfg->unwind_info_offset += encoded_len + (p - buf);
6046 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6049 guint32 debug_info_size, seq_points_size;
6051 MonoMethodHeader *header;
6052 guint8 *p, *buf, *debug_info;
6053 MonoJitInfo *jinfo = cfg->jit_info;
6055 gboolean use_unwind_ops = FALSE;
6056 MonoSeqPointInfo *seq_points;
6058 code = cfg->native_code;
6059 header = cfg->header;
6061 if (!acfg->aot_opts.nodebug) {
6062 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6065 debug_info_size = 0;
6068 seq_points = cfg->seq_point_info;
6069 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6071 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6073 p = buf = (guint8 *)g_malloc (buf_size);
6075 use_unwind_ops = cfg->unwind_ops != NULL;
6077 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);
6079 encode_value (flags, p, &p);
6081 if (use_unwind_ops) {
6082 guint32 encoded_len;
6084 guint32 unwind_desc;
6086 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6088 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6089 encode_value (unwind_desc, p, &p);
6093 encode_value (jinfo->unwind_info, p, &p);
6096 /*Encode the number of holes before the number of clauses to make decoding easier*/
6097 if (jinfo->has_try_block_holes) {
6098 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6099 encode_value (table->num_holes, p, &p);
6102 if (jinfo->has_arch_eh_info) {
6104 * In AOT mode, the code length is calculated from the address of the previous method,
6105 * which could include alignment padding, so calculating the start of the epilog as
6106 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6108 encode_value (jinfo->code_size, p, &p);
6111 /* Exception table */
6112 if (cfg->compile_llvm) {
6114 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6115 * since the information is only available to llc. Instead, we let llc save the data
6116 * into the LSDA, and read it from there at runtime.
6118 /* The assembly might be CIL stripped so emit the data ourselves */
6119 if (header->num_clauses)
6120 encode_value (header->num_clauses, p, &p);
6122 for (k = 0; k < header->num_clauses; ++k) {
6123 MonoExceptionClause *clause;
6125 clause = &header->clauses [k];
6127 encode_value (clause->flags, p, &p);
6128 if (clause->data.catch_class) {
6129 encode_value (1, p, &p);
6130 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6132 encode_value (0, p, &p);
6135 /* Emit the IL ranges too, since they might not be available at runtime */
6136 encode_value (clause->try_offset, p, &p);
6137 encode_value (clause->try_len, p, &p);
6138 encode_value (clause->handler_offset, p, &p);
6139 encode_value (clause->handler_len, p, &p);
6141 /* Emit a list of nesting clauses */
6142 for (i = 0; i < header->num_clauses; ++i) {
6144 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6146 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6148 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6149 encode_value (i, p, &p);
6151 encode_value (-1, p, &p);
6154 if (jinfo->num_clauses)
6155 encode_value (jinfo->num_clauses, p, &p);
6157 for (k = 0; k < jinfo->num_clauses; ++k) {
6158 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6160 encode_value (ei->flags, p, &p);
6161 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6162 /* Not used for catch clauses */
6163 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6164 encode_value (ei->exvar_offset, p, &p);
6166 encode_value (ei->exvar_offset, p, &p);
6169 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6170 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6172 if (ei->data.catch_class) {
6176 buf2 = (guint8 *)g_malloc (4096);
6178 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6180 g_assert (len < 4096);
6181 encode_value (len, p, &p);
6182 memcpy (p, buf2, len);
6186 encode_value (0, p, &p);
6190 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6191 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6192 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6196 if (jinfo->has_try_block_holes) {
6197 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6198 for (i = 0; i < table->num_holes; ++i) {
6199 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6200 encode_value (hole->clause, p, &p);
6201 encode_value (hole->length, p, &p);
6202 encode_value (hole->offset, p, &p);
6206 if (jinfo->has_arch_eh_info) {
6207 MonoArchEHJitInfo *eh_info;
6209 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6210 encode_value (eh_info->stack_size, p, &p);
6211 encode_value (eh_info->epilog_size, p, &p);
6214 if (jinfo->has_generic_jit_info) {
6215 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6216 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6220 encode_value (gi->nlocs, p, &p);
6222 for (i = 0; i < gi->nlocs; ++i) {
6223 MonoDwarfLocListEntry *entry = &gi->locations [i];
6225 encode_value (entry->is_reg ? 1 : 0, p, &p);
6226 encode_value (entry->reg, p, &p);
6228 encode_value (entry->offset, p, &p);
6230 g_assert (entry->from == 0);
6232 encode_value (entry->from, p, &p);
6233 encode_value (entry->to, p, &p);
6236 if (!cfg->compile_llvm) {
6237 encode_value (gi->has_this ? 1 : 0, p, &p);
6238 encode_value (gi->this_reg, p, &p);
6239 encode_value (gi->this_offset, p, &p);
6244 * Need to encode jinfo->method too, since it is not equal to 'method'
6245 * when using generic sharing.
6247 buf2 = (guint8 *)g_malloc (4096);
6249 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6251 g_assert (len < 4096);
6252 encode_value (len, p, &p);
6253 memcpy (p, buf2, len);
6257 if (gsctx && gsctx->is_gsharedvt) {
6258 encode_value (1, p, &p);
6260 encode_value (0, p, &p);
6264 if (seq_points_size)
6265 p += mono_seq_point_info_write (seq_points, p);
6267 g_assert (debug_info_size < buf_size);
6269 encode_value (debug_info_size, p, &p);
6270 if (debug_info_size) {
6271 memcpy (p, debug_info, debug_info_size);
6272 p += debug_info_size;
6273 g_free (debug_info);
6278 encode_value (cfg->gc_map_size, p, &p);
6279 /* The GC map requires 4 bytes of alignment */
6280 while ((gsize)p % 4)
6282 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6283 p += cfg->gc_map_size;
6286 acfg->stats.ex_info_size += p - buf;
6288 g_assert (p - buf < buf_size);
6291 /* The GC Map requires 4 byte alignment */
6292 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6297 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6300 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6302 int i, buf_size, res;
6303 gboolean no_special_static, cant_encode;
6304 gpointer iter = NULL;
6307 mono_error_cleanup (&error);
6311 p = buf = (guint8 *)g_malloc (buf_size);
6313 /* Mark as unusable */
6314 encode_value (-1, p, &p);
6316 res = add_to_blob (acfg, buf, p - buf);
6322 buf_size = 10240 + (klass->vtable_size * 16);
6323 p = buf = (guint8 *)g_malloc (buf_size);
6327 mono_class_init (klass);
6329 mono_class_get_nested_types (klass, &iter);
6330 g_assert (klass->nested_classes_inited);
6332 mono_class_setup_vtable (klass);
6335 * Emit all the information which is required for creating vtables so
6336 * the runtime does not need to create the MonoMethod structures which
6337 * take up a lot of space.
6340 no_special_static = !mono_class_has_special_static_fields (klass);
6342 /* Check whenever we have enough info to encode the vtable */
6343 cant_encode = FALSE;
6344 for (i = 0; i < klass->vtable_size; ++i) {
6345 MonoMethod *cm = klass->vtable [i];
6347 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6351 mono_class_has_finalizer (klass);
6352 if (mono_class_has_failure (klass))
6355 if (mono_class_is_gtd (klass) || cant_encode) {
6356 encode_value (-1, p, &p);
6358 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6359 encode_value (klass->vtable_size, p, &p);
6360 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);
6361 if (klass->has_cctor)
6362 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6363 if (klass->has_finalize)
6364 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6366 encode_value (klass->instance_size, p, &p);
6367 encode_value (mono_class_data_size (klass), p, &p);
6368 encode_value (klass->packing_size, p, &p);
6369 encode_value (klass->min_align, p, &p);
6371 for (i = 0; i < klass->vtable_size; ++i) {
6372 MonoMethod *cm = klass->vtable [i];
6375 encode_method_ref (acfg, cm, p, &p);
6377 encode_value (0, p, &p);
6381 acfg->stats.class_info_size += p - buf;
6383 g_assert (p - buf < buf_size);
6384 res = add_to_blob (acfg, buf, p - buf);
6391 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6393 char *debug_sym = NULL;
6396 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6397 /* Need to add a prefix to create unique symbols */
6398 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6400 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6401 prefix = mangle_symbol_alloc ("plt_");
6403 prefix = g_strdup ("plt_");
6408 case MONO_PATCH_INFO_METHOD:
6409 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6411 case MONO_PATCH_INFO_INTERNAL_METHOD:
6412 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6414 case MONO_PATCH_INFO_RGCTX_FETCH:
6415 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6417 case MONO_PATCH_INFO_ICALL_ADDR:
6418 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6419 char *s = get_debug_sym (ji->data.method, "", cache);
6421 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6425 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6426 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6434 return sanitize_symbol (acfg, debug_sym);
6438 * Calls made from AOTed code are routed through a table of jumps similar to the
6439 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6440 * control to the AOT runtime through a trampoline.
6443 emit_plt (MonoAotCompile *acfg)
6447 if (acfg->aot_opts.llvm_only) {
6448 g_assert (acfg->plt_offset == 1);
6454 emit_section_change (acfg, ".text", 0);
6455 emit_alignment_code (acfg, 16);
6456 emit_info_symbol (acfg, "plt");
6457 emit_label (acfg, acfg->plt_symbol);
6459 for (i = 0; i < acfg->plt_offset; ++i) {
6460 char *debug_sym = NULL;
6461 MonoPltEntry *plt_entry = NULL;
6465 * The first plt entry is unused.
6469 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6471 debug_sym = plt_entry->debug_sym;
6473 if (acfg->thumb_mixed && !plt_entry->jit_used)
6474 /* Emit only a thumb version */
6477 /* Skip plt entries not actually called */
6478 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6481 if (acfg->llvm && !acfg->thumb_mixed) {
6482 emit_label (acfg, plt_entry->llvm_symbol);
6484 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6485 #if defined(TARGET_MACH)
6486 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6492 if (acfg->need_no_dead_strip) {
6493 emit_unset_mode (acfg);
6494 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6496 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6497 emit_label (acfg, debug_sym);
6500 emit_label (acfg, plt_entry->symbol);
6502 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6505 emit_symbol_size (acfg, debug_sym, ".");
6508 if (acfg->thumb_mixed) {
6509 /* Make sure the ARM symbols don't alias the thumb ones */
6510 emit_zero_bytes (acfg, 16);
6513 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6516 for (i = 0; i < acfg->plt_offset; ++i) {
6517 char *debug_sym = NULL;
6518 MonoPltEntry *plt_entry = NULL;
6523 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6525 /* Skip plt entries not actually called by LLVM code */
6526 if (!plt_entry->llvm_used)
6529 if (acfg->aot_opts.write_symbols) {
6530 if (plt_entry->debug_sym)
6531 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6535 #if defined(TARGET_MACH)
6536 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6537 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6539 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6540 emit_label (acfg, debug_sym);
6542 fprintf (acfg->fp, "\n.thumb_func\n");
6544 emit_label (acfg, plt_entry->llvm_symbol);
6547 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6549 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6552 emit_symbol_size (acfg, debug_sym, ".");
6558 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6560 emit_info_symbol (acfg, "plt_end");
6564 * emit_trampoline_full:
6566 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6567 * create_jit_info_for_trampoline ().
6569 static G_GNUC_UNUSED void
6570 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6572 char start_symbol [MAX_SYMBOL_SIZE];
6573 char end_symbol [MAX_SYMBOL_SIZE];
6574 char symbol [MAX_SYMBOL_SIZE];
6575 guint32 buf_size, info_offset;
6576 MonoJumpInfo *patch_info;
6589 code_size = info->code_size;
6591 unwind_ops = info->unwind_ops;
6595 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6597 emit_section_change (acfg, ".text", 0);
6598 emit_global (acfg, start_symbol, TRUE);
6599 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6600 emit_label (acfg, start_symbol);
6602 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6603 emit_label (acfg, symbol);
6606 * The code should access everything through the GOT, so we pass
6609 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6611 emit_symbol_size (acfg, start_symbol, ".");
6614 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6615 emit_label (acfg, end_symbol);
6620 /* Sort relocations */
6621 patches = g_ptr_array_new ();
6622 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6623 if (patch_info->type != MONO_PATCH_INFO_NONE)
6624 g_ptr_array_add (patches, patch_info);
6625 g_ptr_array_sort (patches, compare_patches);
6627 buf_size = patches->len * 128 + 128;
6628 buf = (guint8 *)g_malloc (buf_size);
6631 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6632 g_assert (p - buf < buf_size);
6633 g_ptr_array_free (patches, TRUE);
6635 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6637 info_offset = add_to_blob (acfg, buf, p - buf);
6639 emit_section_change (acfg, RODATA_SECT, 0);
6640 emit_global (acfg, symbol, FALSE);
6641 emit_label (acfg, symbol);
6643 emit_int32 (acfg, info_offset);
6647 guint32 encoded_len;
6651 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6653 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6654 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6657 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6658 emit_int32 (acfg, uw_offset);
6661 /* Emit debug info */
6663 char symbol2 [MAX_SYMBOL_SIZE];
6665 sprintf (symbol, "%s", name);
6666 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6669 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6675 static G_GNUC_UNUSED void
6676 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6678 emit_trampoline_full (acfg, got_offset, info, TRUE);
6682 emit_trampolines (MonoAotCompile *acfg)
6684 char symbol [MAX_SYMBOL_SIZE];
6685 char end_symbol [MAX_SYMBOL_SIZE];
6686 int i, tramp_got_offset;
6688 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6692 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6695 g_assert (acfg->image->assembly);
6697 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6698 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6699 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6700 MonoTrampInfo *info;
6703 * Emit the generic trampolines.
6705 * We could save some code by treating the generic trampolines as a wrapper
6706 * method, but that approach has its own complexities, so we choose the simpler
6709 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6710 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6711 #ifdef DISABLE_REMOTING
6712 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6715 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6716 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6719 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6720 emit_trampoline (acfg, acfg->got_offset, info);
6723 /* Emit the exception related code pieces */
6724 mono_arch_get_restore_context (&info, TRUE);
6725 emit_trampoline (acfg, acfg->got_offset, info);
6726 mono_arch_get_call_filter (&info, TRUE);
6727 emit_trampoline (acfg, acfg->got_offset, info);
6728 mono_arch_get_throw_exception (&info, TRUE);
6729 emit_trampoline (acfg, acfg->got_offset, info);
6730 mono_arch_get_rethrow_exception (&info, TRUE);
6731 emit_trampoline (acfg, acfg->got_offset, info);
6732 mono_arch_get_throw_corlib_exception (&info, TRUE);
6733 emit_trampoline (acfg, acfg->got_offset, info);
6735 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6736 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6737 emit_trampoline (acfg, acfg->got_offset, info);
6738 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6739 emit_trampoline (acfg, acfg->got_offset, info);
6742 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6743 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6745 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6747 /* Create a separate out trampoline for more information in stack traces */
6748 info->name = g_strdup ("gsharedvt_out_trampoline");
6749 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6753 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6755 GSList *l = mono_arch_get_trampolines (TRUE);
6758 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6760 emit_trampoline (acfg, acfg->got_offset, info);
6766 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6769 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6770 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6771 emit_trampoline (acfg, acfg->got_offset, info);
6774 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6775 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6776 emit_trampoline (acfg, acfg->got_offset, info);
6780 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6781 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6782 emit_trampoline (acfg, acfg->got_offset, info);
6788 /* delegate_invoke_impl trampolines */
6789 l = mono_arch_get_delegate_invoke_impls ();
6791 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6793 emit_trampoline (acfg, acfg->got_offset, info);
6798 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6799 mono_arch_create_handler_block_trampoline (&info, TRUE);
6800 emit_trampoline (acfg, acfg->got_offset, info);
6803 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6805 /* Emit trampolines which are numerous */
6808 * These include the following:
6809 * - specific trampolines
6810 * - static rgctx invoke trampolines
6812 * These trampolines have the same code, they are parameterized by GOT
6814 * They are defined in this file, in the arch_... routines instead of
6815 * in tramp-<ARCH>.c, since it is easier to do it this way.
6819 * When running in aot-only mode, we can't create specific trampolines at
6820 * runtime, so we create a few, and save them in the AOT file.
6821 * Normal trampolines embed their argument as a literal inside the
6822 * trampoline code, we can't do that here, so instead we embed an offset
6823 * which needs to be added to the trampoline address to get the address of
6824 * the GOT slot which contains the argument value.
6825 * The generated trampolines jump to the generic trampolines using another
6826 * GOT slot, which will be setup by the AOT loader to point to the
6827 * generic trampoline code of the given type.
6831 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6835 emit_section_change (acfg, ".text", 0);
6837 tramp_got_offset = acfg->got_offset;
6839 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6841 case MONO_AOT_TRAMP_SPECIFIC:
6842 sprintf (symbol, "specific_trampolines");
6844 case MONO_AOT_TRAMP_STATIC_RGCTX:
6845 sprintf (symbol, "static_rgctx_trampolines");
6847 case MONO_AOT_TRAMP_IMT:
6848 sprintf (symbol, "imt_trampolines");
6850 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6851 sprintf (symbol, "gsharedvt_arg_trampolines");
6854 g_assert_not_reached ();
6857 sprintf (end_symbol, "%s_e", symbol);
6859 if (acfg->aot_opts.write_symbols)
6860 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6862 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6863 emit_info_symbol (acfg, symbol);
6865 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6867 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6871 case MONO_AOT_TRAMP_SPECIFIC:
6872 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6873 tramp_got_offset += 2;
6875 case MONO_AOT_TRAMP_STATIC_RGCTX:
6876 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6877 tramp_got_offset += 2;
6879 case MONO_AOT_TRAMP_IMT:
6880 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6881 tramp_got_offset += 1;
6883 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6884 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6885 tramp_got_offset += 2;
6888 g_assert_not_reached ();
6890 if (!acfg->trampoline_size [ntype]) {
6891 g_assert (tramp_size);
6892 acfg->trampoline_size [ntype] = tramp_size;
6896 emit_label (acfg, end_symbol);
6897 emit_int32 (acfg, 0);
6900 arch_emit_specific_trampoline_pages (acfg);
6902 /* Reserve some entries at the end of the GOT for our use */
6903 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6906 acfg->got_offset += acfg->num_trampoline_got_entries;
6910 str_begins_with (const char *str1, const char *str2)
6912 int len = strlen (str2);
6913 return strncmp (str1, str2, len) == 0;
6917 mono_aot_readonly_field_override (MonoClassField *field)
6920 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6921 char *p = rdv->name;
6923 len = strlen (field->parent->name_space);
6924 if (strncmp (p, field->parent->name_space, len))
6929 len = strlen (field->parent->name);
6930 if (strncmp (p, field->parent->name, len))
6935 if (strcmp (p, field->name))
6937 switch (rdv->type) {
6939 return &rdv->value.i1;
6941 return &rdv->value.i2;
6943 return &rdv->value.i4;
6952 add_readonly_value (MonoAotOptions *opts, const char *val)
6957 /* the format of val is:
6958 * namespace.typename.fieldname=type/value
6959 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6961 fval = strrchr (val, '/');
6963 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6966 tval = strrchr (val, '=');
6968 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6971 rdv = g_new0 (ReadOnlyValue, 1);
6972 rdv->name = (char *)g_malloc0 (tval - val + 1);
6973 memcpy (rdv->name, val, tval - val);
6976 if (strncmp (tval, "i1", 2) == 0) {
6977 rdv->value.i1 = atoi (fval);
6978 rdv->type = MONO_TYPE_I1;
6979 } else if (strncmp (tval, "i2", 2) == 0) {
6980 rdv->value.i2 = atoi (fval);
6981 rdv->type = MONO_TYPE_I2;
6982 } else if (strncmp (tval, "i4", 2) == 0) {
6983 rdv->value.i4 = atoi (fval);
6984 rdv->type = MONO_TYPE_I4;
6986 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6989 rdv->next = readonly_values;
6990 readonly_values = rdv;
6994 clean_path (gchar * path)
6999 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7002 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7009 wrap_path (gchar * path)
7015 // If the string contains no spaces, just return the original string.
7016 if (strstr (path, " ") == NULL)
7019 // If the string is already wrapped in quotes, return it.
7020 len = strlen (path);
7021 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7024 // If the string contains spaces, then wrap it in quotes.
7025 gchar *clean = g_strdup_printf ("\"%s\"", path);
7030 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7032 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7034 ptrdiff_t len = end-start;
7036 g_ptr_array_add (args, g_strndup (start, len));
7040 mono_aot_split_options (const char *aot_options)
7042 enum MonoAotOptionState {
7043 MONO_AOT_OPTION_STATE_DEFAULT,
7044 MONO_AOT_OPTION_STATE_STRING,
7045 MONO_AOT_OPTION_STATE_ESCAPE,
7048 GPtrArray *args = g_ptr_array_new ();
7049 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7050 gchar const *opt_start = aot_options;
7051 gboolean end_of_string = FALSE;
7054 g_return_val_if_fail (aot_options != NULL, NULL);
7056 while ((cur = *aot_options) != '\0') {
7057 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7062 // If we find a quote, then if we're in the default case then
7063 // it means we've found the start of a string, if not then it
7064 // means we've found the end of the string and should switch
7065 // back to the default case.
7067 case MONO_AOT_OPTION_STATE_DEFAULT:
7068 state = MONO_AOT_OPTION_STATE_STRING;
7070 case MONO_AOT_OPTION_STATE_STRING:
7071 state = MONO_AOT_OPTION_STATE_DEFAULT;
7073 case MONO_AOT_OPTION_STATE_ESCAPE:
7074 g_assert_not_reached ();
7079 // If we've found an escaping operator, then this means we
7080 // should not process the next character if inside a string.
7081 if (state == MONO_AOT_OPTION_STATE_STRING)
7082 state = MONO_AOT_OPTION_STATE_ESCAPE;
7085 // If we're in the default state then this means we've found
7086 // an option, store it for later processing.
7087 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7095 // If the next character is end of string, then process the last option.
7096 if (*(aot_options) == '\0') {
7097 end_of_string = TRUE;
7103 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7104 opt_start = ++aot_options;
7107 goto restart; // Check for null and continue loop
7114 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7118 args = mono_aot_split_options (aot_options ? aot_options : "");
7119 for (int i = 0; i < args->len; ++i) {
7120 const char *arg = (const char *)g_ptr_array_index (args, i);
7122 if (str_begins_with (arg, "outfile=")) {
7123 opts->outfile = g_strdup (arg + strlen ("outfile="));
7124 } else if (str_begins_with (arg, "llvm-outfile=")) {
7125 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7126 } else if (str_begins_with (arg, "temp-path=")) {
7127 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7128 } else if (str_begins_with (arg, "save-temps")) {
7129 opts->save_temps = TRUE;
7130 } else if (str_begins_with (arg, "keep-temps")) {
7131 opts->save_temps = TRUE;
7132 } else if (str_begins_with (arg, "write-symbols")) {
7133 opts->write_symbols = TRUE;
7134 } else if (str_begins_with (arg, "no-write-symbols")) {
7135 opts->write_symbols = FALSE;
7136 } else if (str_begins_with (arg, "metadata-only")) {
7137 opts->metadata_only = TRUE;
7138 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7139 opts->bind_to_runtime_version = TRUE;
7140 } else if (str_begins_with (arg, "full")) {
7141 opts->mode = MONO_AOT_MODE_FULL;
7142 } else if (str_begins_with (arg, "hybrid")) {
7143 opts->mode = MONO_AOT_MODE_HYBRID;
7144 } else if (str_begins_with (arg, "threads=")) {
7145 opts->nthreads = atoi (arg + strlen ("threads="));
7146 } else if (str_begins_with (arg, "static")) {
7147 opts->static_link = TRUE;
7148 opts->no_dlsym = TRUE;
7149 } else if (str_begins_with (arg, "asmonly")) {
7150 opts->asm_only = TRUE;
7151 } else if (str_begins_with (arg, "asmwriter")) {
7152 opts->asm_writer = TRUE;
7153 } else if (str_begins_with (arg, "nodebug")) {
7154 opts->nodebug = TRUE;
7155 } else if (str_begins_with (arg, "dwarfdebug")) {
7156 opts->dwarf_debug = TRUE;
7157 } else if (str_begins_with (arg, "nopagetrampolines")) {
7158 opts->use_trampolines_page = FALSE;
7159 } else if (str_begins_with (arg, "ntrampolines=")) {
7160 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7161 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7162 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7163 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7164 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7165 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7166 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7167 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7168 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7169 } else if (str_begins_with (arg, "tool-prefix=")) {
7170 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7171 } else if (str_begins_with (arg, "ld-flags=")) {
7172 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7173 } else if (str_begins_with (arg, "soft-debug")) {
7174 opts->soft_debug = TRUE;
7175 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7176 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7177 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7178 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7179 } else if (str_begins_with (arg, "msym-dir=")) {
7180 debug_options.no_seq_points_compact_data = FALSE;
7181 opts->gen_msym_dir = TRUE;
7182 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7183 } else if (str_begins_with (arg, "direct-pinvoke")) {
7184 opts->direct_pinvoke = TRUE;
7185 } else if (str_begins_with (arg, "direct-icalls")) {
7186 opts->direct_icalls = TRUE;
7187 } else if (str_begins_with (arg, "no-direct-calls")) {
7188 opts->no_direct_calls = TRUE;
7189 } else if (str_begins_with (arg, "print-skipped")) {
7190 opts->print_skipped_methods = TRUE;
7191 } else if (str_begins_with (arg, "stats")) {
7193 } else if (str_begins_with (arg, "no-instances")) {
7194 opts->no_instances = TRUE;
7195 } else if (str_begins_with (arg, "log-generics")) {
7196 opts->log_generics = TRUE;
7197 } else if (str_begins_with (arg, "log-instances=")) {
7198 opts->log_instances = TRUE;
7199 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7200 } else if (str_begins_with (arg, "log-instances")) {
7201 opts->log_instances = TRUE;
7202 } else if (str_begins_with (arg, "internal-logfile=")) {
7203 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7204 } else if (str_begins_with (arg, "mtriple=")) {
7205 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7206 } else if (str_begins_with (arg, "llvm-path=")) {
7207 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7208 } else if (!strcmp (arg, "llvm")) {
7210 } else if (str_begins_with (arg, "readonly-value=")) {
7211 add_readonly_value (opts, arg + strlen ("readonly-value="));
7212 } else if (str_begins_with (arg, "info")) {
7213 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7215 } else if (str_begins_with (arg, "gc-maps")) {
7216 mini_gc_enable_gc_maps_for_aot ();
7217 } else if (str_begins_with (arg, "dump")) {
7218 opts->dump_json = TRUE;
7219 } else if (str_begins_with (arg, "llvmonly")) {
7220 opts->mode = MONO_AOT_MODE_FULL;
7222 opts->llvm_only = TRUE;
7223 } else if (str_begins_with (arg, "data-outfile=")) {
7224 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7225 } else if (str_begins_with (arg, "profile=")) {
7226 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7227 } else if (!strcmp (arg, "verbose")) {
7228 opts->verbose = TRUE;
7229 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7230 printf ("Supported options for --aot:\n");
7231 printf (" outfile=\n");
7232 printf (" llvm-outfile=\n");
7233 printf (" llvm-path=\n");
7234 printf (" temp-path=\n");
7235 printf (" save-temps\n");
7236 printf (" keep-temps\n");
7237 printf (" write-symbols\n");
7238 printf (" metadata-only\n");
7239 printf (" bind-to-runtime-version\n");
7241 printf (" threads=\n");
7242 printf (" static\n");
7243 printf (" asmonly\n");
7244 printf (" asmwriter\n");
7245 printf (" nodebug\n");
7246 printf (" dwarfdebug\n");
7247 printf (" ntrampolines=\n");
7248 printf (" nrgctx-trampolines=\n");
7249 printf (" nimt-trampolines=\n");
7250 printf (" ngsharedvt-trampolines=\n");
7251 printf (" tool-prefix=\n");
7252 printf (" readonly-value=\n");
7253 printf (" soft-debug\n");
7254 printf (" msym-dir=\n");
7255 printf (" gc-maps\n");
7256 printf (" print-skipped\n");
7257 printf (" no-instances\n");
7258 printf (" stats\n");
7261 printf (" verbose\n");
7262 printf (" help/?\n");
7265 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7269 g_free ((gpointer) arg);
7272 if (opts->use_trampolines_page) {
7273 opts->ntrampolines = 0;
7274 opts->nrgctx_trampolines = 0;
7275 opts->nimt_trampolines = 0;
7276 opts->ngsharedvt_arg_trampolines = 0;
7279 g_ptr_array_free (args, /*free_seg=*/TRUE);
7283 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7285 MonoMethod *method = (MonoMethod*)key;
7286 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7287 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7288 MonoJumpInfoToken *new_ji;
7290 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7291 new_ji->image = ji->image;
7292 new_ji->token = ji->token;
7293 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7297 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7299 if (klass->type_token)
7301 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7304 return can_encode_class (acfg, klass->element_class);
7309 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7311 if (method->wrapper_type) {
7312 switch (method->wrapper_type) {
7313 case MONO_WRAPPER_NONE:
7314 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7315 case MONO_WRAPPER_XDOMAIN_INVOKE:
7316 case MONO_WRAPPER_STFLD:
7317 case MONO_WRAPPER_LDFLD:
7318 case MONO_WRAPPER_LDFLDA:
7319 case MONO_WRAPPER_STELEMREF:
7320 case MONO_WRAPPER_PROXY_ISINST:
7321 case MONO_WRAPPER_ALLOC:
7322 case MONO_WRAPPER_REMOTING_INVOKE:
7323 case MONO_WRAPPER_UNKNOWN:
7324 case MONO_WRAPPER_WRITE_BARRIER:
7325 case MONO_WRAPPER_DELEGATE_INVOKE:
7326 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7327 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7328 case MONO_WRAPPER_SYNCHRONIZED:
7330 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7331 case MONO_WRAPPER_CASTCLASS: {
7332 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7341 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7345 if (!method->token) {
7346 /* The method is part of a constructed type like Int[,].Set (). */
7347 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7348 if (method->klass->rank)
7358 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7360 switch (patch_info->type) {
7361 case MONO_PATCH_INFO_METHOD:
7362 case MONO_PATCH_INFO_METHODCONST:
7363 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7364 MonoMethod *method = patch_info->data.method;
7366 return can_encode_method (acfg, method);
7368 case MONO_PATCH_INFO_VTABLE:
7369 case MONO_PATCH_INFO_CLASS:
7370 case MONO_PATCH_INFO_IID:
7371 case MONO_PATCH_INFO_ADJUSTED_IID:
7372 if (!can_encode_class (acfg, patch_info->data.klass)) {
7373 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7377 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7378 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7379 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7384 case MONO_PATCH_INFO_RGCTX_FETCH:
7385 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7386 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7388 if (!can_encode_method (acfg, entry->method))
7390 if (!can_encode_patch (acfg, entry->data))
7402 is_concrete_type (MonoType *t)
7407 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7409 if (t->type == MONO_TYPE_GENERICINST) {
7410 MonoGenericContext *orig_ctx;
7411 MonoGenericInst *inst;
7414 if (!MONO_TYPE_ISSTRUCT (t))
7416 klass = mono_class_from_mono_type (t);
7417 orig_ctx = &mono_class_get_generic_class (klass)->context;
7419 inst = orig_ctx->class_inst;
7421 for (i = 0; i < inst->type_argc; ++i) {
7422 arg = mini_get_underlying_type (inst->type_argv [i]);
7423 if (!is_concrete_type (arg))
7427 inst = orig_ctx->method_inst;
7429 for (i = 0; i < inst->type_argc; ++i) {
7430 arg = mini_get_underlying_type (inst->type_argv [i]);
7431 if (!is_concrete_type (arg))
7439 /* LOCKING: Assumes the loader lock is held */
7441 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7443 MonoMethod *wrapper;
7444 gboolean concrete = TRUE;
7445 gboolean add_in = gsharedvt_in;
7446 gboolean add_out = gsharedvt_out;
7448 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7450 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7453 if (!add_in && !add_out)
7456 if (mini_is_gsharedvt_variable_signature (sig))
7460 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7462 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7464 if (!sig->has_type_parameters) {
7465 //printf ("%s\n", mono_signature_full_name (sig));
7468 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7469 add_extra_method (acfg, wrapper);
7471 if (gsharedvt_out) {
7472 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7473 add_extra_method (acfg, wrapper);
7476 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7477 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7480 //printf ("%s\n", mono_signature_full_name (sig));
7482 copy->ret = mini_get_underlying_type (sig->ret);
7483 if (!is_concrete_type (copy->ret))
7485 for (i = 0; i < sig->param_count; ++i) {
7486 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7487 if (!is_concrete_type (copy->params [i]))
7491 copy->has_type_parameters = 0;
7494 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7495 add_extra_method (acfg, wrapper);
7498 if (gsharedvt_out) {
7499 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7500 add_extra_method (acfg, wrapper);
7503 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7511 * AOT compile a given method.
7512 * This function might be called by multiple threads, so it must be thread-safe.
7515 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7518 MonoJumpInfo *patch_info;
7521 MonoMethod *wrapped;
7525 if (acfg->aot_opts.metadata_only)
7528 mono_acfg_lock (acfg);
7529 index = get_method_index (acfg, method);
7530 mono_acfg_unlock (acfg);
7532 /* fixme: maybe we can also precompile wrapper methods */
7533 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7534 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7535 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7536 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7540 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7543 wrapped = mono_marshal_method_from_wrapper (method);
7544 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7545 // FIXME: The wrapper should be generic too, but it is not
7548 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7551 InterlockedIncrement (&acfg->stats.mcount);
7554 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7555 InterlockedIncrement (&acfg->stats.genericcount);
7560 //acfg->aot_opts.print_skipped_methods = TRUE;
7563 * Since these methods are the only ones which are compiled with
7564 * AOT support, and they are not used by runtime startup/shutdown code,
7565 * the runtime will not see AOT methods during AOT compilation,so it
7566 * does not need to support them by creating a fake GOT etc.
7568 flags = JIT_FLAG_AOT;
7569 if (mono_aot_mode_is_full (&acfg->aot_opts))
7570 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7572 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7573 if (acfg->aot_opts.llvm_only)
7574 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7575 if (acfg->aot_opts.no_direct_calls)
7576 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7577 if (acfg->aot_opts.direct_pinvoke)
7578 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7580 jit_timer = mono_time_track_start ();
7581 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7582 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7584 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7585 if (acfg->aot_opts.print_skipped_methods)
7586 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7587 InterlockedIncrement (&acfg->stats.genericcount);
7590 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7591 if (acfg->aot_opts.print_skipped_methods)
7592 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7593 /* Let the exception happen at runtime */
7597 if (cfg->disable_aot) {
7598 if (acfg->aot_opts.print_skipped_methods)
7599 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7600 InterlockedIncrement (&acfg->stats.ocount);
7603 cfg->method_index = index;
7605 /* Nullify patches which need no aot processing */
7606 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7607 switch (patch_info->type) {
7608 case MONO_PATCH_INFO_LABEL:
7609 case MONO_PATCH_INFO_BB:
7610 patch_info->type = MONO_PATCH_INFO_NONE;
7617 /* Collect method->token associations from the cfg */
7618 mono_acfg_lock (acfg);
7619 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7620 mono_acfg_unlock (acfg);
7621 g_hash_table_destroy (cfg->token_info_hash);
7622 cfg->token_info_hash = NULL;
7625 * Check for absolute addresses.
7628 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7629 switch (patch_info->type) {
7630 case MONO_PATCH_INFO_ABS:
7631 /* unable to handle this */
7640 if (acfg->aot_opts.print_skipped_methods)
7641 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7642 InterlockedIncrement (&acfg->stats.abscount);
7646 /* Lock for the rest of the code */
7647 mono_acfg_lock (acfg);
7650 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7651 else if (cfg->gshared)
7652 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7653 else if (cfg->method->wrapper_type)
7654 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7656 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7659 * Check for methods/klasses we can't encode.
7662 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7663 if (!can_encode_patch (acfg, patch_info))
7668 if (acfg->aot_opts.print_skipped_methods)
7669 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7670 acfg->stats.ocount++;
7671 mono_acfg_unlock (acfg);
7675 if (!cfg->compile_llvm)
7676 acfg->has_jitted_code = TRUE;
7678 if (method->is_inflated && acfg->aot_opts.log_instances) {
7679 if (acfg->instances_logfile)
7680 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7682 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7685 /* Adds generic instances referenced by this method */
7687 * The depth is used to avoid infinite loops when generic virtual recursion is
7690 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7691 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7692 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7693 switch (patch_info->type) {
7694 case MONO_PATCH_INFO_RGCTX_FETCH:
7695 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7696 case MONO_PATCH_INFO_METHOD: {
7697 MonoMethod *m = NULL;
7699 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7700 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7702 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7703 m = e->data->data.method;
7705 m = patch_info->data.method;
7710 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7711 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7712 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7713 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7714 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7715 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7716 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7718 add_extra_method_with_depth (acfg, m, depth + 1);
7719 add_types_from_method_header (acfg, m);
7722 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7724 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7725 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7727 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7728 add_extra_method_with_depth (acfg, m, depth + 1);
7732 case MONO_PATCH_INFO_VTABLE: {
7733 MonoClass *klass = patch_info->data.klass;
7735 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7736 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7739 case MONO_PATCH_INFO_SFLDA: {
7740 MonoClass *klass = patch_info->data.field->parent;
7742 /* The .cctor needs to run at runtime. */
7743 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))
7744 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7753 /* Determine whenever the method has GOT slots */
7754 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7755 switch (patch_info->type) {
7756 case MONO_PATCH_INFO_GOT_OFFSET:
7757 case MONO_PATCH_INFO_NONE:
7758 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7759 case MONO_PATCH_INFO_GC_NURSERY_START:
7760 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7762 case MONO_PATCH_INFO_IMAGE:
7763 /* The assembly is stored in GOT slot 0 */
7764 if (patch_info->data.image != acfg->image)
7765 cfg->has_got_slots = TRUE;
7768 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7769 cfg->has_got_slots = TRUE;
7774 if (!cfg->has_got_slots)
7775 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7777 /* Add gsharedvt wrappers for signatures used by the method */
7778 if (acfg->aot_opts.llvm_only) {
7781 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7782 /* These only need out wrappers */
7783 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7785 for (l = cfg->signatures; l; l = l->next) {
7786 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7788 /* These only need in wrappers */
7789 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7794 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7796 /* Make a copy of the patch info which is in the mempool */
7798 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7800 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7801 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7804 patches = new_patch_info;
7806 patches_end->next = new_patch_info;
7807 patches_end = new_patch_info;
7809 cfg->patch_info = patches;
7811 /* Make a copy of the unwind info */
7813 GSList *l, *unwind_ops;
7817 for (l = cfg->unwind_ops; l; l = l->next) {
7818 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7819 memcpy (op, l->data, sizeof (MonoUnwindOp));
7820 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7822 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7824 /* Make a copy of the argument/local info */
7827 MonoInst **args, **locals;
7828 MonoMethodSignature *sig;
7829 MonoMethodHeader *header;
7832 sig = mono_method_signature (method);
7833 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7834 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7835 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7836 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7840 header = mono_method_get_header_checked (method, &error);
7841 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7842 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7843 for (i = 0; i < header->num_locals; ++i) {
7844 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7845 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7847 mono_metadata_free_mh (header);
7848 cfg->locals = locals;
7851 /* Free some fields used by cfg to conserve memory */
7852 mono_empty_compile (cfg);
7854 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7856 while (index >= acfg->cfgs_size) {
7857 MonoCompile **new_cfgs;
7860 new_size = acfg->cfgs_size * 2;
7861 new_cfgs = g_new0 (MonoCompile*, new_size);
7862 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7863 g_free (acfg->cfgs);
7864 acfg->cfgs = new_cfgs;
7865 acfg->cfgs_size = new_size;
7867 acfg->cfgs [index] = cfg;
7869 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7871 mono_update_jit_stats (cfg);
7874 if (cfg->orig_method->wrapper_type)
7875 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7878 mono_acfg_unlock (acfg);
7880 InterlockedIncrement (&acfg->stats.ccount);
7883 static mono_thread_start_return_t WINAPI
7884 compile_thread_main (gpointer user_data)
7886 MonoDomain *domain = ((MonoDomain **)user_data) [0];
7887 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [1];
7888 GPtrArray *methods = ((GPtrArray **)user_data) [2];
7892 MonoThread *thread = mono_thread_attach (domain);
7893 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7894 mono_error_assert_ok (&error);
7896 for (i = 0; i < methods->len; ++i)
7897 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7902 /* Used by the LLVM backend */
7904 mono_aot_get_got_offset (MonoJumpInfo *ji)
7906 return get_got_offset (llvm_acfg, TRUE, ji);
7910 * mono_aot_is_shared_got_offset:
7912 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7913 * when the AOT image is loaded.
7916 mono_aot_is_shared_got_offset (int offset)
7918 return offset < llvm_acfg->nshared_got_entries;
7922 mono_aot_get_method_name (MonoCompile *cfg)
7924 if (llvm_acfg->aot_opts.static_link)
7925 /* Include the assembly name too to avoid duplicate symbol errors */
7926 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7928 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7932 * mono_aot_is_linkonce_method:
7934 * Return whenever METHOD should be emitted with linkonce linkage,
7935 * eliminating duplicate copies when compiling in static mode.
7938 mono_aot_is_linkonce_method (MonoMethod *method)
7944 // FIXME: Add more cases
7945 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7947 info = mono_marshal_get_wrapper_info (method);
7948 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7955 append_mangled_type (GString *s, MonoType *t)
7958 g_string_append_printf (s, "b");
7960 case MONO_TYPE_VOID:
7961 g_string_append_printf (s, "void_");
7964 g_string_append_printf (s, "i1");
7967 g_string_append_printf (s, "u1");
7970 g_string_append_printf (s, "i2");
7973 g_string_append_printf (s, "u2");
7976 g_string_append_printf (s, "i4");
7979 g_string_append_printf (s, "u4");
7982 g_string_append_printf (s, "i8");
7985 g_string_append_printf (s, "u8");
7988 g_string_append_printf (s, "ii");
7991 g_string_append_printf (s, "ui");
7994 g_string_append_printf (s, "fl");
7997 g_string_append_printf (s, "do");
8000 char *fullname = mono_type_full_name (t);
8006 * Have to create a mangled name which is:
8010 temp = g_string_new ("");
8011 len = strlen (fullname);
8012 for (i = 0; i < len; ++i) {
8013 char c = fullname [i];
8015 g_string_append_c (temp, c);
8016 } else if (c == '_') {
8017 g_string_append_c (temp, '_');
8018 g_string_append_c (temp, '_');
8020 g_string_append_c (temp, '_');
8021 g_string_append_printf (temp, "%x", (int)c);
8024 temps = g_string_free (temp, FALSE);
8025 /* Include the length to avoid different length type names aliasing each other */
8026 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8035 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8040 supported = append_mangled_type (s, sig->ret);
8044 g_string_append_printf (s, "this_");
8045 for (i = 0; i < sig->param_count; ++i) {
8046 supported = append_mangled_type (s, sig->params [i]);
8055 * mono_aot_get_mangled_method_name:
8057 * Return a unique mangled name for METHOD, or NULL.
8060 mono_aot_get_mangled_method_name (MonoMethod *method)
8066 // FIXME: Add more cases
8067 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8069 info = mono_marshal_get_wrapper_info (method);
8070 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8073 s = g_string_new ("");
8075 g_string_append_printf (s, "aot_method_w_");
8077 switch (info->subtype) {
8078 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8079 g_string_append_printf (s, "gsharedvt_in_");
8081 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8082 g_string_append_printf (s, "gsharedvt_out_");
8085 g_assert_not_reached ();
8089 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8091 g_string_free (s, TRUE);
8095 return g_string_free (s, FALSE);
8099 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8101 return is_direct_callable (llvm_acfg, NULL, patch_info);
8105 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8107 MonoPltEntry *plt_entry;
8109 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8110 plt_entry->llvm_used = FALSE;
8114 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8116 const char *sym = NULL;
8118 if (llvm_acfg->aot_opts.direct_icalls) {
8119 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8120 /* Call to a C function implementing a jit icall */
8121 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8122 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8123 MonoMethod *method = (MonoMethod *)data;
8124 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8125 sym = mono_lookup_icall_symbol (method);
8126 else if (llvm_acfg->aot_opts.direct_pinvoke)
8127 sym = get_pinvoke_import (llvm_acfg, method);
8130 return g_strdup (sym);
8136 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8138 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8139 MonoPltEntry *plt_entry;
8140 const char *sym = NULL;
8143 ji->data.target = data;
8145 if (!can_encode_patch (llvm_acfg, ji))
8148 if (llvm_acfg->aot_opts.direct_icalls) {
8149 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8150 /* Call to a C function implementing a jit icall */
8151 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8152 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8153 MonoMethod *method = (MonoMethod *)data;
8154 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8155 sym = mono_lookup_icall_symbol (method);
8158 return g_strdup (sym);
8161 plt_entry = get_plt_entry (llvm_acfg, ji);
8162 plt_entry->llvm_used = TRUE;
8164 #if defined(TARGET_MACH)
8165 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8167 return g_strdup_printf (plt_entry->llvm_symbol);
8172 mono_aot_get_method_index (MonoMethod *method)
8174 g_assert (llvm_acfg);
8175 return get_method_index (llvm_acfg, method);
8179 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8183 mono_acfg_lock (llvm_acfg);
8184 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8185 mono_acfg_unlock (llvm_acfg);
8191 execute_system (const char * command)
8196 // We need an extra set of quotes around the whole command to properly handle commands
8197 // with spaces since internally the command is called through "cmd /c.
8198 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8200 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8201 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8202 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8203 status = _wsystem (wstr);
8206 g_free (quoted_command);
8207 #elif defined (HAVE_SYSTEM)
8208 status = system (command);
8210 g_assert_not_reached ();
8221 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8225 emit_llvm_file (MonoAotCompile *acfg)
8227 char *command, *opts, *tempbc, *optbc, *output_fname;
8229 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8230 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8231 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8233 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8234 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8237 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8240 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8241 * a lot of time, and doesn't seem to save much space.
8242 * The following optimizations cannot be enabled:
8244 * - 'jump-threading' changes our blockaddress references to int constants.
8245 * - 'basiccg' fails because it contains:
8246 * if (CS && !isa<IntrinsicInst>(II)) {
8247 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8248 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8249 * The opt list below was produced by taking the output of:
8250 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8251 * then removing tailcallelim + the global opts.
8252 * strip-dead-prototypes deletes unused intrinsics definitions.
8254 /* The dse pass is disabled because of #13734 and #17616 */
8256 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8257 * // If we have no DataLayout information around, then the size of the store
8258 * // is inferrable from the pointee type. If they are the same type, then
8259 * // we know that the store is safe.
8260 * if (AA.getDataLayout() == 0 &&
8261 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8262 * return OverwriteComplete;
8263 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8265 if (acfg->aot_opts.llvm_only)
8266 // FIXME: This doesn't work yet
8267 opts = g_strdup ("");
8269 #if LLVM_API_VERSION > 100
8270 opts = g_strdup ("-O2 -disable-tail-calls");
8272 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");
8274 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8275 aot_printf (acfg, "Executing opt: %s\n", command);
8276 if (execute_system (command) != 0)
8280 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8281 /* Nothing else to do */
8284 if (acfg->aot_opts.llvm_only) {
8285 /* Use the stock clang from xcode */
8287 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);
8289 aot_printf (acfg, "Executing clang: %s\n", command);
8290 if (execute_system (command) != 0)
8295 if (!acfg->llc_args)
8296 acfg->llc_args = g_string_new ("");
8298 /* Verbose asm slows down llc greatly */
8299 g_string_append (acfg->llc_args, " -asm-verbose=false");
8301 if (acfg->aot_opts.mtriple)
8302 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8304 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8306 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8308 #if LLVM_API_VERSION > 100
8309 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8312 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8313 /* ios requires PIC code now */
8314 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8316 if (llvm_acfg->aot_opts.static_link)
8317 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8319 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8322 if (acfg->llvm_owriter) {
8323 /* Emit an object file directly */
8324 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8325 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8327 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8329 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8330 g_free (output_fname);
8332 aot_printf (acfg, "Executing llc: %s\n", command);
8334 if (execute_system (command) != 0)
8341 emit_code (MonoAotCompile *acfg)
8343 int oindex, i, prev_index;
8344 gboolean saved_unbox_info = FALSE;
8345 char symbol [MAX_SYMBOL_SIZE];
8347 if (acfg->aot_opts.llvm_only)
8350 #if defined(TARGET_POWERPC64)
8351 sprintf (symbol, ".Lgot_addr");
8352 emit_section_change (acfg, ".text", 0);
8353 emit_alignment (acfg, 8);
8354 emit_label (acfg, symbol);
8355 emit_pointer (acfg, acfg->got_symbol);
8359 * This global symbol is used to compute the address of each method using the
8360 * code_offsets array. It is also used to compute the memory ranges occupied by
8361 * AOT code, so it must be equal to the address of the first emitted method.
8363 emit_section_change (acfg, ".text", 0);
8364 emit_alignment_code (acfg, 8);
8365 emit_info_symbol (acfg, "jit_code_start");
8368 * Emit some padding so the local symbol for the first method doesn't have the
8369 * same address as 'methods'.
8371 emit_padding (acfg, 16);
8373 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8377 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8379 cfg = acfg->cfgs [i];
8384 method = cfg->orig_method;
8386 /* Emit unbox trampoline */
8387 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8388 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8390 emit_section_change (acfg, ".text", 0);
8392 if (acfg->thumb_mixed && cfg->compile_llvm) {
8393 emit_set_thumb_mode (acfg);
8394 fprintf (acfg->fp, "\n.thumb_func\n");
8397 emit_label (acfg, symbol);
8399 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8401 if (acfg->thumb_mixed && cfg->compile_llvm)
8402 emit_set_arm_mode (acfg);
8404 if (!saved_unbox_info) {
8405 char user_symbol [128];
8407 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8409 emit_label (acfg, "ut_end");
8411 unwind_ops = mono_unwind_get_cie_program ();
8412 save_unwind_info (acfg, user_symbol, unwind_ops);
8413 mono_free_unwind_info (unwind_ops);
8415 /* Save the unbox trampoline size */
8416 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8418 saved_unbox_info = TRUE;
8422 if (cfg->compile_llvm)
8423 acfg->stats.llvm_count ++;
8425 emit_method_code (acfg, cfg);
8428 emit_section_change (acfg, ".text", 0);
8429 emit_alignment_code (acfg, 8);
8430 emit_info_symbol (acfg, "jit_code_end");
8432 /* To distinguish it from the next symbol */
8433 emit_padding (acfg, 4);
8436 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8437 * from optimizing them away, since it doesn't see that code_offsets references them.
8438 * JITted methods don't need this since they are referenced using assembler local
8440 * FIXME: This is why write-symbols doesn't work on OSX ?
8442 if (acfg->llvm && acfg->need_no_dead_strip) {
8443 fprintf (acfg->fp, "\n");
8444 for (i = 0; i < acfg->nmethods; ++i) {
8445 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8446 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8451 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8452 * This is PIE code, and the linker can update it if needed.
8455 sprintf (symbol, "method_addresses");
8456 emit_section_change (acfg, ".text", 1);
8457 emit_alignment_code (acfg, 8);
8458 emit_info_symbol (acfg, symbol);
8459 if (acfg->aot_opts.write_symbols)
8460 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8461 emit_unset_mode (acfg);
8462 if (acfg->need_no_dead_strip)
8463 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8465 for (i = 0; i < acfg->nmethods; ++i) {
8466 #ifdef MONO_ARCH_AOT_SUPPORTED
8469 if (acfg->cfgs [i]) {
8470 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8472 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8477 sprintf (symbol, "method_addresses_end");
8478 emit_label (acfg, symbol);
8481 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8482 sprintf (symbol, "unbox_trampolines");
8483 emit_section_change (acfg, RODATA_SECT, 0);
8484 emit_alignment (acfg, 8);
8485 emit_info_symbol (acfg, symbol);
8488 for (i = 0; i < acfg->nmethods; ++i) {
8493 cfg = acfg->cfgs [i];
8497 method = cfg->orig_method;
8499 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8500 index = get_method_index (acfg, method);
8502 emit_int32 (acfg, index);
8503 /* Make sure the table is sorted by index */
8504 g_assert (index > prev_index);
8508 sprintf (symbol, "unbox_trampolines_end");
8509 emit_info_symbol (acfg, symbol);
8510 emit_int32 (acfg, 0);
8512 /* Emit a separate table with the trampoline addresses/offsets */
8513 sprintf (symbol, "unbox_trampoline_addresses");
8514 emit_section_change (acfg, ".text", 0);
8515 emit_alignment_code (acfg, 8);
8516 emit_info_symbol (acfg, symbol);
8518 for (i = 0; i < acfg->nmethods; ++i) {
8523 cfg = acfg->cfgs [i];
8527 method = cfg->orig_method;
8529 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8530 #ifdef MONO_ARCH_AOT_SUPPORTED
8533 index = get_method_index (acfg, method);
8534 sprintf (symbol, "ut_%d", index);
8536 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8540 emit_int32 (acfg, 0);
8544 emit_info (MonoAotCompile *acfg)
8549 offsets = g_new0 (gint32, acfg->nmethods);
8551 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8552 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8554 if (acfg->cfgs [i]) {
8555 emit_method_info (acfg, acfg->cfgs [i]);
8556 offsets [i] = acfg->cfgs [i]->method_info_offset;
8562 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8567 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8569 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8570 #define mix(a,b,c) { \
8571 a -= c; a ^= rot(c, 4); c += b; \
8572 b -= a; b ^= rot(a, 6); a += c; \
8573 c -= b; c ^= rot(b, 8); b += a; \
8574 a -= c; a ^= rot(c,16); c += b; \
8575 b -= a; b ^= rot(a,19); a += c; \
8576 c -= b; c ^= rot(b, 4); b += a; \
8578 #define final(a,b,c) { \
8579 c ^= b; c -= rot(b,14); \
8580 a ^= c; a -= rot(c,11); \
8581 b ^= a; b -= rot(a,25); \
8582 c ^= b; c -= rot(b,16); \
8583 a ^= c; a -= rot(c,4); \
8584 b ^= a; b -= rot(a,14); \
8585 c ^= b; c -= rot(b,24); \
8589 mono_aot_type_hash (MonoType *t1)
8591 guint hash = t1->type;
8593 hash |= t1->byref << 6; /* do not collide with t1->type values */
8595 case MONO_TYPE_VALUETYPE:
8596 case MONO_TYPE_CLASS:
8597 case MONO_TYPE_SZARRAY:
8598 /* check if the distribution is good enough */
8599 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8601 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8602 case MONO_TYPE_ARRAY:
8603 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8604 case MONO_TYPE_GENERICINST:
8605 return ((hash << 5) - hash) ^ 0;
8612 * mono_aot_method_hash:
8614 * Return a hash code for methods which only depends on metadata.
8617 mono_aot_method_hash (MonoMethod *method)
8619 MonoMethodSignature *sig;
8623 guint32 *hashes_start, *hashes;
8625 MonoGenericInst *class_ginst = NULL;
8626 MonoGenericInst *ginst = NULL;
8628 /* Similar to the hash in mono_method_get_imt_slot () */
8630 sig = mono_method_signature (method);
8632 if (mono_class_is_ginst (method->klass))
8633 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
8634 if (method->is_inflated)
8635 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8637 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8638 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8639 hashes = hashes_start;
8641 /* Some wrappers are assigned to random classes */
8642 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8643 klass = method->klass;
8645 klass = mono_defaults.object_class;
8647 if (!method->wrapper_type) {
8650 if (mono_class_is_ginst (klass))
8651 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
8653 full_name = mono_type_full_name (&klass->byval_arg);
8655 hashes [0] = mono_metadata_str_hash (full_name);
8659 hashes [0] = mono_metadata_str_hash (klass->name);
8660 hashes [1] = mono_metadata_str_hash (klass->name_space);
8662 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8663 /* The method name includes a stringified pointer */
8666 hashes [2] = mono_metadata_str_hash (method->name);
8667 hashes [3] = method->wrapper_type;
8668 hashes [4] = mono_aot_type_hash (sig->ret);
8670 for (i = 0; i < sig->param_count; i++) {
8671 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8674 for (i = 0; i < class_ginst->type_argc; ++i)
8675 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8678 for (i = 0; i < ginst->type_argc; ++i)
8679 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8681 g_assert (hindex == hashes_count);
8683 /* Setup internal state */
8684 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8686 /* Handle most of the hashes */
8687 while (hashes_count > 3) {
8696 /* Handle the last 3 hashes (all the case statements fall through) */
8697 switch (hashes_count) {
8698 case 3 : c += hashes [2];
8699 case 2 : b += hashes [1];
8700 case 1 : a += hashes [0];
8702 case 0: /* nothing left to add */
8706 g_free (hashes_start);
8715 * mono_aot_get_array_helper_from_wrapper;
8717 * Get the helper method in Array called by an array wrapper method.
8720 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8724 MonoGenericContext ctx;
8725 MonoType *args [16];
8726 char *mname, *iname, *s, *s2, *helper_name = NULL;
8728 prefix = "System.Collections.Generic";
8729 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8730 s2 = strstr (s, "`1.");
8736 //printf ("X: %s %s\n", iname, mname);
8738 if (!strcmp (iname, "IList"))
8739 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8741 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8742 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8744 g_free (helper_name);
8747 if (m->is_generic) {
8749 memset (&ctx, 0, sizeof (ctx));
8750 args [0] = &method->klass->element_class->byval_arg;
8751 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8752 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8753 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8759 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8761 typedef struct HashEntry {
8762 guint32 key, value, index;
8763 struct HashEntry *next;
8767 * emit_extra_methods:
8769 * Emit methods which are not in the METHOD table, like wrappers.
8772 emit_extra_methods (MonoAotCompile *acfg)
8774 int i, table_size, buf_size;
8776 guint32 *info_offsets;
8779 HashEntry *entry, *new_entry;
8780 int nmethods, max_chain_length;
8783 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8785 /* Emit method info */
8787 for (i = 0; i < acfg->extra_methods->len; ++i) {
8788 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8789 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8795 p = buf = (guint8 *)g_malloc (buf_size);
8799 method = cfg->method_to_register;
8801 encode_method_ref (acfg, method, p, &p);
8803 g_assert ((p - buf) < buf_size);
8805 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8810 * Construct a chained hash table for mapping indexes in extra_method_info to
8813 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8814 table = g_ptr_array_sized_new (table_size);
8815 for (i = 0; i < table_size; ++i)
8816 g_ptr_array_add (table, NULL);
8817 chain_lengths = g_new0 (int, table_size);
8818 max_chain_length = 0;
8819 for (i = 0; i < acfg->extra_methods->len; ++i) {
8820 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8821 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8827 key = info_offsets [i];
8828 value = get_method_index (acfg, method);
8830 hash = mono_aot_method_hash (method) % table_size;
8831 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8833 chain_lengths [hash] ++;
8834 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8836 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8837 new_entry->key = key;
8838 new_entry->value = value;
8840 entry = (HashEntry *)g_ptr_array_index (table, hash);
8841 if (entry == NULL) {
8842 new_entry->index = hash;
8843 g_ptr_array_index (table, hash) = new_entry;
8846 entry = entry->next;
8848 entry->next = new_entry;
8849 new_entry->index = table->len;
8850 g_ptr_array_add (table, new_entry);
8853 g_free (chain_lengths);
8855 //printf ("MAX: %d\n", max_chain_length);
8857 buf_size = table->len * 12 + 4;
8858 p = buf = (guint8 *)g_malloc (buf_size);
8859 encode_int (table_size, p, &p);
8861 for (i = 0; i < table->len; ++i) {
8862 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8864 if (entry == NULL) {
8865 encode_int (0, p, &p);
8866 encode_int (0, p, &p);
8867 encode_int (0, p, &p);
8869 //g_assert (entry->key > 0);
8870 encode_int (entry->key, p, &p);
8871 encode_int (entry->value, p, &p);
8873 encode_int (entry->next->index, p, &p);
8875 encode_int (0, p, &p);
8878 g_assert (p - buf <= buf_size);
8880 /* Emit the table */
8881 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8886 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8887 * This is used by mono_aot_find_jit_info ().
8889 buf_size = acfg->extra_methods->len * 8 + 4;
8890 p = buf = (guint8 *)g_malloc (buf_size);
8891 encode_int (acfg->extra_methods->len, p, &p);
8892 for (i = 0; i < acfg->extra_methods->len; ++i) {
8893 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8895 encode_int (get_method_index (acfg, method), p, &p);
8896 encode_int (info_offsets [i], p, &p);
8898 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8901 g_free (info_offsets);
8902 g_ptr_array_free (table, TRUE);
8906 generate_aotid (guint8* aotid)
8908 gpointer rand_handle;
8912 rand_handle = mono_rand_init (NULL, 0);
8914 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8915 mono_error_assert_ok (&error);
8917 mono_rand_close (rand_handle);
8921 emit_exception_info (MonoAotCompile *acfg)
8925 SeqPointData sp_data;
8926 gboolean seq_points_to_file = FALSE;
8928 offsets = g_new0 (gint32, acfg->nmethods);
8929 for (i = 0; i < acfg->nmethods; ++i) {
8930 if (acfg->cfgs [i]) {
8931 MonoCompile *cfg = acfg->cfgs [i];
8933 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8934 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8935 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8936 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8937 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8939 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8940 offsets [i] = cfg->ex_info_offset;
8942 if (method_seq_points_to_file) {
8943 if (!seq_points_to_file) {
8944 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8945 seq_points_to_file = TRUE;
8947 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8954 if (seq_points_to_file) {
8955 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8956 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8957 char *image_basename = g_path_get_basename (acfg->image->name);
8958 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8959 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8961 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8962 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8966 mono_seq_point_data_write (&sp_data, aot_file_path);
8967 mono_seq_point_data_free (&sp_data);
8971 g_free (image_basename);
8973 g_free (aot_file_path);
8976 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8981 emit_unwind_info (MonoAotCompile *acfg)
8986 if (acfg->aot_opts.llvm_only) {
8987 g_assert (acfg->unwind_ops->len == 0);
8992 * The unwind info contains a lot of duplicates so we emit each unique
8993 * entry once, and only store the offset from the start of the table in the
8997 sprintf (symbol, "unwind_info");
8998 emit_section_change (acfg, RODATA_SECT, 1);
8999 emit_alignment (acfg, 8);
9000 emit_info_symbol (acfg, symbol);
9002 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9003 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9004 guint8 *unwind_info;
9005 guint32 unwind_info_len;
9009 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9012 encode_value (unwind_info_len, p, &p);
9013 emit_bytes (acfg, buf, p - buf);
9014 emit_bytes (acfg, unwind_info, unwind_info_len);
9016 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9021 emit_class_info (MonoAotCompile *acfg)
9026 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9027 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9028 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9030 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);
9034 typedef struct ClassNameTableEntry {
9035 guint32 token, index;
9036 struct ClassNameTableEntry *next;
9037 } ClassNameTableEntry;
9040 emit_class_name_table (MonoAotCompile *acfg)
9042 int i, table_size, buf_size;
9043 guint32 token, hash;
9048 ClassNameTableEntry *entry, *new_entry;
9051 * Construct a chained hash table for mapping class names to typedef tokens.
9053 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9054 table = g_ptr_array_sized_new (table_size);
9055 for (i = 0; i < table_size; ++i)
9056 g_ptr_array_add (table, NULL);
9057 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9059 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9060 klass = mono_class_get_checked (acfg->image, token, &error);
9062 mono_error_cleanup (&error);
9065 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9066 hash = mono_metadata_str_hash (full_name) % table_size;
9069 /* FIXME: Allocate from the mempool */
9070 new_entry = g_new0 (ClassNameTableEntry, 1);
9071 new_entry->token = token;
9073 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9074 if (entry == NULL) {
9075 new_entry->index = hash;
9076 g_ptr_array_index (table, hash) = new_entry;
9079 entry = entry->next;
9081 entry->next = new_entry;
9082 new_entry->index = table->len;
9083 g_ptr_array_add (table, new_entry);
9087 /* Emit the table */
9088 buf_size = table->len * 4 + 4;
9089 p = buf = (guint8 *)g_malloc0 (buf_size);
9091 /* FIXME: Optimize memory usage */
9092 g_assert (table_size < 65000);
9093 encode_int16 (table_size, p, &p);
9094 g_assert (table->len < 65000);
9095 for (i = 0; i < table->len; ++i) {
9096 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9098 if (entry == NULL) {
9099 encode_int16 (0, p, &p);
9100 encode_int16 (0, p, &p);
9102 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9104 encode_int16 (entry->next->index, p, &p);
9106 encode_int16 (0, p, &p);
9110 g_assert (p - buf <= buf_size);
9111 g_ptr_array_free (table, TRUE);
9113 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9119 emit_image_table (MonoAotCompile *acfg)
9125 * The image table is small but referenced in a lot of places.
9126 * So we emit it at once, and reference its elements by an index.
9128 buf_size = acfg->image_table->len * 28 + 4;
9129 for (i = 0; i < acfg->image_table->len; i++) {
9130 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9131 MonoAssemblyName *aname = &image->assembly->aname;
9133 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9136 buf = p = (guint8 *)g_malloc0 (buf_size);
9137 encode_int (acfg->image_table->len, p, &p);
9138 for (i = 0; i < acfg->image_table->len; i++) {
9139 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9140 MonoAssemblyName *aname = &image->assembly->aname;
9142 /* FIXME: Support multi-module assemblies */
9143 g_assert (image->assembly->image == image);
9145 encode_string (image->assembly_name, p, &p);
9146 encode_string (image->guid, p, &p);
9147 encode_string (aname->culture ? aname->culture : "", p, &p);
9148 encode_string ((const char*)aname->public_key_token, p, &p);
9150 while (GPOINTER_TO_UINT (p) % 8 != 0)
9153 encode_int (aname->flags, p, &p);
9154 encode_int (aname->major, p, &p);
9155 encode_int (aname->minor, p, &p);
9156 encode_int (aname->build, p, &p);
9157 encode_int (aname->revision, p, &p);
9159 g_assert (p - buf <= buf_size);
9161 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9167 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9169 int i, first_plt_got_patch = 0, buf_size;
9171 guint32 *got_info_offsets;
9172 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9174 /* Add the patches needed by the PLT to the GOT */
9176 acfg->plt_got_offset_base = acfg->got_offset;
9177 first_plt_got_patch = info->got_patches->len;
9178 for (i = 1; i < acfg->plt_offset; ++i) {
9179 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9181 g_ptr_array_add (info->got_patches, plt_entry->ji);
9183 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9186 acfg->got_offset += acfg->plt_offset;
9191 * - optimize offsets table.
9192 * - reduce number of exported symbols.
9193 * - emit info for a klass only once.
9194 * - determine when a method uses a GOT slot which is guaranteed to be already
9196 * - clean up and document the code.
9197 * - use String.Empty in class libs.
9200 /* Encode info required to decode shared GOT entries */
9201 buf_size = info->got_patches->len * 128;
9202 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9203 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9205 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9207 if (acfg->plt_offset)
9208 acfg->plt_got_info_offsets [0] = 0;
9210 for (i = 0; i < info->got_patches->len; ++i) {
9211 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9216 encode_value (ji->type, p, &p);
9218 encode_patch (acfg, ji, p, &p);
9219 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9220 g_assert (p - buf <= buf_size);
9221 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9223 if (!llvm && i >= first_plt_got_patch)
9224 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9225 acfg->stats.got_info_size += p - buf;
9228 /* Emit got_info_offsets table */
9230 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9231 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);
9235 emit_got (MonoAotCompile *acfg)
9237 char symbol [MAX_SYMBOL_SIZE];
9239 if (acfg->aot_opts.llvm_only)
9242 /* Don't make GOT global so accesses to it don't need relocations */
9243 sprintf (symbol, "%s", acfg->got_symbol);
9246 emit_unset_mode (acfg);
9247 fprintf (acfg->fp, ".section __DATA, __bss\n");
9248 emit_alignment (acfg, 8);
9250 emit_info_symbol (acfg, "jit_got");
9251 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9253 emit_section_change (acfg, ".bss", 0);
9254 emit_alignment (acfg, 8);
9255 if (acfg->aot_opts.write_symbols)
9256 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9257 emit_label (acfg, symbol);
9259 emit_info_symbol (acfg, "jit_got");
9260 if (acfg->got_offset > 0)
9261 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9264 sprintf (symbol, "got_end");
9265 emit_label (acfg, symbol);
9268 typedef struct GlobalsTableEntry {
9269 guint32 value, index;
9270 struct GlobalsTableEntry *next;
9271 } GlobalsTableEntry;
9273 #ifdef TARGET_WIN32_MSVC
9274 #define DLL_ENTRY_POINT "DllMain"
9277 emit_library_info (MonoAotCompile *acfg)
9279 // Only include for shared libraries linked directly from generated object.
9280 if (link_shared_library (acfg)) {
9282 char symbol [MAX_SYMBOL_SIZE];
9284 // Ask linker to export all global symbols.
9285 emit_section_change (acfg, ".drectve", 0);
9286 for (guint i = 0; i < acfg->globals->len; ++i) {
9287 name = (char *)g_ptr_array_index (acfg->globals, i);
9288 g_assert (name != NULL);
9289 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9290 emit_string (acfg, symbol);
9293 // Emit DLLMain function, needed by MSVC linker for DLL's.
9294 // NOTE, DllMain should not go into exports above.
9295 emit_section_change (acfg, ".text", 0);
9296 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9297 emit_label (acfg, DLL_ENTRY_POINT);
9299 // Simple implementation of DLLMain, just returning TRUE.
9300 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9301 fprintf (acfg->fp, "movl $1, %%eax\n");
9302 fprintf (acfg->fp, "ret\n");
9304 // Inform linker about our dll entry function.
9305 emit_section_change (acfg, ".drectve", 0);
9306 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9314 emit_library_info (MonoAotCompile *acfg)
9321 emit_globals (MonoAotCompile *acfg)
9327 GlobalsTableEntry *entry, *new_entry;
9329 if (!acfg->aot_opts.static_link)
9332 if (acfg->aot_opts.llvm_only) {
9333 g_assert (acfg->globals->len == 0);
9338 * When static linking, we emit a table containing our globals.
9342 * Construct a chained hash table for mapping global names to their index in
9343 * the globals table.
9345 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9346 table = g_ptr_array_sized_new (table_size);
9347 for (i = 0; i < table_size; ++i)
9348 g_ptr_array_add (table, NULL);
9349 for (i = 0; i < acfg->globals->len; ++i) {
9350 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9352 hash = mono_metadata_str_hash (name) % table_size;
9354 /* FIXME: Allocate from the mempool */
9355 new_entry = g_new0 (GlobalsTableEntry, 1);
9356 new_entry->value = i;
9358 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9359 if (entry == NULL) {
9360 new_entry->index = hash;
9361 g_ptr_array_index (table, hash) = new_entry;
9364 entry = entry->next;
9366 entry->next = new_entry;
9367 new_entry->index = table->len;
9368 g_ptr_array_add (table, new_entry);
9372 /* Emit the table */
9373 sprintf (symbol, ".Lglobals_hash");
9374 emit_section_change (acfg, RODATA_SECT, 0);
9375 emit_alignment (acfg, 8);
9376 emit_label (acfg, symbol);
9378 /* FIXME: Optimize memory usage */
9379 g_assert (table_size < 65000);
9380 emit_int16 (acfg, table_size);
9381 for (i = 0; i < table->len; ++i) {
9382 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9384 if (entry == NULL) {
9385 emit_int16 (acfg, 0);
9386 emit_int16 (acfg, 0);
9388 emit_int16 (acfg, entry->value + 1);
9390 emit_int16 (acfg, entry->next->index);
9392 emit_int16 (acfg, 0);
9396 /* Emit the names */
9397 for (i = 0; i < acfg->globals->len; ++i) {
9398 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9400 sprintf (symbol, "name_%d", i);
9401 emit_section_change (acfg, RODATA_SECT, 1);
9403 emit_alignment (acfg, 4);
9405 emit_label (acfg, symbol);
9406 emit_string (acfg, name);
9409 /* Emit the globals table */
9410 sprintf (symbol, "globals");
9411 emit_section_change (acfg, ".data", 0);
9412 /* This is not a global, since it is accessed by the init function */
9413 emit_alignment (acfg, 8);
9414 emit_info_symbol (acfg, symbol);
9416 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9417 emit_pointer (acfg, symbol);
9419 for (i = 0; i < acfg->globals->len; ++i) {
9420 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9422 sprintf (symbol, "name_%d", i);
9423 emit_pointer (acfg, symbol);
9425 g_assert (strlen (name) < sizeof (symbol));
9426 sprintf (symbol, "%s", name);
9427 emit_pointer (acfg, symbol);
9429 /* Null terminate the table */
9430 emit_int32 (acfg, 0);
9431 emit_int32 (acfg, 0);
9435 emit_mem_end (MonoAotCompile *acfg)
9439 if (acfg->aot_opts.llvm_only)
9442 sprintf (symbol, "mem_end");
9443 emit_section_change (acfg, ".text", 1);
9444 emit_alignment_code (acfg, 8);
9445 emit_label (acfg, symbol);
9449 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9453 info->version = MONO_AOT_FILE_VERSION;
9454 info->plt_got_offset_base = acfg->plt_got_offset_base;
9455 info->got_size = acfg->got_offset * sizeof (gpointer);
9456 info->plt_size = acfg->plt_offset;
9457 info->nmethods = acfg->nmethods;
9458 info->flags = acfg->flags;
9459 info->opts = acfg->opts;
9460 info->simd_opts = acfg->simd_opts;
9461 info->gc_name_index = acfg->gc_name_offset;
9462 info->datafile_size = acfg->datafile_offset;
9463 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9464 info->table_offsets [i] = acfg->table_offsets [i];
9465 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9466 info->num_trampolines [i] = acfg->num_trampolines [i];
9467 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9468 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9469 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9470 info->trampoline_size [i] = acfg->trampoline_size [i];
9471 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9473 info->double_align = MONO_ABI_ALIGNOF (double);
9474 info->long_align = MONO_ABI_ALIGNOF (gint64);
9475 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9476 info->tramp_page_size = acfg->tramp_page_size;
9477 info->nshared_got_entries = acfg->nshared_got_entries;
9478 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9479 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9481 memcpy(&info->aotid, acfg->image->aotid, 16);
9485 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9487 char symbol [MAX_SYMBOL_SIZE];
9489 const char **symbols;
9491 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9493 symbols [sindex ++] = acfg->got_symbol;
9495 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9496 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9498 symbols [sindex ++] = NULL;
9499 symbols [sindex ++] = NULL;
9501 /* llvm_get_method */
9502 symbols [sindex ++] = NULL;
9503 /* llvm_get_unbox_tramp */
9504 symbols [sindex ++] = NULL;
9505 if (!acfg->aot_opts.llvm_only) {
9506 symbols [sindex ++] = "jit_code_start";
9507 symbols [sindex ++] = "jit_code_end";
9508 symbols [sindex ++] = "method_addresses";
9510 symbols [sindex ++] = NULL;
9511 symbols [sindex ++] = NULL;
9512 symbols [sindex ++] = NULL;
9514 if (acfg->data_outfile) {
9515 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9516 symbols [sindex ++] = NULL;
9518 symbols [sindex ++] = "blob";
9519 symbols [sindex ++] = "class_name_table";
9520 symbols [sindex ++] = "class_info_offsets";
9521 symbols [sindex ++] = "method_info_offsets";
9522 symbols [sindex ++] = "ex_info_offsets";
9523 symbols [sindex ++] = "extra_method_info_offsets";
9524 symbols [sindex ++] = "extra_method_table";
9525 symbols [sindex ++] = "got_info_offsets";
9527 symbols [sindex ++] = "llvm_got_info_offsets";
9529 symbols [sindex ++] = NULL;
9530 symbols [sindex ++] = "image_table";
9532 symbols [sindex ++] = "mem_end";
9533 symbols [sindex ++] = "assembly_guid";
9534 symbols [sindex ++] = "runtime_version";
9535 if (acfg->num_trampoline_got_entries) {
9536 symbols [sindex ++] = "specific_trampolines";
9537 symbols [sindex ++] = "static_rgctx_trampolines";
9538 symbols [sindex ++] = "imt_trampolines";
9539 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9541 symbols [sindex ++] = NULL;
9542 symbols [sindex ++] = NULL;
9543 symbols [sindex ++] = NULL;
9544 symbols [sindex ++] = NULL;
9546 if (acfg->aot_opts.static_link) {
9547 symbols [sindex ++] = "globals";
9549 symbols [sindex ++] = NULL;
9551 symbols [sindex ++] = "assembly_name";
9552 symbols [sindex ++] = "plt";
9553 symbols [sindex ++] = "plt_end";
9554 symbols [sindex ++] = "unwind_info";
9555 if (!acfg->aot_opts.llvm_only) {
9556 symbols [sindex ++] = "unbox_trampolines";
9557 symbols [sindex ++] = "unbox_trampolines_end";
9558 symbols [sindex ++] = "unbox_trampoline_addresses";
9560 symbols [sindex ++] = NULL;
9561 symbols [sindex ++] = NULL;
9562 symbols [sindex ++] = NULL;
9565 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9567 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9568 emit_section_change (acfg, ".data", 0);
9569 emit_alignment (acfg, 8);
9570 emit_label (acfg, symbol);
9571 if (!acfg->aot_opts.static_link)
9572 emit_global (acfg, symbol, FALSE);
9574 /* The data emitted here must match MonoAotFileInfo. */
9576 emit_int32 (acfg, info->version);
9577 emit_int32 (acfg, info->dummy);
9580 * We emit pointers to our data structures instead of emitting global symbols which
9581 * point to them, to reduce the number of globals, and because using globals leads to
9582 * various problems (i.e. arm/thumb).
9584 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9585 emit_pointer (acfg, symbols [i]);
9587 emit_int32 (acfg, info->plt_got_offset_base);
9588 emit_int32 (acfg, info->got_size);
9589 emit_int32 (acfg, info->plt_size);
9590 emit_int32 (acfg, info->nmethods);
9591 emit_int32 (acfg, info->flags);
9592 emit_int32 (acfg, info->opts);
9593 emit_int32 (acfg, info->simd_opts);
9594 emit_int32 (acfg, info->gc_name_index);
9595 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9596 emit_int32 (acfg, info->double_align);
9597 emit_int32 (acfg, info->long_align);
9598 emit_int32 (acfg, info->generic_tramp_num);
9599 emit_int32 (acfg, info->tramp_page_size);
9600 emit_int32 (acfg, info->nshared_got_entries);
9601 emit_int32 (acfg, info->datafile_size);
9603 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9604 emit_int32 (acfg, info->table_offsets [i]);
9605 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9606 emit_int32 (acfg, info->num_trampolines [i]);
9607 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9608 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9609 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9610 emit_int32 (acfg, info->trampoline_size [i]);
9611 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9612 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9614 emit_bytes (acfg, info->aotid, 16);
9616 if (acfg->aot_opts.static_link) {
9617 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9618 emit_alignment (acfg, sizeof (gpointer));
9619 emit_label (acfg, acfg->static_linking_symbol);
9620 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9625 * Emit a structure containing all the information not stored elsewhere.
9628 emit_file_info (MonoAotCompile *acfg)
9631 MonoAotFileInfo *info;
9633 if (acfg->aot_opts.bind_to_runtime_version) {
9634 build_info = mono_get_runtime_build_info ();
9635 emit_string_symbol (acfg, "runtime_version", build_info);
9636 g_free (build_info);
9638 emit_string_symbol (acfg, "runtime_version", "");
9641 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9643 /* Emit a string holding the assembly name */
9644 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9646 info = g_new0 (MonoAotFileInfo, 1);
9647 init_aot_file_info (acfg, info);
9649 if (acfg->aot_opts.static_link) {
9650 char symbol [MAX_SYMBOL_SIZE];
9654 * Emit a global symbol which can be passed by an embedding app to
9655 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9658 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9660 /* Get rid of characters which cannot occur in symbols */
9662 for (p = symbol; *p; ++p) {
9663 if (!(isalnum (*p) || *p == '_'))
9666 acfg->static_linking_symbol = g_strdup (symbol);
9670 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9672 emit_aot_file_info (acfg, info);
9676 emit_blob (MonoAotCompile *acfg)
9678 acfg->blob_closed = TRUE;
9680 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9684 emit_objc_selectors (MonoAotCompile *acfg)
9689 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9694 * cat > foo.m << EOF
9697 * return @selector(print:);
9702 mono_img_writer_emit_unset_mode (acfg->w);
9703 g_assert (acfg->fp);
9704 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9705 fprintf (acfg->fp, ".align 3\n");
9706 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9707 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9708 emit_label (acfg, symbol);
9709 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9710 emit_pointer (acfg, symbol);
9713 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9714 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9715 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9716 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9719 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9720 fprintf (acfg->fp, ".align 3\n");
9721 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9722 fprintf (acfg->fp, ".long 0\n");
9723 fprintf (acfg->fp, ".long 16\n");
9727 emit_dwarf_info (MonoAotCompile *acfg)
9729 #ifdef EMIT_DWARF_INFO
9733 /* DIEs for methods */
9734 for (i = 0; i < acfg->nmethods; ++i) {
9735 MonoCompile *cfg = acfg->cfgs [i];
9740 // FIXME: LLVM doesn't define .Lme_...
9741 if (cfg->compile_llvm)
9744 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9746 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 ()));
9752 collect_methods (MonoAotCompile *acfg)
9755 MonoImage *image = acfg->image;
9757 /* Collect methods */
9758 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9761 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9763 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9766 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9767 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9768 mono_error_cleanup (&error);
9772 /* Load all methods eagerly to skip the slower lazy loading code */
9773 mono_class_setup_methods (method->klass);
9775 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9776 /* Compile the wrapper instead */
9777 /* We do this here instead of add_wrappers () because it is easy to do it here */
9778 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9782 /* FIXME: Some mscorlib methods don't have debug info */
9784 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9785 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9786 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9787 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9788 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9789 if (!mono_debug_lookup_method (method)) {
9790 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9797 if (method->is_generic || mono_class_is_gtd (method->klass))
9798 /* Compile the ref shared version instead */
9799 method = mini_get_shared_method (method);
9801 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9802 add_method_with_index (acfg, method, i, FALSE);
9803 acfg->method_index ++;
9806 /* gsharedvt methods */
9807 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9810 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9812 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9815 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9816 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9818 if (method->is_generic || mono_class_is_gtd (method->klass)) {
9819 MonoMethod *gshared;
9821 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9822 add_extra_method (acfg, gshared);
9826 if (mono_aot_mode_is_full (&acfg->aot_opts))
9827 add_generic_instances (acfg);
9829 if (mono_aot_mode_is_full (&acfg->aot_opts))
9830 add_wrappers (acfg);
9835 compile_methods (MonoAotCompile *acfg)
9839 if (acfg->aot_opts.nthreads > 0) {
9843 MonoThreadHandle *thread_handle;
9844 gpointer *user_data;
9845 MonoMethod **methods;
9847 methods_len = acfg->methods->len;
9849 len = acfg->methods->len / acfg->aot_opts.nthreads;
9852 * Partition the list of methods into fragments, and hand it to threads to
9855 threads = g_ptr_array_new ();
9856 /* Make a copy since acfg->methods is modified by compile_method () */
9857 methods = g_new0 (MonoMethod*, methods_len);
9858 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9859 for (i = 0; i < methods_len; ++i)
9860 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9862 while (i < methods_len) {
9863 frag = g_ptr_array_new ();
9864 for (j = 0; j < len; ++j) {
9865 if (i < methods_len) {
9866 g_ptr_array_add (frag, methods [i]);
9871 user_data = g_new0 (gpointer, 3);
9872 user_data [0] = mono_domain_get ();
9873 user_data [1] = acfg;
9874 user_data [2] = frag;
9876 thread_handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
9877 g_ptr_array_add (threads, thread_handle);
9881 for (i = 0; i < threads->len; ++i) {
9882 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
9883 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9889 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9890 for (i = methods_len; i < acfg->methods->len; ++i) {
9891 /* This can add new methods to acfg->methods */
9892 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9897 compile_asm (MonoAotCompile *acfg)
9899 char *command, *objfile;
9900 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9901 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9902 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9904 #ifdef TARGET_WIN32_MSVC
9905 #define AS_OPTIONS "-c -x assembler"
9906 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
9907 #define AS_OPTIONS "--64"
9908 #elif defined(TARGET_POWERPC64)
9909 #define AS_OPTIONS "-a64 -mppc64"
9910 #elif defined(sparc) && SIZEOF_VOID_P == 8
9911 #define AS_OPTIONS "-xarch=v9"
9912 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9913 #define AS_OPTIONS "-arch i386"
9915 #define AS_OPTIONS ""
9918 #ifdef __native_client_codegen__
9919 #if defined(TARGET_AMD64)
9920 #define AS_NAME "nacl64-as"
9922 #define AS_NAME "nacl-as"
9924 #elif defined(TARGET_OSX)
9925 #define AS_NAME "clang"
9926 #elif defined(TARGET_WIN32_MSVC)
9927 #define AS_NAME "clang.exe"
9929 #define AS_NAME "as"
9932 #ifdef TARGET_WIN32_MSVC
9933 #define AS_OBJECT_FILE_SUFFIX "obj"
9935 #define AS_OBJECT_FILE_SUFFIX "o"
9939 #define LD_NAME "ld"
9940 #define LD_OPTIONS "-shared -G"
9941 #elif defined(__ppc__) && defined(TARGET_MACH)
9942 #define LD_NAME "gcc"
9943 #define LD_OPTIONS "-dynamiclib"
9944 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9945 #define LD_NAME "clang"
9946 #define LD_OPTIONS "--shared"
9947 #elif defined(TARGET_WIN32_MSVC)
9948 #define LD_NAME "link.exe"
9949 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
9950 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9951 #define LD_NAME "gcc"
9952 #define LD_OPTIONS "-shared"
9953 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9954 #define LD_NAME "clang"
9955 #define LD_OPTIONS "-m32 -dynamiclib"
9956 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9957 #define LD_NAME "gcc"
9958 #define LD_OPTIONS "--shared"
9959 #elif defined(TARGET_POWERPC64)
9960 #define LD_OPTIONS "-m elf64ppc"
9964 #define LD_OPTIONS ""
9967 if (acfg->aot_opts.asm_only) {
9968 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9969 if (acfg->aot_opts.static_link)
9970 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9972 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9976 if (acfg->aot_opts.static_link) {
9977 if (acfg->aot_opts.outfile)
9978 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9980 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
9982 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
9986 g_string_append (acfg->as_args, "-c -x assembler");
9989 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9990 acfg->as_args ? acfg->as_args->str : "",
9991 wrap_path (objfile), wrap_path (acfg->tmpfname));
9992 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9993 if (execute_system (command) != 0) {
9999 if (acfg->llvm && !acfg->llvm_owriter) {
10000 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10001 acfg->as_args ? acfg->as_args->str : "",
10002 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10003 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10004 if (execute_system (command) != 0) {
10013 if (acfg->aot_opts.static_link) {
10014 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10015 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10020 if (acfg->aot_opts.outfile)
10021 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10023 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10025 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10028 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10030 llvm_ofile = g_strdup ("");
10033 /* replace the ; flags separators with spaces */
10034 g_strdelimit (ld_flags, ";", ' ');
10036 if (acfg->aot_opts.llvm_only)
10037 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10039 #ifdef TARGET_WIN32_MSVC
10040 g_assert (tmp_outfile_name != NULL);
10041 g_assert (objfile != NULL);
10042 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10043 ld_flags, tmp_outfile_name, objfile);
10044 #elif defined(LD_NAME)
10045 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10046 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10047 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10050 if (acfg->aot_opts.tool_prefix) {
10051 /* Cross compiling */
10052 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10053 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10054 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10056 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10057 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10058 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10060 if (acfg->aot_opts.llvm_only) {
10061 command = g_strdup_printf ("clang++ %s", args);
10063 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10068 aot_printf (acfg, "Executing the native linker: %s\n", command);
10069 if (execute_system (command) != 0) {
10070 g_free (tmp_outfile_name);
10071 g_free (outfile_name);
10080 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10081 printf ("Stripping the binary: %s\n", com);
10082 execute_system (com);
10085 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10087 * gas generates 'mapping symbols' each time code and data is mixed, which
10088 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10090 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10091 aot_printf (acfg, "Stripping the binary: %s\n", command);
10092 if (execute_system (command) != 0) {
10093 g_free (tmp_outfile_name);
10094 g_free (outfile_name);
10101 if (0 != rename (tmp_outfile_name, outfile_name)) {
10102 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10103 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10104 unlink (outfile_name);
10105 rename (tmp_outfile_name, outfile_name);
10109 #if defined(TARGET_MACH)
10110 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10111 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10112 if (execute_system (command) != 0) {
10117 if (!acfg->aot_opts.save_temps)
10120 g_free (tmp_outfile_name);
10121 g_free (outfile_name);
10124 if (acfg->aot_opts.save_temps)
10125 aot_printf (acfg, "Retained input file.\n");
10127 unlink (acfg->tmpfname);
10133 profread_byte (FILE *infile)
10138 res = fread (&i, 1, 1, infile);
10139 g_assert (res == 1);
10144 profread_int (FILE *infile)
10148 res = fread (&i, 4, 1, infile);
10149 g_assert (res == 1);
10154 profread_string (FILE *infile)
10160 len = profread_int (infile);
10161 if (len + 1 > 1024)
10162 pbuf = g_malloc (len + 1);
10165 res = fread (pbuf, 1, len, infile);
10166 g_assert (res == len);
10169 return g_strdup (buf);
10175 load_profile_file (MonoAotCompile *acfg, char *filename)
10179 int res, len, version;
10182 infile = fopen (filename, "r");
10184 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10188 printf ("Using profile data file '%s'\n", filename);
10190 sprintf (magic, AOT_PROFILER_MAGIC);
10191 len = strlen (magic);
10192 res = fread (buf, 1, len, infile);
10193 magic [len] = '\0';
10195 if ((res != len) || strcmp (buf, magic) != 0) {
10196 printf ("Profile file has wrong header: '%s'.\n", buf);
10200 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10201 version = profread_int (infile);
10202 if (version != expected_version) {
10203 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10208 ProfileData *data = g_new0 (ProfileData, 1);
10209 data->images = g_hash_table_new (NULL, NULL);
10210 data->classes = g_hash_table_new (NULL, NULL);
10211 data->ginsts = g_hash_table_new (NULL, NULL);
10212 data->methods = g_hash_table_new (NULL, NULL);
10215 int type = profread_byte (infile);
10216 int id = profread_int (infile);
10218 if (type == AOTPROF_RECORD_NONE)
10222 case AOTPROF_RECORD_IMAGE: {
10223 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10224 idata->name = profread_string (infile);
10225 char *mvid = profread_string (infile);
10227 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10230 case AOTPROF_RECORD_GINST: {
10232 int len = profread_int (infile);
10234 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10236 gdata->argv = g_new0 (ClassProfileData*, len);
10238 for (i = 0; i < len; ++i) {
10239 int class_id = profread_int (infile);
10241 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10242 g_assert (gdata->argv [i]);
10244 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10247 case AOTPROF_RECORD_TYPE: {
10248 int type = profread_byte (infile);
10251 case MONO_TYPE_CLASS: {
10252 int image_id = profread_int (infile);
10253 int ginst_id = profread_int (infile);
10254 char *class_name = profread_string (infile);
10256 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10259 char *p = strrchr (class_name, '.');
10263 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10264 cdata->image = image;
10265 cdata->ns = g_strdup (class_name);
10266 cdata->name = g_strdup (p + 1);
10268 if (ginst_id != -1) {
10269 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10270 g_assert (cdata->inst);
10272 g_free (class_name);
10274 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10278 case MONO_TYPE_SZARRAY: {
10279 int elem_id = profread_int (infile);
10285 g_assert_not_reached ();
10290 case AOTPROF_RECORD_METHOD: {
10291 int class_id = profread_int (infile);
10292 int ginst_id = profread_int (infile);
10293 int param_count = profread_int (infile);
10294 char *method_name = profread_string (infile);
10295 char *sig = profread_string (infile);
10297 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10300 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10302 mdata->klass = klass;
10303 mdata->name = method_name;
10304 mdata->signature = sig;
10305 mdata->param_count = param_count;
10307 if (ginst_id != -1) {
10308 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10309 g_assert (mdata->inst);
10311 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10315 printf ("%d\n", type);
10316 g_assert_not_reached ();
10321 acfg->profile_data = g_list_append (acfg->profile_data, data);
10325 resolve_class (ClassProfileData *cdata);
10328 resolve_ginst (GInstProfileData *inst_data)
10332 if (inst_data->inst)
10335 for (i = 0; i < inst_data->argc; ++i) {
10336 resolve_class (inst_data->argv [i]);
10337 if (!inst_data->argv [i]->klass)
10340 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10341 for (i = 0; i < inst_data->argc; ++i)
10342 args [i] = &inst_data->argv [i]->klass->byval_arg;
10344 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10348 resolve_class (ClassProfileData *cdata)
10353 if (!cdata->image->image)
10356 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10358 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10362 resolve_ginst (cdata->inst);
10363 if (!cdata->inst->inst)
10365 MonoGenericContext ctx;
10367 memset (&ctx, 0, sizeof (ctx));
10368 ctx.class_inst = cdata->inst->inst;
10369 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10371 cdata->klass = klass;
10376 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10379 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10381 GHashTableIter iter;
10382 gpointer key, value;
10389 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10390 g_hash_table_iter_init (&iter, data->images);
10391 while (g_hash_table_iter_next (&iter, &key, &value)) {
10392 ImageProfileData *idata = (ImageProfileData*)value;
10394 for (i = 0; i < assemblies->len; ++i) {
10395 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10397 if (!strcmp (ass->aname.name, idata->name)) {
10398 idata->image = ass->image;
10403 g_ptr_array_free (assemblies, TRUE);
10406 g_hash_table_iter_init (&iter, data->classes);
10407 while (g_hash_table_iter_next (&iter, &key, &value)) {
10408 ClassProfileData *cdata = (ClassProfileData*)value;
10410 if (!cdata->image->image) {
10411 if (acfg->aot_opts.verbose)
10412 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10416 resolve_class (cdata);
10419 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10424 g_hash_table_iter_init (&iter, data->methods);
10425 while (g_hash_table_iter_next (&iter, &key, &value)) {
10426 MethodProfileData *mdata = (MethodProfileData*)value;
10431 resolve_class (mdata->klass);
10432 klass = mdata->klass->klass;
10434 if (acfg->aot_opts.verbose)
10435 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10439 while ((m = mono_class_get_methods (klass, &miter))) {
10442 if (strcmp (m->name, mdata->name))
10444 MonoMethodSignature *sig = mono_method_signature (m);
10447 if (sig->param_count != mdata->param_count)
10450 resolve_ginst (mdata->inst);
10451 if (!mdata->inst->inst)
10453 MonoGenericContext ctx;
10455 memset (&ctx, 0, sizeof (ctx));
10456 ctx.method_inst = mdata->inst->inst;
10458 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10461 sig = mono_method_signature_checked (m, &error);
10462 if (!is_ok (&error)) {
10463 mono_error_cleanup (&error);
10467 char *sig_str = mono_signature_full_name (sig);
10468 gboolean match = !strcmp (sig_str, mdata->signature);
10473 //printf ("%s\n", mono_method_full_name (m, 1));
10477 if (!mdata->method) {
10478 if (acfg->aot_opts.verbose)
10479 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10485 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10489 for (i = 0; i < inst->type_argc; ++i) {
10490 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10491 if (k->image == image)
10493 if (mono_class_is_ginst (k)) {
10494 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10495 if (inst_references_image (kinst, image))
10503 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10507 for (i = 0; i < inst->type_argc; ++i) {
10508 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10509 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10516 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10518 GHashTableIter iter;
10519 gpointer key, value;
10526 * Add method instances 'related' to this assembly to the AOT image.
10528 g_hash_table_iter_init (&iter, data->methods);
10529 while (g_hash_table_iter_next (&iter, &key, &value)) {
10530 MethodProfileData *mdata = (MethodProfileData*)value;
10531 MonoMethod *m = mdata->method;
10532 MonoGenericContext *ctx;
10536 if (!m->is_inflated)
10539 ctx = mono_method_get_context (m);
10540 /* For simplicity, add instances which reference the assembly we are compiling */
10541 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10542 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10543 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10544 //printf ("%s\n", mono_method_full_name (m, TRUE));
10545 add_extra_method (acfg, m);
10547 } else if (m->klass->image == acfg->image &&
10548 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
10549 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
10550 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10551 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
10552 //printf ("%s\n", mono_method_full_name (m, TRUE));
10553 add_extra_method (acfg, m);
10557 * FIXME: We might skip some instances, for example:
10558 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
10559 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
10563 printf ("Added %d methods from profile.\n", count);
10567 init_got_info (GotInfo *info)
10571 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10572 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10573 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10574 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10575 info->got_patches = g_ptr_array_new ();
10578 static MonoAotCompile*
10579 acfg_create (MonoAssembly *ass, guint32 opts)
10581 MonoImage *image = ass->image;
10582 MonoAotCompile *acfg;
10584 acfg = g_new0 (MonoAotCompile, 1);
10585 acfg->methods = g_ptr_array_new ();
10586 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10587 acfg->method_depth = g_hash_table_new (NULL, NULL);
10588 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10589 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10590 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10591 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10592 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10593 acfg->image_hash = g_hash_table_new (NULL, NULL);
10594 acfg->image_table = g_ptr_array_new ();
10595 acfg->globals = g_ptr_array_new ();
10596 acfg->image = image;
10598 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10599 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10600 acfg->mempool = mono_mempool_new ();
10601 acfg->extra_methods = g_ptr_array_new ();
10602 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10603 acfg->unwind_ops = g_ptr_array_new ();
10604 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10605 acfg->method_order = g_ptr_array_new ();
10606 acfg->export_names = g_hash_table_new (NULL, NULL);
10607 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10608 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10609 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10610 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10611 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10612 mono_os_mutex_init_recursive (&acfg->mutex);
10614 init_got_info (&acfg->got_info);
10615 init_got_info (&acfg->llvm_got_info);
10621 got_info_free (GotInfo *info)
10625 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10626 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10627 g_free (info->patch_to_got_offset_by_type);
10628 g_hash_table_destroy (info->patch_to_got_offset);
10629 g_ptr_array_free (info->got_patches, TRUE);
10633 acfg_free (MonoAotCompile *acfg)
10637 mono_img_writer_destroy (acfg->w);
10638 for (i = 0; i < acfg->nmethods; ++i)
10639 if (acfg->cfgs [i])
10640 mono_destroy_compile (acfg->cfgs [i]);
10642 g_free (acfg->cfgs);
10644 g_free (acfg->static_linking_symbol);
10645 g_free (acfg->got_symbol);
10646 g_free (acfg->plt_symbol);
10647 g_ptr_array_free (acfg->methods, TRUE);
10648 g_ptr_array_free (acfg->image_table, TRUE);
10649 g_ptr_array_free (acfg->globals, TRUE);
10650 g_ptr_array_free (acfg->unwind_ops, TRUE);
10651 g_hash_table_destroy (acfg->method_indexes);
10652 g_hash_table_destroy (acfg->method_depth);
10653 g_hash_table_destroy (acfg->plt_offset_to_entry);
10654 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10655 if (acfg->patch_to_plt_entry [i])
10656 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10658 g_free (acfg->patch_to_plt_entry);
10659 g_hash_table_destroy (acfg->method_to_cfg);
10660 g_hash_table_destroy (acfg->token_info_hash);
10661 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10662 g_hash_table_destroy (acfg->image_hash);
10663 g_hash_table_destroy (acfg->unwind_info_offsets);
10664 g_hash_table_destroy (acfg->method_label_hash);
10665 if (acfg->typespec_classes)
10666 g_hash_table_destroy (acfg->typespec_classes);
10667 g_hash_table_destroy (acfg->export_names);
10668 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10669 g_hash_table_destroy (acfg->klass_blob_hash);
10670 g_hash_table_destroy (acfg->method_blob_hash);
10671 got_info_free (&acfg->got_info);
10672 got_info_free (&acfg->llvm_got_info);
10673 mono_mempool_destroy (acfg->mempool);
10677 #define WRAPPER(e,n) n,
10678 static const char* const
10679 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10680 #include "mono/metadata/wrapper-types.h"
10684 static G_GNUC_UNUSED const char*
10685 get_wrapper_type_name (int type)
10687 return wrapper_type_names [type];
10693 static void aot_dump (MonoAotCompile *acfg)
10699 mono_json_writer_init (&writer);
10701 mono_json_writer_object_begin(&writer);
10704 mono_json_writer_indent (&writer);
10705 mono_json_writer_object_key(&writer, "methods");
10706 mono_json_writer_array_begin (&writer);
10709 for (i = 0; i < acfg->nmethods; ++i) {
10711 MonoMethod *method;
10714 cfg = acfg->cfgs [i];
10718 method = cfg->orig_method;
10720 mono_json_writer_indent (&writer);
10721 mono_json_writer_object_begin(&writer);
10723 mono_json_writer_indent (&writer);
10724 mono_json_writer_object_key(&writer, "name");
10725 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10727 mono_json_writer_indent (&writer);
10728 mono_json_writer_object_key(&writer, "signature");
10729 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10731 mono_json_writer_indent (&writer);
10732 mono_json_writer_object_key(&writer, "code_size");
10733 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10735 klass = method->klass;
10737 mono_json_writer_indent (&writer);
10738 mono_json_writer_object_key(&writer, "class");
10739 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10741 mono_json_writer_indent (&writer);
10742 mono_json_writer_object_key(&writer, "namespace");
10743 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10745 mono_json_writer_indent (&writer);
10746 mono_json_writer_object_key(&writer, "wrapper_type");
10747 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10749 mono_json_writer_indent_pop (&writer);
10750 mono_json_writer_indent (&writer);
10751 mono_json_writer_object_end (&writer);
10752 mono_json_writer_printf (&writer, ",\n");
10755 mono_json_writer_indent_pop (&writer);
10756 mono_json_writer_indent (&writer);
10757 mono_json_writer_array_end (&writer);
10758 mono_json_writer_printf (&writer, ",\n");
10762 mono_json_writer_indent_push (&writer);
10763 mono_json_writer_indent (&writer);
10764 mono_json_writer_object_key(&writer, "plt");
10765 mono_json_writer_array_begin (&writer);
10767 for (i = 0; i < acfg->plt_offset; ++i) {
10768 MonoPltEntry *plt_entry = NULL;
10773 * The first plt entry is unused.
10777 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10778 ji = plt_entry->ji;
10780 mono_json_writer_indent (&writer);
10781 mono_json_writer_printf (&writer, "{ ");
10782 mono_json_writer_object_key(&writer, "symbol");
10783 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10786 mono_json_writer_indent_pop (&writer);
10787 mono_json_writer_indent (&writer);
10788 mono_json_writer_array_end (&writer);
10789 mono_json_writer_printf (&writer, ",\n");
10794 mono_json_writer_indent_push (&writer);
10795 mono_json_writer_indent (&writer);
10796 mono_json_writer_object_key(&writer, "got");
10797 mono_json_writer_array_begin (&writer);
10799 mono_json_writer_indent_push (&writer);
10800 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10801 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10803 mono_json_writer_indent (&writer);
10804 mono_json_writer_printf (&writer, "{ ");
10805 mono_json_writer_object_key(&writer, "patch_name");
10806 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10809 mono_json_writer_indent_pop (&writer);
10810 mono_json_writer_indent (&writer);
10811 mono_json_writer_array_end (&writer);
10812 mono_json_writer_printf (&writer, ",\n");
10815 mono_json_writer_indent_pop (&writer);
10816 mono_json_writer_indent (&writer);
10817 mono_json_writer_object_end (&writer);
10819 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10820 dumpfile = fopen (dumpname, "w+");
10823 fprintf (dumpfile, "%s", writer.text->str);
10826 mono_json_writer_destroy (&writer);
10829 static const char *preinited_jit_icalls[] = {
10830 "mono_aot_init_llvm_method",
10831 "mono_aot_init_gshared_method_this",
10832 "mono_aot_init_gshared_method_mrgctx",
10833 "mono_aot_init_gshared_method_vtable",
10834 "mono_llvm_throw_corlib_exception",
10835 "mono_init_vtable_slot",
10836 "mono_helper_ldstr_mscorlib"
10840 add_preinit_got_slots (MonoAotCompile *acfg)
10846 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10847 * during method initialization etc.
10850 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10851 ji->type = MONO_PATCH_INFO_IMAGE;
10852 ji->data.image = acfg->image;
10853 get_got_offset (acfg, FALSE, ji);
10854 get_got_offset (acfg, TRUE, ji);
10856 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10857 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10858 get_got_offset (acfg, FALSE, ji);
10859 get_got_offset (acfg, TRUE, ji);
10861 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10862 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10863 get_got_offset (acfg, FALSE, ji);
10864 get_got_offset (acfg, TRUE, ji);
10866 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10867 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10868 get_got_offset (acfg, FALSE, ji);
10869 get_got_offset (acfg, TRUE, ji);
10871 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10872 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10873 get_got_offset (acfg, FALSE, ji);
10874 get_got_offset (acfg, TRUE, ji);
10876 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10877 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10878 get_got_offset (acfg, FALSE, ji);
10879 get_got_offset (acfg, TRUE, ji);
10881 for (i = 0; i < TLS_KEY_NUM; i++) {
10882 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10883 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
10884 ji->data.index = i;
10885 get_got_offset (acfg, FALSE, ji);
10886 get_got_offset (acfg, TRUE, ji);
10888 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10889 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
10890 ji->data.index = i;
10891 get_got_offset (acfg, FALSE, ji);
10892 get_got_offset (acfg, TRUE, ji);
10895 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10896 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
10897 get_got_offset (acfg, FALSE, ji);
10898 get_got_offset (acfg, TRUE, ji);
10900 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10901 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10902 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10903 ji->data.name = preinited_jit_icalls [i];
10904 get_got_offset (acfg, FALSE, ji);
10905 get_got_offset (acfg, TRUE, ji);
10908 acfg->nshared_got_entries = acfg->got_offset;
10912 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10914 MonoImage *image = ass->image;
10917 MonoAotCompile *acfg;
10918 char *outfile_name, *tmp_outfile_name, *p;
10919 char llvm_stats_msg [256];
10923 acfg = acfg_create (ass, opts);
10925 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10926 acfg->aot_opts.write_symbols = TRUE;
10927 acfg->aot_opts.ntrampolines = 4096;
10928 acfg->aot_opts.nrgctx_trampolines = 4096;
10929 acfg->aot_opts.nimt_trampolines = 512;
10930 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10931 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10932 acfg->aot_opts.llvm_path = g_strdup ("");
10933 acfg->aot_opts.temp_path = g_strdup ("");
10935 acfg->aot_opts.use_trampolines_page = TRUE;
10938 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10940 if (acfg->aot_opts.logfile) {
10941 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10944 if (acfg->aot_opts.data_outfile) {
10945 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10946 if (!acfg->data_outfile) {
10947 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10950 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10953 //acfg->aot_opts.print_skipped_methods = TRUE;
10955 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10956 if (acfg->opts & MONO_OPT_GSHAREDVT) {
10957 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10960 if (acfg->aot_opts.llvm_only) {
10961 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10965 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10966 acfg->opts |= MONO_OPT_GSHAREDVT;
10969 #if !defined(ENABLE_LLVM)
10970 if (acfg->aot_opts.llvm_only) {
10971 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
10976 if (acfg->opts & MONO_OPT_GSHAREDVT)
10977 mono_set_generic_sharing_vt_supported (TRUE);
10979 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10981 generate_aotid ((guint8*) &acfg->image->aotid);
10983 char *aotid = mono_guid_to_string (acfg->image->aotid);
10984 aot_printf (acfg, "AOTID %s\n", aotid);
10987 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10988 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10989 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10994 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10995 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10999 if (acfg->aot_opts.static_link)
11000 acfg->aot_opts.asm_writer = TRUE;
11002 if (acfg->aot_opts.soft_debug) {
11003 MonoDebugOptions *opt = mini_get_debug_options ();
11005 opt->mdb_optimizations = TRUE;
11006 opt->gen_sdb_seq_points = TRUE;
11008 if (!mono_debug_enabled ()) {
11009 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11012 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11015 if (mono_use_llvm || acfg->aot_opts.llvm) {
11017 acfg->aot_opts.asm_writer = TRUE;
11018 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11020 if (acfg->aot_opts.soft_debug) {
11021 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11027 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11028 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11033 if (mono_aot_mode_is_full (&acfg->aot_opts))
11034 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11036 if (mono_threads_is_coop_enabled ())
11037 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11039 if (acfg->aot_opts.instances_logfile_path) {
11040 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11041 if (!acfg->instances_logfile) {
11042 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11047 if (acfg->aot_opts.profile_files) {
11050 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11051 load_profile_file (acfg, (char*)l->data);
11058 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11059 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11063 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11064 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11065 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11067 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11068 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11069 if (acfg->opts & MONO_OPT_GSHAREDVT)
11070 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11073 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11077 if (mono_use_llvm || acfg->aot_opts.llvm) {
11080 * Emit all LLVM code into a separate assembly/object file and link with it
11083 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11084 acfg->llvm_owriter = TRUE;
11085 } else if (acfg->aot_opts.llvm_outfile) {
11086 int len = strlen (acfg->aot_opts.llvm_outfile);
11088 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11089 acfg->llvm_owriter = TRUE;
11093 if (acfg->llvm && acfg->thumb_mixed)
11094 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11095 if (acfg->aot_opts.llvm_only)
11096 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11098 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11099 /* Get rid of characters which cannot occur in symbols */
11100 for (p = acfg->assembly_name_sym; *p; ++p) {
11101 if (!(isalnum (*p) || *p == '_'))
11105 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11106 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11107 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11109 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11110 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11113 acfg->method_index = 1;
11115 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11116 mono_set_partial_sharing_supported (TRUE);
11118 res = collect_methods (acfg);
11125 for (l = acfg->profile_data; l; l = l->next)
11126 resolve_profile_data (acfg, (ProfileData*)l->data);
11127 for (l = acfg->profile_data; l; l = l->next)
11128 add_profile_instances (acfg, (ProfileData*)l->data);
11131 acfg->cfgs_size = acfg->methods->len + 32;
11132 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11134 /* PLT offset 0 is reserved for the PLT trampoline */
11135 acfg->plt_offset = 1;
11136 add_preinit_got_slots (acfg);
11141 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11147 compile_methods (acfg);
11151 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11157 if (acfg->aot_opts.asm_only) {
11158 if (acfg->aot_opts.outfile) {
11159 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11160 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11162 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11163 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11165 g_assert (acfg->aot_opts.llvm_outfile);
11166 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11167 if (acfg->llvm_owriter)
11168 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11170 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11172 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11173 g_strdup_printf ("%s", "temp") :
11174 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11176 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11177 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11178 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11183 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11184 if (acfg->aot_opts.outfile)
11185 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11187 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11188 acfg->fp = fopen (acfg->tmpfname, "w+");
11190 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11191 acfg->fp = fdopen (i, "w+");
11193 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11194 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11198 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11200 tmp_outfile_name = NULL;
11201 outfile_name = NULL;
11203 /* Compute symbols for methods */
11204 for (i = 0; i < acfg->nmethods; ++i) {
11205 if (acfg->cfgs [i]) {
11206 MonoCompile *cfg = acfg->cfgs [i];
11207 int method_index = get_method_index (acfg, cfg->orig_method);
11209 if (COMPILE_LLVM (cfg))
11210 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11211 else if (acfg->global_symbols || acfg->llvm)
11212 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11214 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11215 cfg->asm_debug_symbol = cfg->asm_symbol;
11219 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11221 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11223 acfg->gas_line_numbers = TRUE;
11226 #ifdef EMIT_DWARF_INFO
11227 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11228 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11229 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11232 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11234 #endif /* EMIT_DWARF_INFO */
11237 mono_img_writer_emit_start (acfg->w);
11240 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11246 emit_extra_methods (acfg);
11248 emit_trampolines (acfg);
11250 emit_class_name_table (acfg);
11252 emit_got_info (acfg, FALSE);
11254 emit_got_info (acfg, TRUE);
11256 emit_exception_info (acfg);
11258 emit_unwind_info (acfg);
11260 emit_class_info (acfg);
11264 emit_image_table (acfg);
11270 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11273 const char *gc_name = mono_gc_get_gc_name ();
11274 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11279 emit_objc_selectors (acfg);
11281 emit_globals (acfg);
11283 emit_file_info (acfg);
11285 emit_library_info (acfg);
11288 emit_dwarf_info (acfg);
11289 mono_dwarf_writer_close (acfg->dwarf);
11292 emit_mem_end (acfg);
11294 if (acfg->need_pt_gnu_stack) {
11295 /* This is required so the .so doesn't have an executable stack */
11296 /* The bin writer already emits this */
11297 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11300 if (acfg->aot_opts.data_outfile)
11301 fclose (acfg->data_outfile);
11307 res = emit_llvm_file (acfg);
11315 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11318 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11320 strcpy (llvm_stats_msg, "");
11322 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;
11324 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",
11325 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11326 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11327 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11328 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11329 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11330 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,
11331 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11332 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11333 (int)(acfg->got_offset * sizeof (gpointer)));
11334 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11335 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11337 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11338 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11339 if (acfg->stats.genericcount)
11340 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11341 if (acfg->stats.abscount)
11342 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11343 if (acfg->stats.lmfcount)
11344 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11345 if (acfg->stats.ocount)
11346 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11350 res = mono_img_writer_emit_writeout (acfg->w);
11355 res = compile_asm (acfg);
11362 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11364 if (acfg->aot_opts.stats) {
11367 aot_printf (acfg, "GOT slot distribution:\n");
11368 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11369 if (acfg->stats.got_slot_types [i])
11370 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]);
11371 aot_printf (acfg, "\nMethod stats:\n");
11372 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11373 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11374 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11375 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11378 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);
11380 if (acfg->aot_opts.dump_json)
11393 mono_aot_readonly_field_override (MonoClassField *field)
11399 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11405 mono_aot_is_shared_got_offset (int offset)