[ci] Add {,hybrid,full}aot_llvm presets to make sure we compile with LLVM (#8053)
[mono-project.git] / mono / mini / aot-compiler.c
blobfa9cfe66ecf714651b4d320d9fccf9102c080daf
1 /**
2 * \file
3 * mono Ahead of Time compiler
5 * Author:
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
8 * Johan Lorensson (lateralusx.github@gmail.com)
10 * (C) 2002 Ximian, Inc.
11 * Copyright 2003-2011 Novell, Inc
12 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include "config.h"
17 #include <sys/types.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_STDINT_H
22 #include <stdint.h>
23 #endif
24 #include <fcntl.h>
25 #include <ctype.h>
26 #include <string.h>
27 #ifndef HOST_WIN32
28 #include <sys/time.h>
29 #else
30 #include <winsock2.h>
31 #include <windows.h>
32 #endif
34 #include <errno.h>
35 #include <sys/stat.h>
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/metadata/custom-attrs-internals.h>
53 #include <mono/utils/mono-logger-internals.h>
54 #include <mono/utils/mono-compiler.h>
55 #include <mono/utils/mono-time.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-rand.h>
58 #include <mono/utils/json.h>
59 #include <mono/utils/mono-threads-coop.h>
60 #include <mono/profiler/aot.h>
61 #include <mono/utils/w32api.h>
63 #include "aot-compiler.h"
64 #include "aot-runtime.h"
65 #include "seq-points.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68 #include "mini-gc.h"
69 #include "mini-llvm.h"
70 #include "mini-runtime.h"
72 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
74 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
75 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
76 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
77 #define TARGET_X86_64_WIN32_MSVC
78 #endif
80 #if defined(TARGET_X86_64_WIN32_MSVC)
81 #define TARGET_WIN32_MSVC
82 #endif
84 // Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
85 // works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
86 // compiling for AMD64 (Windows x64 platforms).
87 #if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
88 #define EMIT_WIN32_UNWIND_INFO
89 #endif
91 #if defined(__linux__)
92 #define RODATA_SECT ".rodata"
93 #elif defined(TARGET_MACH)
94 #define RODATA_SECT ".section __TEXT, __const"
95 #elif defined(TARGET_WIN32_MSVC)
96 #define RODATA_SECT ".rdata"
97 #else
98 #define RODATA_SECT ".text"
99 #endif
101 #define TV_DECLARE(name) gint64 name
102 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
103 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
105 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
107 typedef struct {
108 char *name;
109 MonoImage *image;
110 } ImageProfileData;
112 typedef struct ClassProfileData ClassProfileData;
114 typedef struct {
115 int argc;
116 ClassProfileData **argv;
117 MonoGenericInst *inst;
118 } GInstProfileData;
120 struct ClassProfileData {
121 ImageProfileData *image;
122 char *ns, *name;
123 GInstProfileData *inst;
124 MonoClass *klass;
127 typedef struct {
128 ClassProfileData *klass;
129 int id;
130 char *name;
131 int param_count;
132 char *signature;
133 GInstProfileData *inst;
134 MonoMethod *method;
135 } MethodProfileData;
137 typedef struct {
138 GHashTable *images, *classes, *ginsts, *methods;
139 } ProfileData;
141 /* predefined values for static readonly fields without needed to run the .cctor */
142 typedef struct _ReadOnlyValue ReadOnlyValue;
143 struct _ReadOnlyValue {
144 ReadOnlyValue *next;
145 char *name;
146 int type; /* to be used later for typechecking to prevent user errors */
147 union {
148 guint8 i1;
149 guint16 i2;
150 guint32 i4;
151 guint64 i8;
152 gpointer ptr;
153 } value;
155 static ReadOnlyValue *readonly_values;
157 typedef struct MonoAotOptions {
158 char *outfile;
159 char *llvm_outfile;
160 char *data_outfile;
161 GList *profile_files;
162 gboolean save_temps;
163 gboolean write_symbols;
164 gboolean metadata_only;
165 gboolean bind_to_runtime_version;
166 MonoAotMode mode;
167 gboolean interp;
168 gboolean no_dlsym;
169 gboolean static_link;
170 gboolean asm_only;
171 gboolean asm_writer;
172 gboolean nodebug;
173 gboolean dwarf_debug;
174 gboolean soft_debug;
175 gboolean log_generics;
176 gboolean log_instances;
177 gboolean gen_msym_dir;
178 char *gen_msym_dir_path;
179 gboolean direct_pinvoke;
180 gboolean direct_icalls;
181 gboolean no_direct_calls;
182 gboolean use_trampolines_page;
183 gboolean no_instances;
184 // We are collecting inflated methods and emitting non-inflated
185 gboolean dedup;
186 // The name of the assembly for which the AOT module is going to have all deduped methods moved to.
187 // When set, we are emitting inflated methods only
188 char *dedup_include;
189 gboolean gnu_asm;
190 gboolean llvm;
191 gboolean llvm_only;
192 int nthreads;
193 int ntrampolines;
194 int nrgctx_trampolines;
195 int nimt_trampolines;
196 int ngsharedvt_arg_trampolines;
197 int nrgctx_fetch_trampolines;
198 gboolean print_skipped_methods;
199 gboolean stats;
200 gboolean verbose;
201 char *tool_prefix;
202 char *ld_flags;
203 char *mtriple;
204 char *llvm_path;
205 char *temp_path;
206 char *instances_logfile_path;
207 char *logfile;
208 char *llvm_opts;
209 gboolean dump_json;
210 gboolean profile_only;
211 } MonoAotOptions;
213 typedef enum {
214 METHOD_CAT_NORMAL,
215 METHOD_CAT_GSHAREDVT,
216 METHOD_CAT_INST,
217 METHOD_CAT_WRAPPER,
218 METHOD_CAT_NUM
219 } MethodCategory;
221 typedef struct MonoAotStats {
222 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
223 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
224 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
225 int got_slots, offsets_size;
226 int method_categories [METHOD_CAT_NUM];
227 int got_slot_types [MONO_PATCH_INFO_NUM];
228 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
229 int jit_time, gen_time, link_time;
230 } MonoAotStats;
232 typedef struct GotInfo {
233 GHashTable *patch_to_got_offset;
234 GHashTable **patch_to_got_offset_by_type;
235 GPtrArray *got_patches;
236 } GotInfo;
238 #ifdef EMIT_WIN32_UNWIND_INFO
239 typedef struct _UnwindInfoSectionCacheItem {
240 char *xdata_section_label;
241 PUNWIND_INFO unwind_info;
242 gboolean xdata_section_emitted;
243 } UnwindInfoSectionCacheItem;
244 #endif
246 typedef struct MonoAotCompile {
247 MonoImage *image;
248 GPtrArray *methods;
249 GHashTable *method_indexes;
250 GHashTable *method_depth;
251 MonoCompile **cfgs;
252 int cfgs_size;
253 GHashTable **patch_to_plt_entry;
254 GHashTable *plt_offset_to_entry;
255 //GHashTable *patch_to_got_offset;
256 //GHashTable **patch_to_got_offset_by_type;
257 //GPtrArray *got_patches;
258 GotInfo got_info, llvm_got_info;
259 GHashTable *image_hash;
260 GHashTable *method_to_cfg;
261 GHashTable *token_info_hash;
262 GHashTable *method_to_pinvoke_import;
263 GPtrArray *extra_methods;
264 GPtrArray *image_table;
265 GPtrArray *globals;
266 GPtrArray *method_order;
267 GHashTable *dedup_stats;
268 GHashTable *dedup_cache;
269 gboolean dedup_cache_changed;
270 GHashTable *export_names;
271 /* Maps MonoClass* -> blob offset */
272 GHashTable *klass_blob_hash;
273 /* Maps MonoMethod* -> blob offset */
274 GHashTable *method_blob_hash;
275 GHashTable *gsharedvt_in_signatures;
276 GHashTable *gsharedvt_out_signatures;
277 guint32 *plt_got_info_offsets;
278 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
279 /* Number of GOT entries reserved for trampolines */
280 guint32 num_trampoline_got_entries;
281 guint32 tramp_page_size;
283 guint32 table_offsets [MONO_AOT_TABLE_NUM];
284 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
285 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
286 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
287 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
289 MonoAotOptions aot_opts;
290 guint32 nmethods;
291 guint32 opts;
292 guint32 simd_opts;
293 MonoMemPool *mempool;
294 MonoAotStats stats;
295 int method_index;
296 char *static_linking_symbol;
297 mono_mutex_t mutex;
298 gboolean gas_line_numbers;
299 /* Whenever to emit an object file directly from llc */
300 gboolean llvm_owriter;
301 gboolean llvm_owriter_supported;
302 MonoImageWriter *w;
303 MonoDwarfWriter *dwarf;
304 FILE *fp;
305 char *tmpbasename;
306 char *tmpfname;
307 char *llvm_sfile;
308 char *llvm_ofile;
309 GSList *cie_program;
310 GHashTable *unwind_info_offsets;
311 GPtrArray *unwind_ops;
312 guint32 unwind_info_offset;
313 char *global_prefix;
314 char *got_symbol;
315 char *llvm_got_symbol;
316 char *plt_symbol;
317 char *llvm_eh_frame_symbol;
318 GHashTable *method_label_hash;
319 const char *temp_prefix;
320 const char *user_symbol_prefix;
321 const char *llvm_label_prefix;
322 const char *inst_directive;
323 int align_pad_value;
324 guint32 label_generator;
325 gboolean llvm;
326 gboolean has_jitted_code;
327 gboolean is_full_aot;
328 MonoAotFileFlags flags;
329 MonoDynamicStream blob;
330 gboolean blob_closed;
331 GHashTable *typespec_classes;
332 GString *llc_args;
333 GString *as_args;
334 char *assembly_name_sym;
335 GHashTable *plt_entry_debug_sym_cache;
336 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
337 GHashTable *ginst_hash;
338 GHashTable *dwarf_ln_filenames;
339 gboolean global_symbols;
340 int objc_selector_index, objc_selector_index_2;
341 GPtrArray *objc_selectors;
342 GHashTable *objc_selector_to_index;
343 GList *profile_data;
344 GHashTable *profile_methods;
345 #ifdef EMIT_WIN32_UNWIND_INFO
346 GList *unwind_info_section_cache;
347 #endif
348 FILE *logfile;
349 FILE *instances_logfile;
350 FILE *data_outfile;
351 int datafile_offset;
352 int gc_name_offset;
353 // In this mode, we are emitting dedupable methods that we encounter
354 gboolean dedup_emit_mode;
355 } MonoAotCompile;
357 typedef struct {
358 int plt_offset;
359 char *symbol, *llvm_symbol, *debug_sym;
360 MonoJumpInfo *ji;
361 gboolean jit_used, llvm_used;
362 } MonoPltEntry;
364 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
365 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
367 /* This points to the current acfg in LLVM mode */
368 static MonoAotCompile *llvm_acfg;
370 #ifdef HAVE_ARRAY_ELEM_INIT
371 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
372 #define MSGSTRFIELD1(line) str##line
373 static const struct msgstr_t {
374 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
375 #include "patch-info.h"
376 #undef PATCH_INFO
377 } opstr = {
378 #define PATCH_INFO(a,b) b,
379 #include "patch-info.h"
380 #undef PATCH_INFO
382 static const gint16 opidx [] = {
383 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
384 #include "patch-info.h"
385 #undef PATCH_INFO
388 static G_GNUC_UNUSED const char*
389 get_patch_name (int info)
391 return (const char*)&opstr + opidx [info];
394 #else
395 #define PATCH_INFO(a,b) b,
396 static const char* const
397 patch_types [MONO_PATCH_INFO_NUM + 1] = {
398 #include "patch-info.h"
399 NULL
402 static G_GNUC_UNUSED const char*
403 get_patch_name (int info)
405 return patch_types [info];
408 #endif
410 static void
411 mono_flush_method_cache (MonoAotCompile *acfg);
413 static void
414 mono_read_method_cache (MonoAotCompile *acfg);
416 static guint32
417 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
419 static char*
420 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
422 static void
423 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
425 static void
426 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
428 static inline gboolean
429 ignore_cfg (MonoCompile *cfg)
431 return !cfg || cfg->skip;
434 static void
435 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
437 FILE *output;
438 va_list args;
440 if (acfg->logfile)
441 output = acfg->logfile;
442 else
443 output = stdout;
445 va_start (args, format);
446 vfprintf (output, format, args);
447 va_end (args);
450 static void
451 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
453 FILE *output;
454 va_list args;
456 if (acfg->logfile)
457 output = acfg->logfile;
458 else
459 output = stderr;
461 va_start (args, format);
462 vfprintf (output, format, args);
463 va_end (args);
466 static void
467 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
469 FILE *output;
470 va_list args;
472 if (mono_error_ok (error))
473 return;
475 if (acfg->logfile)
476 output = acfg->logfile;
477 else
478 output = stderr;
480 va_start (args, format);
481 vfprintf (output, format, args);
482 va_end (args);
483 mono_error_cleanup (error);
485 if (acfg->is_full_aot && fatal) {
486 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
487 exit (1);
491 /* Wrappers around the image writer functions */
493 #define MAX_SYMBOL_SIZE 256
495 static inline const char *
496 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
498 gsize needed_size = length;
500 g_assert (NULL != symbol);
501 g_assert (NULL != mangled_symbol);
502 g_assert (0 != length);
504 #if defined(TARGET_WIN32) && defined(TARGET_X86)
505 if (symbol && '_' != symbol [0]) {
506 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
507 } else {
508 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
510 #else
511 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
512 #endif
514 g_assert (0 <= needed_size && needed_size < length);
515 return mangled_symbol;
518 static inline char *
519 mangle_symbol_alloc (const char * symbol)
521 g_assert (NULL != symbol);
523 #if defined(TARGET_WIN32) && defined(TARGET_X86)
524 if (symbol && '_' != symbol [0]) {
525 return g_strdup_printf ("_%s", symbol);
527 else {
528 return g_strdup_printf ("%s", symbol);
530 #else
531 return g_strdup_printf ("%s", symbol);
532 #endif
535 static inline void
536 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
538 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
541 #if defined(TARGET_WIN32) && defined(TARGET_X86)
543 static inline void
544 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
546 const char * mangled_symbol_name = name;
547 char * mangled_symbol_name_alloc = NULL;
549 if (TRUE == func) {
550 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
551 mangled_symbol_name = mangled_symbol_name_alloc;
554 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
555 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
557 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
559 if (NULL != mangled_symbol_name_alloc) {
560 g_free (mangled_symbol_name_alloc);
564 #else
566 static inline void
567 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
569 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
572 #endif
574 static inline void
575 emit_label (MonoAotCompile *acfg, const char *name)
577 mono_img_writer_emit_label (acfg->w, name);
580 static inline void
581 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
583 mono_img_writer_emit_bytes (acfg->w, buf, size);
586 static inline void
587 emit_string (MonoAotCompile *acfg, const char *value)
589 mono_img_writer_emit_string (acfg->w, value);
592 static inline void
593 emit_line (MonoAotCompile *acfg)
595 mono_img_writer_emit_line (acfg->w);
598 static inline void
599 emit_alignment (MonoAotCompile *acfg, int size)
601 mono_img_writer_emit_alignment (acfg->w, size);
604 static inline void
605 emit_alignment_code (MonoAotCompile *acfg, int size)
607 if (acfg->align_pad_value)
608 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
609 else
610 mono_img_writer_emit_alignment (acfg->w, size);
613 static inline void
614 emit_padding (MonoAotCompile *acfg, int size)
616 int i;
617 guint8 buf [16];
619 if (acfg->align_pad_value) {
620 for (i = 0; i < 16; ++i)
621 buf [i] = acfg->align_pad_value;
622 } else {
623 memset (buf, 0, sizeof (buf));
626 for (i = 0; i < size; i += 16) {
627 if (size - i < 16)
628 emit_bytes (acfg, buf, size - i);
629 else
630 emit_bytes (acfg, buf, 16);
634 static inline void
635 emit_pointer (MonoAotCompile *acfg, const char *target)
637 mono_img_writer_emit_pointer (acfg->w, target);
640 static inline void
641 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
643 if (prefix [0] != '\0') {
644 char *s = g_strdup_printf ("%s%s", prefix, target);
645 mono_img_writer_emit_pointer (acfg->w, s);
646 g_free (s);
647 } else {
648 mono_img_writer_emit_pointer (acfg->w, target);
652 static inline void
653 emit_int16 (MonoAotCompile *acfg, int value)
655 mono_img_writer_emit_int16 (acfg->w, value);
658 static inline void
659 emit_int32 (MonoAotCompile *acfg, int value)
661 mono_img_writer_emit_int32 (acfg->w, value);
664 static inline void
665 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
667 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
670 static inline void
671 emit_zero_bytes (MonoAotCompile *acfg, int num)
673 mono_img_writer_emit_zero_bytes (acfg->w, num);
676 static inline void
677 emit_byte (MonoAotCompile *acfg, guint8 val)
679 mono_img_writer_emit_byte (acfg->w, val);
682 #if defined(TARGET_WIN32) && defined(TARGET_X86)
684 static G_GNUC_UNUSED void
685 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
687 const char * mangled_symbol_name = name;
688 char * mangled_symbol_name_alloc = NULL;
690 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
691 mangled_symbol_name = mangled_symbol_name_alloc;
693 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
694 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
696 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
698 if (NULL != mangled_symbol_name_alloc) {
699 g_free (mangled_symbol_name_alloc);
703 #else
705 static G_GNUC_UNUSED void
706 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
708 mono_img_writer_emit_global (acfg->w, name, func);
711 #endif
713 static inline gboolean
714 link_shared_library (MonoAotCompile *acfg)
716 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
719 static inline gboolean
720 add_to_global_symbol_table (MonoAotCompile *acfg)
722 #ifdef TARGET_WIN32_MSVC
723 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
724 #else
725 return acfg->aot_opts.no_dlsym;
726 #endif
729 static void
730 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
732 if (add_to_global_symbol_table (acfg))
733 g_ptr_array_add (acfg->globals, g_strdup (name));
735 if (acfg->aot_opts.no_dlsym) {
736 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
737 } else {
738 emit_global_inner (acfg, name, func);
742 static void
743 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
745 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
748 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
749 static void
750 emit_info_symbol (MonoAotCompile *acfg, const char *name)
752 char symbol [MAX_SYMBOL_SIZE];
754 if (acfg->llvm) {
755 emit_label (acfg, name);
756 /* LLVM generated code references this */
757 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
758 emit_label (acfg, symbol);
759 emit_global_inner (acfg, symbol, FALSE);
760 } else {
761 emit_label (acfg, name);
765 static void
766 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
768 if (acfg->llvm) {
769 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
770 return;
773 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
774 #ifdef TARGET_MACH
775 /* On apple, all symbols need to be aligned to avoid warnings from ld */
776 emit_alignment (acfg, 4);
777 #endif
778 mono_img_writer_emit_label (acfg->w, name);
779 mono_img_writer_emit_string (acfg->w, value);
782 static G_GNUC_UNUSED void
783 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
785 do {
786 guint8 b = value & 0x7f;
787 value >>= 7;
788 if (value != 0) /* more bytes to come */
789 b |= 0x80;
790 emit_byte (acfg, b);
791 } while (value);
794 static G_GNUC_UNUSED void
795 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
797 gboolean more = 1;
798 gboolean negative = (value < 0);
799 guint32 size = 64;
800 guint8 byte;
802 while (more) {
803 byte = value & 0x7f;
804 value >>= 7;
805 /* the following is unnecessary if the
806 * implementation of >>= uses an arithmetic rather
807 * than logical shift for a signed left operand
809 if (negative)
810 /* sign extend */
811 value |= - ((gint64)1 <<(size - 7));
812 /* sign bit of byte is second high order bit (0x40) */
813 if ((value == 0 && !(byte & 0x40)) ||
814 (value == -1 && (byte & 0x40)))
815 more = 0;
816 else
817 byte |= 0x80;
818 emit_byte (acfg, byte);
822 static G_GNUC_UNUSED void
823 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
825 guint8 *p = buf;
827 do {
828 guint8 b = value & 0x7f;
829 value >>= 7;
830 if (value != 0) /* more bytes to come */
831 b |= 0x80;
832 *p ++ = b;
833 } while (value);
835 *endbuf = p;
838 static G_GNUC_UNUSED void
839 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
841 gboolean more = 1;
842 gboolean negative = (value < 0);
843 guint32 size = 32;
844 guint8 byte;
845 guint8 *p = buf;
847 while (more) {
848 byte = value & 0x7f;
849 value >>= 7;
850 /* the following is unnecessary if the
851 * implementation of >>= uses an arithmetic rather
852 * than logical shift for a signed left operand
854 if (negative)
855 /* sign extend */
856 value |= - (1 <<(size - 7));
857 /* sign bit of byte is second high order bit (0x40) */
858 if ((value == 0 && !(byte & 0x40)) ||
859 (value == -1 && (byte & 0x40)))
860 more = 0;
861 else
862 byte |= 0x80;
863 *p ++= byte;
866 *endbuf = p;
869 static void
870 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
872 // FIXME: Big-endian
873 buf [0] = (val >> 0) & 0xff;
874 buf [1] = (val >> 8) & 0xff;
875 buf [2] = (val >> 16) & 0xff;
876 buf [3] = (val >> 24) & 0xff;
878 *endbuf = buf + 4;
881 static void
882 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
884 buf [0] = (val >> 0) & 0xff;
885 buf [1] = (val >> 8) & 0xff;
887 *endbuf = buf + 2;
890 static void
891 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
893 int len = strlen (s);
895 memcpy (buf, s, len + 1);
896 *endbuf = buf + len + 1;
899 static void
900 emit_unset_mode (MonoAotCompile *acfg)
902 mono_img_writer_emit_unset_mode (acfg->w);
905 static G_GNUC_UNUSED void
906 emit_set_thumb_mode (MonoAotCompile *acfg)
908 emit_unset_mode (acfg);
909 fprintf (acfg->fp, ".code 16\n");
912 static G_GNUC_UNUSED void
913 emit_set_arm_mode (MonoAotCompile *acfg)
915 emit_unset_mode (acfg);
916 fprintf (acfg->fp, ".code 32\n");
919 static inline void
920 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
922 #ifdef TARGET_ARM64
923 int i;
925 g_assert (size % 4 == 0);
926 emit_unset_mode (acfg);
927 for (i = 0; i < size; i += 4)
928 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
929 #else
930 emit_bytes (acfg, buf, size);
931 #endif
934 /* ARCHITECTURE SPECIFIC CODE */
936 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
937 #define EMIT_DWARF_INFO 1
938 #endif
940 #ifdef TARGET_WIN32_MSVC
941 #undef EMIT_DWARF_INFO
942 #define EMIT_WIN32_CODEVIEW_INFO
943 #endif
945 #ifdef EMIT_WIN32_UNWIND_INFO
946 static UnwindInfoSectionCacheItem *
947 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
949 static void
950 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
952 static void
953 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
955 static void
956 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
957 #endif
959 static void
960 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
962 #ifdef EMIT_WIN32_UNWIND_INFO
963 free_unwind_info_section_cache_win32 (acfg);
964 #endif
967 static void
968 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
970 #ifdef EMIT_WIN32_UNWIND_INFO
971 gboolean own_unwind_ops = FALSE;
972 if (!unwind_ops) {
973 unwind_ops = mono_unwind_get_cie_program ();
974 own_unwind_ops = TRUE;
977 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
979 if (own_unwind_ops)
980 mono_free_unwind_info (unwind_ops);
981 #endif
984 #if defined(TARGET_ARM)
985 #define AOT_FUNC_ALIGNMENT 4
986 #else
987 #define AOT_FUNC_ALIGNMENT 16
988 #endif
990 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
991 #define PPC_LD_OP "ld"
992 #define PPC_LDX_OP "ldx"
993 #else
994 #define PPC_LD_OP "lwz"
995 #define PPC_LDX_OP "lwzx"
996 #endif
998 #ifdef TARGET_X86_64_WIN32_MSVC
999 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
1000 #elif TARGET_AMD64
1001 #define AOT_TARGET_STR "AMD64"
1002 #endif
1004 #ifdef TARGET_ARM
1005 #ifdef TARGET_MACH
1006 #define AOT_TARGET_STR "ARM (MACH)"
1007 #else
1008 #define AOT_TARGET_STR "ARM (!MACH)"
1009 #endif
1010 #endif
1012 #ifdef TARGET_ARM64
1013 #ifdef TARGET_MACH
1014 #define AOT_TARGET_STR "ARM64 (MACH)"
1015 #else
1016 #define AOT_TARGET_STR "ARM64 (!MACH)"
1017 #endif
1018 #endif
1020 #ifdef TARGET_POWERPC64
1021 #ifdef __mono_ilp32__
1022 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1023 #else
1024 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1025 #endif
1026 #else
1027 #ifdef TARGET_POWERPC
1028 #ifdef __mono_ilp32__
1029 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1030 #else
1031 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1032 #endif
1033 #endif
1034 #endif
1036 #ifdef TARGET_X86
1037 #ifdef TARGET_WIN32
1038 #define AOT_TARGET_STR "X86 (WIN32)"
1039 #else
1040 #define AOT_TARGET_STR "X86"
1041 #endif
1042 #endif
1044 #ifndef AOT_TARGET_STR
1045 #define AOT_TARGET_STR ""
1046 #endif
1048 static void
1049 arch_init (MonoAotCompile *acfg)
1051 acfg->llc_args = g_string_new ("");
1052 acfg->as_args = g_string_new ("");
1053 acfg->llvm_owriter_supported = TRUE;
1056 * The prefix LLVM likes to put in front of symbol names on darwin.
1057 * The mach-os specs require this for globals, but LLVM puts them in front of all
1058 * symbols. We need to handle this, since we need to refer to LLVM generated
1059 * symbols.
1061 acfg->llvm_label_prefix = "";
1062 acfg->user_symbol_prefix = "";
1064 #if defined(TARGET_X86)
1065 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
1066 #endif
1068 #if defined(TARGET_AMD64)
1069 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
1070 /* NOP */
1071 acfg->align_pad_value = 0x90;
1072 #endif
1074 #ifdef TARGET_ARM
1075 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1076 g_string_append (acfg->llc_args, "-mattr=+v6");
1077 } else {
1078 #if defined(ARM_FPU_VFP_HARD)
1079 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1080 g_string_append (acfg->as_args, " -mfpu=vfp3");
1081 #elif defined(ARM_FPU_VFP)
1082 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1083 g_string_append (acfg->as_args, " -mfpu=vfp3");
1084 #else
1085 g_string_append (acfg->llc_args, " -soft-float");
1086 #endif
1088 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1089 acfg->thumb_mixed = TRUE;
1091 if (acfg->aot_opts.mtriple)
1092 mono_arch_set_target (acfg->aot_opts.mtriple);
1093 #endif
1095 #ifdef TARGET_ARM64
1096 acfg->inst_directive = ".inst";
1097 if (acfg->aot_opts.mtriple)
1098 mono_arch_set_target (acfg->aot_opts.mtriple);
1099 #endif
1101 #ifdef TARGET_MACH
1102 acfg->user_symbol_prefix = "_";
1103 acfg->llvm_label_prefix = "_";
1104 acfg->inst_directive = ".word";
1105 acfg->need_no_dead_strip = TRUE;
1106 acfg->aot_opts.gnu_asm = TRUE;
1107 #endif
1109 #if defined(__linux__) && !defined(TARGET_ARM)
1110 acfg->need_pt_gnu_stack = TRUE;
1111 #endif
1113 #ifdef MONOTOUCH
1114 acfg->global_symbols = TRUE;
1115 #endif
1117 #ifdef TARGET_ANDROID
1118 acfg->llvm_owriter_supported = FALSE;
1119 #endif
1122 #ifdef TARGET_ARM64
1125 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1126 static void
1127 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1129 int offset;
1131 g_assert (acfg->fp);
1132 emit_unset_mode (acfg);
1133 /* r16==ip0 */
1134 offset = (int)(got_slot * sizeof (gpointer));
1135 #ifdef TARGET_MACH
1136 /* clang's integrated assembler */
1137 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1138 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1139 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1140 #else
1141 /* Linux GAS */
1142 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1143 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1144 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1145 #endif
1148 static void
1149 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1151 int reg;
1153 g_assert (acfg->fp);
1154 emit_unset_mode (acfg);
1156 /* ldr rt, target */
1157 reg = arm_get_ldr_lit_reg (code);
1159 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1160 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1161 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1163 *code_size = 12;
1166 static void
1167 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1169 g_assert (acfg->fp);
1170 emit_unset_mode (acfg);
1171 if (ji && ji->relocation == MONO_R_ARM64_B) {
1172 fprintf (acfg->fp, "b %s\n", target);
1173 } else {
1174 if (ji)
1175 g_assert (ji->relocation == MONO_R_ARM64_BL);
1176 fprintf (acfg->fp, "bl %s\n", target);
1178 *call_size = 4;
1181 static void
1182 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1184 int reg;
1186 /* ldr rt, target */
1187 reg = arm_get_ldr_lit_reg (code);
1188 arm64_emit_load_got_slot (acfg, reg, got_slot);
1189 *code_size = 12;
1192 static void
1193 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1195 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1196 fprintf (acfg->fp, "br x16\n");
1197 /* Used by mono_aot_get_plt_info_offset () */
1198 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1201 static void
1202 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1204 guint8 buf [256];
1205 guint8 *code;
1206 int imm;
1208 /* The common code */
1209 code = buf;
1210 imm = pagesize;
1211 /* The trampoline address is in IP0 */
1212 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1213 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1214 /* Compute the data slot address */
1215 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1216 /* Trampoline argument */
1217 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1218 /* Address */
1219 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1220 arm_brx (code, ARMREG_IP0);
1222 /* Emit it */
1223 emit_code_bytes (acfg, buf, code - buf);
1225 *size = code - buf;
1228 static void
1229 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1231 guint8 buf [256];
1232 guint8 *code;
1233 int i, count;
1235 count = (pagesize - common_tramp_size) / specific_tramp_size;
1236 for (i = 0; i < count; ++i) {
1237 code = buf;
1238 arm_adrx (code, ARMREG_IP0, code);
1239 /* Branch to the generic code */
1240 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1241 /* This has to be 2 pointers long */
1242 arm_nop (code);
1243 arm_nop (code);
1244 g_assert (code - buf == specific_tramp_size);
1245 emit_code_bytes (acfg, buf, code - buf);
1249 static void
1250 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1252 guint8 buf [128];
1253 guint8 *code;
1254 guint8 *labels [16];
1255 int common_tramp_size;
1256 int specific_tramp_size = 2 * 8;
1257 int imm, pagesize;
1258 char symbol [128];
1260 if (!acfg->aot_opts.use_trampolines_page)
1261 return;
1263 #ifdef TARGET_MACH
1264 /* Have to match the target pagesize */
1265 pagesize = 16384;
1266 #else
1267 pagesize = mono_pagesize ();
1268 #endif
1269 acfg->tramp_page_size = pagesize;
1271 /* The specific trampolines */
1272 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1273 emit_alignment (acfg, pagesize);
1274 emit_global (acfg, symbol, TRUE);
1275 emit_label (acfg, symbol);
1277 /* The common code */
1278 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1279 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1281 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1283 /* The rgctx trampolines */
1284 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1285 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1286 emit_alignment (acfg, pagesize);
1287 emit_global (acfg, symbol, TRUE);
1288 emit_label (acfg, symbol);
1290 /* The common code */
1291 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1292 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1294 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1296 /* The gsharedvt arg trampolines */
1297 /* These are the same as the specific trampolines */
1298 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1299 emit_alignment (acfg, pagesize);
1300 emit_global (acfg, symbol, TRUE);
1301 emit_label (acfg, symbol);
1303 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1304 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1306 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1308 /* The IMT trampolines */
1309 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1310 emit_alignment (acfg, pagesize);
1311 emit_global (acfg, symbol, TRUE);
1312 emit_label (acfg, symbol);
1314 code = buf;
1315 imm = pagesize;
1316 /* The trampoline address is in IP0 */
1317 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1318 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1319 /* Compute the data slot address */
1320 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1321 /* Trampoline argument */
1322 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1324 /* Same as arch_emit_imt_trampoline () */
1325 labels [0] = code;
1326 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1327 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1328 labels [1] = code;
1329 arm_bcc (code, ARMCOND_EQ, 0);
1331 /* End-of-loop check */
1332 labels [2] = code;
1333 arm_cbzx (code, ARMREG_IP0, 0);
1335 /* Loop footer */
1336 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1337 arm_b (code, labels [0]);
1339 /* Match */
1340 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1341 /* Load vtable slot addr */
1342 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1343 /* Load vtable slot */
1344 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1345 arm_brx (code, ARMREG_IP0);
1347 /* No match */
1348 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1349 /* Load fail addr */
1350 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1351 arm_brx (code, ARMREG_IP0);
1353 emit_code_bytes (acfg, buf, code - buf);
1355 common_tramp_size = code - buf;
1356 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1358 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1361 static void
1362 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1364 /* Load argument from second GOT slot */
1365 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1366 /* Load generic trampoline address from first GOT slot */
1367 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1368 fprintf (acfg->fp, "br x16\n");
1369 *tramp_size = 7 * 4;
1372 static void
1373 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1375 emit_unset_mode (acfg);
1376 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1377 fprintf (acfg->fp, "b %s\n", call_target);
1380 static void
1381 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1383 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1385 /* Load argument from first GOT slot */
1386 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1387 /* Load generic trampoline address from second GOT slot */
1388 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1389 fprintf (acfg->fp, "br x16\n");
1390 *tramp_size = 7 * 4;
1393 static void
1394 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1396 guint8 buf [128];
1397 guint8 *code, *labels [16];
1399 /* Load parameter from GOT slot into ip1 */
1400 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1402 code = buf;
1403 labels [0] = code;
1404 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1405 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1406 labels [1] = code;
1407 arm_bcc (code, ARMCOND_EQ, 0);
1409 /* End-of-loop check */
1410 labels [2] = code;
1411 arm_cbzx (code, ARMREG_IP0, 0);
1413 /* Loop footer */
1414 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1415 arm_b (code, labels [0]);
1417 /* Match */
1418 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1419 /* Load vtable slot addr */
1420 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1421 /* Load vtable slot */
1422 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1423 arm_brx (code, ARMREG_IP0);
1425 /* No match */
1426 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1427 /* Load fail addr */
1428 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1429 arm_brx (code, ARMREG_IP0);
1431 emit_code_bytes (acfg, buf, code - buf);
1433 *tramp_size = code - buf + (3 * 4);
1436 static void
1437 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1439 /* Similar to the specific trampolines, but the address is in the second slot */
1440 /* Load argument from first GOT slot */
1441 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1442 /* Load generic trampoline address from second GOT slot */
1443 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1444 fprintf (acfg->fp, "br x16\n");
1445 *tramp_size = 7 * 4;
1449 #endif
1451 #ifdef MONO_ARCH_AOT_SUPPORTED
1453 * arch_emit_direct_call:
1455 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1456 * calling code.
1458 static void
1459 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1461 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1462 /* Need to make sure this is exactly 5 bytes long */
1463 emit_unset_mode (acfg);
1464 fprintf (acfg->fp, "call %s\n", target);
1465 *call_size = 5;
1466 #elif defined(TARGET_ARM)
1467 emit_unset_mode (acfg);
1468 if (thumb)
1469 fprintf (acfg->fp, "blx %s\n", target);
1470 else
1471 fprintf (acfg->fp, "bl %s\n", target);
1472 *call_size = 4;
1473 #elif defined(TARGET_ARM64)
1474 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1475 #elif defined(TARGET_POWERPC)
1476 emit_unset_mode (acfg);
1477 fprintf (acfg->fp, "bl %s\n", target);
1478 *call_size = 4;
1479 #else
1480 g_assert_not_reached ();
1481 #endif
1483 #endif
1486 * PPC32 design:
1487 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1488 * the GOT pointer.
1489 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1490 * in in the 2. slot of every GOT, and require every method to place the GOT
1491 * address in r30, even when it doesn't access the GOT otherwise. This way,
1492 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1496 * PPC64 design:
1497 * PPC64 uses function descriptors which greatly complicate all code, since
1498 * these are used very inconsistently in the runtime. Some functions like
1499 * mono_compile_method () return ftn descriptors, while others like the
1500 * trampoline creation functions do not.
1501 * We assume that all GOT slots contain function descriptors, and create
1502 * descriptors in aot-runtime.c when needed.
1503 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1504 * from function descriptors, we could do the same, but it would require
1505 * rewriting all the ppc/aot code to handle function descriptors properly.
1506 * So instead, we use the same approach as on PPC32.
1507 * This is a horrible mess, but fixing it would probably lead to an even bigger
1508 * one.
1512 * X86 design:
1513 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1516 #ifdef MONO_ARCH_AOT_SUPPORTED
1518 * arch_emit_got_offset:
1520 * The memory pointed to by CODE should hold native code for computing the GOT
1521 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1522 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1524 static void
1525 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1527 #if defined(TARGET_POWERPC64)
1528 emit_unset_mode (acfg);
1530 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1531 * unsupported relocations. So we store the got address into the .Lgot_addr
1532 * symbol which is in the text segment, compute its address, and load it.
1534 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1535 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1536 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1537 fprintf (acfg->fp, "add 30, 30, 0\n");
1538 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1539 acfg->label_generator ++;
1540 *code_size = 16;
1541 #elif defined(TARGET_POWERPC)
1542 emit_unset_mode (acfg);
1543 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1544 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1545 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1546 acfg->label_generator ++;
1547 *code_size = 8;
1548 #else
1549 guint32 offset = mono_arch_get_patch_offset (code);
1550 emit_bytes (acfg, code, offset);
1551 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1553 *code_size = offset + 4;
1554 #endif
1558 * arch_emit_got_access:
1560 * The memory pointed to by CODE should hold native code for loading a GOT
1561 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1562 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1564 static void
1565 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1567 #ifdef TARGET_AMD64
1568 /* mov reg, got+offset(%rip) */
1569 if (acfg->llvm) {
1570 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1571 int dreg;
1572 int rex_r;
1574 /* Decode reg, see amd64_mov_reg_membase () */
1575 rex_r = code [0] & AMD64_REX_R;
1576 g_assert (code [0] == 0x49 + rex_r);
1577 g_assert (code [1] == 0x8b);
1578 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1580 emit_unset_mode (acfg);
1581 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1582 *code_size = 7;
1583 } else {
1584 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1585 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1586 *code_size = mono_arch_get_patch_offset (code) + 4;
1588 #elif defined(TARGET_X86)
1589 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1590 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1591 *code_size = mono_arch_get_patch_offset (code) + 4;
1592 #elif defined(TARGET_ARM)
1593 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1594 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1595 *code_size = mono_arch_get_patch_offset (code) + 4;
1596 #elif defined(TARGET_ARM64)
1597 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1598 arm64_emit_got_access (acfg, code, got_slot, code_size);
1599 #elif defined(TARGET_POWERPC)
1601 guint8 buf [32];
1603 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1604 code = buf;
1605 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1606 g_assert (code - buf == 8);
1607 emit_bytes (acfg, buf, code - buf);
1608 *code_size = code - buf;
1610 #else
1611 g_assert_not_reached ();
1612 #endif
1615 #endif
1617 #ifdef MONO_ARCH_AOT_SUPPORTED
1619 * arch_emit_objc_selector_ref:
1621 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1623 static void
1624 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1626 #if defined(TARGET_ARM)
1627 char symbol1 [MAX_SYMBOL_SIZE];
1628 char symbol2 [MAX_SYMBOL_SIZE];
1629 int lindex = acfg->objc_selector_index_2 ++;
1631 /* Emit ldr.imm/b */
1632 emit_bytes (acfg, code, 8);
1634 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1635 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1637 emit_label (acfg, symbol1);
1638 mono_img_writer_emit_unset_mode (acfg->w);
1639 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1641 *code_size = 12;
1642 #elif defined(TARGET_ARM64)
1643 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1644 #else
1645 g_assert_not_reached ();
1646 #endif
1648 #endif
1651 * arch_emit_plt_entry:
1653 * Emit code for the PLT entry.
1654 * The plt entry should look like this:
1655 * <indirect jump to GOT_SYMBOL + OFFSET>
1656 * <INFO_OFFSET embedded into the instruction stream>
1658 static void
1659 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1661 #if defined(TARGET_X86)
1662 /* jmp *<offset>(%ebx) */
1663 emit_byte (acfg, 0xff);
1664 emit_byte (acfg, 0xa3);
1665 emit_int32 (acfg, offset);
1666 /* Used by mono_aot_get_plt_info_offset */
1667 emit_int32 (acfg, info_offset);
1668 #elif defined(TARGET_AMD64)
1669 emit_unset_mode (acfg);
1670 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1671 /* Used by mono_aot_get_plt_info_offset */
1672 emit_int32 (acfg, info_offset);
1673 acfg->stats.plt_size += 10;
1674 #elif defined(TARGET_ARM)
1675 guint8 buf [256];
1676 guint8 *code;
1678 code = buf;
1679 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1680 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1681 emit_bytes (acfg, buf, code - buf);
1682 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1683 /* Used by mono_aot_get_plt_info_offset */
1684 emit_int32 (acfg, info_offset);
1685 #elif defined(TARGET_ARM64)
1686 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1687 #elif defined(TARGET_POWERPC)
1688 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1689 emit_unset_mode (acfg);
1690 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1691 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1692 fprintf (acfg->fp, "add 11, 11, 30\n");
1693 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1694 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1695 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1696 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1697 #endif
1698 fprintf (acfg->fp, "mtctr 11\n");
1699 fprintf (acfg->fp, "bctr\n");
1700 emit_int32 (acfg, info_offset);
1701 #else
1702 g_assert_not_reached ();
1703 #endif
1707 * arch_emit_llvm_plt_entry:
1709 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1710 * This is only needed on arm to handle thumb interop.
1712 static void
1713 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1715 #if defined(TARGET_ARM)
1716 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1717 /* The caller already transitioned to thumb */
1718 /* The code below should be 12 bytes long */
1719 /* clang has trouble encoding these instructions, so emit the binary */
1720 #if 0
1721 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1722 /* thumb can't encode ld pc, [pc, ip] */
1723 fprintf (acfg->fp, "add ip, pc, ip\n");
1724 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1725 fprintf (acfg->fp, "bx ip\n");
1726 #endif
1727 emit_set_thumb_mode (acfg);
1728 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1729 fprintf (acfg->fp, ".2byte 0x44fc\n");
1730 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1731 fprintf (acfg->fp, ".2byte 0x4760\n");
1732 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1733 emit_int32 (acfg, info_offset);
1734 emit_unset_mode (acfg);
1735 emit_set_arm_mode (acfg);
1736 #else
1737 g_assert_not_reached ();
1738 #endif
1741 /* Save unwind_info in the module and emit the offset to the information at symbol */
1742 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1744 guint32 uw_offset, encoded_len;
1745 guint8 *encoded;
1747 emit_section_change (acfg, RODATA_SECT, 0);
1748 emit_global (acfg, symbol, FALSE);
1749 emit_label (acfg, symbol);
1751 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1752 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1753 g_free (encoded);
1754 emit_int32 (acfg, uw_offset);
1758 * arch_emit_specific_trampoline_pages:
1760 * Emits a page full of trampolines: each trampoline uses its own address to
1761 * lookup both the generic trampoline code and the data argument.
1762 * This page can be remapped in process multiple times so we can get an
1763 * unlimited number of trampolines.
1764 * Specifically this implementation uses the following trick: two memory pages
1765 * are allocated, with the first containing the data and the second containing the trampolines.
1766 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1767 * implementation does all the lifting.
1768 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1769 * on the arm 32 bit system.
1771 static void
1772 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1774 #if defined(TARGET_ARM)
1775 guint8 buf [128];
1776 guint8 *code;
1777 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1778 int i;
1779 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1780 GSList *unwind_ops = NULL;
1781 #define COMMON_TRAMP_SIZE 16
1782 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1783 int imm8, rot_amount;
1784 char symbol [128];
1786 if (!acfg->aot_opts.use_trampolines_page)
1787 return;
1789 acfg->tramp_page_size = pagesize;
1791 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1792 emit_alignment (acfg, pagesize);
1793 emit_global (acfg, symbol, TRUE);
1794 emit_label (acfg, symbol);
1796 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1797 code = buf;
1798 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1799 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1800 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1801 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1802 ARM_NOP (code);
1803 g_assert (code - buf == COMMON_TRAMP_SIZE);
1805 /* Emit it */
1806 emit_bytes (acfg, buf, code - buf);
1808 for (i = 0; i < count; ++i) {
1809 code = buf;
1810 ARM_PUSH (code, 0x5fff);
1811 ARM_BL (code, 0);
1812 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1813 g_assert (code - buf == 8);
1814 emit_bytes (acfg, buf, code - buf);
1817 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1818 * the instruction pointer address, so the generic trampoline at the start of the page
1819 * subtracts 4096 to get to the data page and loads the values
1820 * We again fit the generic trampiline in 16 bytes.
1822 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1823 emit_global (acfg, symbol, TRUE);
1824 emit_label (acfg, symbol);
1825 code = buf;
1826 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1827 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1828 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1829 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1830 ARM_NOP (code);
1831 g_assert (code - buf == COMMON_TRAMP_SIZE);
1833 /* Emit it */
1834 emit_bytes (acfg, buf, code - buf);
1836 for (i = 0; i < count; ++i) {
1837 code = buf;
1838 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1839 ARM_B (code, 0);
1840 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1841 g_assert (code - buf == 8);
1842 emit_bytes (acfg, buf, code - buf);
1846 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1848 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1849 emit_global (acfg, symbol, TRUE);
1850 emit_label (acfg, symbol);
1851 code = buf;
1852 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1853 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1854 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1855 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1856 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1857 g_assert (code - buf == COMMON_TRAMP_SIZE);
1858 /* Emit it */
1859 emit_bytes (acfg, buf, code - buf);
1861 for (i = 0; i < count; ++i) {
1862 code = buf;
1863 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1864 ARM_B (code, 0);
1865 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1866 g_assert (code - buf == 8);
1867 emit_bytes (acfg, buf, code - buf);
1870 /* now the imt trampolines: each specific trampolines puts in the ip register
1871 * the instruction pointer address, so the generic trampoline at the start of the page
1872 * subtracts 4096 to get to the data page and loads the values
1874 #define IMT_TRAMP_SIZE 72
1875 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1876 emit_global (acfg, symbol, TRUE);
1877 emit_label (acfg, symbol);
1878 code = buf;
1879 /* Need at least two free registers, plus a slot for storing the pc */
1880 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1882 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1883 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1884 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1886 /* The IMT method is in v5, r0 has the imt array address */
1888 loop_start = code;
1889 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1890 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1891 imt_found_check = code;
1892 ARM_B_COND (code, ARMCOND_EQ, 0);
1894 /* End-of-loop check */
1895 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1896 loop_end_check = code;
1897 ARM_B_COND (code, ARMCOND_EQ, 0);
1899 /* Loop footer */
1900 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1901 loop_branch_back = code;
1902 ARM_B (code, 0);
1903 arm_patch (loop_branch_back, loop_start);
1905 /* Match */
1906 arm_patch (imt_found_check, code);
1907 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1908 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1909 /* Save it to the third stack slot */
1910 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1911 /* Restore the registers and branch */
1912 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1914 /* No match */
1915 arm_patch (loop_end_check, code);
1916 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1917 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1918 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1919 ARM_NOP (code);
1921 /* Emit it */
1922 g_assert (code - buf == IMT_TRAMP_SIZE);
1923 emit_bytes (acfg, buf, code - buf);
1925 for (i = 0; i < count; ++i) {
1926 code = buf;
1927 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1928 ARM_B (code, 0);
1929 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1930 g_assert (code - buf == 8);
1931 emit_bytes (acfg, buf, code - buf);
1934 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1935 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1936 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1937 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1939 /* Unwind info for specifc trampolines */
1940 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1941 /* We unwind to the original caller, from the stack, since lr is clobbered */
1942 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1943 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1944 save_unwind_info (acfg, symbol, unwind_ops);
1945 mono_free_unwind_info (unwind_ops);
1947 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1948 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1949 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1950 save_unwind_info (acfg, symbol, unwind_ops);
1951 mono_free_unwind_info (unwind_ops);
1953 /* Unwind info for rgctx trampolines */
1954 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1955 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1956 save_unwind_info (acfg, symbol, unwind_ops);
1958 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1959 save_unwind_info (acfg, symbol, unwind_ops);
1960 mono_free_unwind_info (unwind_ops);
1962 /* Unwind info for gsharedvt trampolines */
1963 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1964 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1965 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1966 save_unwind_info (acfg, symbol, unwind_ops);
1967 mono_free_unwind_info (unwind_ops);
1969 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1970 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1971 save_unwind_info (acfg, symbol, unwind_ops);
1972 mono_free_unwind_info (unwind_ops);
1974 /* Unwind info for imt trampolines */
1975 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1976 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1977 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1978 save_unwind_info (acfg, symbol, unwind_ops);
1979 mono_free_unwind_info (unwind_ops);
1981 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1982 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1983 save_unwind_info (acfg, symbol, unwind_ops);
1984 mono_free_unwind_info (unwind_ops);
1985 #elif defined(TARGET_ARM64)
1986 arm64_emit_specific_trampoline_pages (acfg);
1987 #endif
1991 * arch_emit_specific_trampoline:
1993 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1994 * two GOT slots which contain the generic trampoline address and the trampoline
1995 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1997 static void
1998 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2001 * The trampolines created here are variations of the specific
2002 * trampolines created in mono_arch_create_specific_trampoline (). The
2003 * differences are:
2004 * - the generic trampoline address is taken from a got slot.
2005 * - the offset of the got slot where the trampoline argument is stored
2006 * is embedded in the instruction stream, and the generic trampoline
2007 * can load the argument by loading the offset, adding it to the
2008 * address of the trampoline to get the address of the got slot, and
2009 * loading the argument from there.
2010 * - all the trampolines should be of the same length.
2012 #if defined(TARGET_AMD64)
2013 /* This should be exactly 8 bytes long */
2014 *tramp_size = 8;
2015 /* call *<offset>(%rip) */
2016 if (acfg->llvm) {
2017 emit_unset_mode (acfg);
2018 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2019 emit_zero_bytes (acfg, 2);
2020 } else {
2021 emit_byte (acfg, '\x41');
2022 emit_byte (acfg, '\xff');
2023 emit_byte (acfg, '\x15');
2024 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2025 emit_zero_bytes (acfg, 1);
2027 #elif defined(TARGET_ARM)
2028 guint8 buf [128];
2029 guint8 *code;
2031 /* This should be exactly 20 bytes long */
2032 *tramp_size = 20;
2033 code = buf;
2034 ARM_PUSH (code, 0x5fff);
2035 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2036 /* Load the value from the GOT */
2037 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2038 /* Branch to it */
2039 ARM_BLX_REG (code, ARMREG_R1);
2041 g_assert (code - buf == 16);
2043 /* Emit it */
2044 emit_bytes (acfg, buf, code - buf);
2046 * Only one offset is needed, since the second one would be equal to the
2047 * first one.
2049 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
2050 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
2051 #elif defined(TARGET_ARM64)
2052 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2053 #elif defined(TARGET_POWERPC)
2054 guint8 buf [128];
2055 guint8 *code;
2057 *tramp_size = 4;
2058 code = buf;
2061 * PPC has no ip relative addressing, so we need to compute the address
2062 * of the mscorlib got. That is slow and complex, so instead, we store it
2063 * in the second got slot of every aot image. The caller already computed
2064 * the address of its got and placed it into r30.
2066 emit_unset_mode (acfg);
2067 /* Load mscorlib got address */
2068 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2069 /* Load generic trampoline address */
2070 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2071 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2072 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2073 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2074 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2075 #endif
2076 fprintf (acfg->fp, "mtctr 11\n");
2077 /* Load trampoline argument */
2078 /* On ppc, we pass it normally to the generic trampoline */
2079 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2080 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2081 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2082 /* Branch to generic trampoline */
2083 fprintf (acfg->fp, "bctr\n");
2085 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2086 *tramp_size = 10 * 4;
2087 #else
2088 *tramp_size = 9 * 4;
2089 #endif
2090 #elif defined(TARGET_X86)
2091 guint8 buf [128];
2092 guint8 *code;
2094 /* Similar to the PPC code above */
2096 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2098 code = buf;
2099 /* Load mscorlib got address */
2100 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2101 /* Push trampoline argument */
2102 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2103 /* Load generic trampoline address */
2104 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2105 /* Branch to generic trampoline */
2106 x86_jump_reg (code, X86_ECX);
2108 emit_bytes (acfg, buf, code - buf);
2110 *tramp_size = 17;
2111 g_assert (code - buf == *tramp_size);
2112 #else
2113 g_assert_not_reached ();
2114 #endif
2118 * arch_emit_unbox_trampoline:
2120 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2121 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2123 static void
2124 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2126 #if defined(TARGET_AMD64)
2127 guint8 buf [32];
2128 guint8 *code;
2129 int this_reg;
2131 this_reg = mono_arch_get_this_arg_reg (NULL);
2132 code = buf;
2133 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2135 emit_bytes (acfg, buf, code - buf);
2136 /* jump <method> */
2137 if (acfg->llvm) {
2138 emit_unset_mode (acfg);
2139 fprintf (acfg->fp, "jmp %s\n", call_target);
2140 } else {
2141 emit_byte (acfg, '\xe9');
2142 emit_symbol_diff (acfg, call_target, ".", -4);
2144 #elif defined(TARGET_X86)
2145 guint8 buf [32];
2146 guint8 *code;
2147 int this_pos = 4;
2149 code = buf;
2151 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2153 emit_bytes (acfg, buf, code - buf);
2155 /* jump <method> */
2156 emit_byte (acfg, '\xe9');
2157 emit_symbol_diff (acfg, call_target, ".", -4);
2158 #elif defined(TARGET_ARM)
2159 guint8 buf [128];
2160 guint8 *code;
2162 if (acfg->thumb_mixed && cfg->compile_llvm) {
2163 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2164 fprintf (acfg->fp, "b %s\n", call_target);
2165 fprintf (acfg->fp, ".arm\n");
2166 fprintf (acfg->fp, ".align 2\n");
2167 return;
2170 code = buf;
2172 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2174 emit_bytes (acfg, buf, code - buf);
2175 /* jump to method */
2176 if (acfg->thumb_mixed && cfg->compile_llvm)
2177 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2178 else
2179 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2180 #elif defined(TARGET_ARM64)
2181 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2182 #elif defined(TARGET_POWERPC)
2183 int this_pos = 3;
2185 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2186 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2187 #else
2188 g_assert_not_reached ();
2189 #endif
2193 * arch_emit_static_rgctx_trampoline:
2195 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2196 * two GOT slots which contain the rgctx argument, and the method to jump to.
2197 * TRAMP_SIZE is set to the size of the emitted trampoline.
2198 * These kinds of trampolines cannot be enumerated statically, since there could
2199 * be one trampoline per method instantiation, so we emit the same code for all
2200 * trampolines, and parameterize them using two GOT slots.
2202 static void
2203 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2205 #if defined(TARGET_AMD64)
2206 /* This should be exactly 13 bytes long */
2207 *tramp_size = 13;
2209 if (acfg->llvm) {
2210 emit_unset_mode (acfg);
2211 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2212 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2213 } else {
2214 /* mov <OFFSET>(%rip), %r10 */
2215 emit_byte (acfg, '\x4d');
2216 emit_byte (acfg, '\x8b');
2217 emit_byte (acfg, '\x15');
2218 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2220 /* jmp *<offset>(%rip) */
2221 emit_byte (acfg, '\xff');
2222 emit_byte (acfg, '\x25');
2223 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2225 #elif defined(TARGET_ARM)
2226 guint8 buf [128];
2227 guint8 *code;
2229 /* This should be exactly 24 bytes long */
2230 *tramp_size = 24;
2231 code = buf;
2232 /* Load rgctx value */
2233 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2234 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2235 /* Load branch addr + branch */
2236 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2237 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2239 g_assert (code - buf == 16);
2241 /* Emit it */
2242 emit_bytes (acfg, buf, code - buf);
2243 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2244 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2245 #elif defined(TARGET_ARM64)
2246 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2247 #elif defined(TARGET_POWERPC)
2248 guint8 buf [128];
2249 guint8 *code;
2251 *tramp_size = 4;
2252 code = buf;
2255 * PPC has no ip relative addressing, so we need to compute the address
2256 * of the mscorlib got. That is slow and complex, so instead, we store it
2257 * in the second got slot of every aot image. The caller already computed
2258 * the address of its got and placed it into r30.
2260 emit_unset_mode (acfg);
2261 /* Load mscorlib got address */
2262 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2263 /* Load rgctx */
2264 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2265 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2266 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2267 /* Load target address */
2268 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2269 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2270 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2271 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2272 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2273 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2274 #endif
2275 fprintf (acfg->fp, "mtctr 11\n");
2276 /* Branch to the target address */
2277 fprintf (acfg->fp, "bctr\n");
2279 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2280 *tramp_size = 11 * 4;
2281 #else
2282 *tramp_size = 9 * 4;
2283 #endif
2285 #elif defined(TARGET_X86)
2286 guint8 buf [128];
2287 guint8 *code;
2289 /* Similar to the PPC code above */
2291 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2293 code = buf;
2294 /* Load mscorlib got address */
2295 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2296 /* Load arg */
2297 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2298 /* Branch to the target address */
2299 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2301 emit_bytes (acfg, buf, code - buf);
2303 *tramp_size = 15;
2304 g_assert (code - buf == *tramp_size);
2305 #else
2306 g_assert_not_reached ();
2307 #endif
2311 * arch_emit_imt_trampoline:
2313 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2314 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2315 * key is the IMT key, and ptr holds the address of a memory location holding
2316 * the address to branch to if the IMT arg matches the key. The array is
2317 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2318 * fail_tramp.
2319 * TRAMP_SIZE is set to the size of the emitted trampoline.
2321 static void
2322 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2324 #if defined(TARGET_AMD64)
2325 guint8 *buf, *code;
2326 guint8 *labels [16];
2327 guint8 mov_buf[3];
2328 guint8 *mov_buf_ptr = mov_buf;
2330 const int kSizeOfMove = 7;
2332 code = buf = (guint8 *)g_malloc (256);
2334 /* FIXME: Optimize this, i.e. use binary search etc. */
2335 /* Maybe move the body into a separate function (slower, but much smaller) */
2337 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2339 if (acfg->llvm) {
2340 emit_unset_mode (acfg);
2341 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2344 labels [0] = code;
2345 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2346 labels [1] = code;
2347 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2349 /* Check key */
2350 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2351 labels [2] = code;
2352 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2354 /* Loop footer */
2355 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2356 amd64_jump_code (code, labels [0]);
2358 /* Match */
2359 mono_amd64_patch (labels [2], code);
2360 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2361 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2363 /* No match */
2364 mono_amd64_patch (labels [1], code);
2365 /* Load fail tramp */
2366 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2367 /* Check if there is a fail tramp */
2368 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2369 labels [3] = code;
2370 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2371 /* Jump to fail tramp */
2372 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2374 /* Fail */
2375 mono_amd64_patch (labels [3], code);
2376 x86_breakpoint (code);
2378 if (!acfg->llvm) {
2379 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2380 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2381 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2382 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2383 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2384 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2386 emit_bytes (acfg, buf, code - buf);
2388 *tramp_size = code - buf + kSizeOfMove;
2390 g_free (buf);
2392 #elif defined(TARGET_X86)
2393 guint8 *buf, *code;
2394 guint8 *labels [16];
2396 code = buf = g_malloc (256);
2398 /* Allocate a temporary stack slot */
2399 x86_push_reg (code, X86_EAX);
2400 /* Save EAX */
2401 x86_push_reg (code, X86_EAX);
2403 /* Load mscorlib got address */
2404 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2405 /* Load arg */
2406 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2408 labels [0] = code;
2409 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2410 labels [1] = code;
2411 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2413 /* Check key */
2414 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2415 labels [2] = code;
2416 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2418 /* Loop footer */
2419 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2420 x86_jump_code (code, labels [0]);
2422 /* Match */
2423 mono_x86_patch (labels [2], code);
2424 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2425 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2426 /* Save the target address to the temporary stack location */
2427 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2428 /* Restore EAX */
2429 x86_pop_reg (code, X86_EAX);
2430 /* Jump to the target address */
2431 x86_ret (code);
2433 /* No match */
2434 mono_x86_patch (labels [1], code);
2435 /* Load fail tramp */
2436 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2437 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2438 labels [3] = code;
2439 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2440 /* Jump to fail tramp */
2441 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2442 x86_pop_reg (code, X86_EAX);
2443 x86_ret (code);
2445 /* Fail */
2446 mono_x86_patch (labels [3], code);
2447 x86_breakpoint (code);
2449 emit_bytes (acfg, buf, code - buf);
2451 *tramp_size = code - buf;
2453 g_free (buf);
2455 #elif defined(TARGET_ARM)
2456 guint8 buf [128];
2457 guint8 *code, *code2, *labels [16];
2459 code = buf;
2461 /* The IMT method is in v5 */
2463 /* Need at least two free registers, plus a slot for storing the pc */
2464 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2465 labels [0] = code;
2466 /* Load the parameter from the GOT */
2467 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2468 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2470 labels [1] = code;
2471 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2472 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2473 labels [2] = code;
2474 ARM_B_COND (code, ARMCOND_EQ, 0);
2476 /* End-of-loop check */
2477 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2478 labels [3] = code;
2479 ARM_B_COND (code, ARMCOND_EQ, 0);
2481 /* Loop footer */
2482 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2483 labels [4] = code;
2484 ARM_B (code, 0);
2485 arm_patch (labels [4], labels [1]);
2487 /* Match */
2488 arm_patch (labels [2], code);
2489 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2490 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2491 /* Save it to the third stack slot */
2492 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2493 /* Restore the registers and branch */
2494 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2496 /* No match */
2497 arm_patch (labels [3], code);
2498 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2499 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2500 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2502 /* Fixup offset */
2503 code2 = labels [0];
2504 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2506 emit_bytes (acfg, buf, code - buf);
2507 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2509 *tramp_size = code - buf + 4;
2510 #elif defined(TARGET_ARM64)
2511 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2512 #elif defined(TARGET_POWERPC)
2513 guint8 buf [128];
2514 guint8 *code, *labels [16];
2516 code = buf;
2518 /* Load the mscorlib got address */
2519 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2520 /* Load the parameter from the GOT */
2521 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2522 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2524 /* Load and check key */
2525 labels [1] = code;
2526 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2527 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2528 labels [2] = code;
2529 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2531 /* End-of-loop check */
2532 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2533 labels [3] = code;
2534 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2536 /* Loop footer */
2537 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2538 labels [4] = code;
2539 ppc_b (code, 0);
2540 mono_ppc_patch (labels [4], labels [1]);
2542 /* Match */
2543 mono_ppc_patch (labels [2], code);
2544 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2545 /* r12 now contains the value of the vtable slot */
2546 /* this is not a function descriptor on ppc64 */
2547 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2548 ppc_mtctr (code, ppc_r12);
2549 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2551 /* Fail */
2552 mono_ppc_patch (labels [3], code);
2553 /* FIXME: */
2554 ppc_break (code);
2556 *tramp_size = code - buf;
2558 emit_bytes (acfg, buf, code - buf);
2559 #else
2560 g_assert_not_reached ();
2561 #endif
2565 #if defined (TARGET_AMD64)
2567 static void
2568 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2571 g_assert (acfg->fp);
2572 emit_unset_mode (acfg);
2574 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2577 #endif
2581 * arch_emit_gsharedvt_arg_trampoline:
2583 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2584 * two GOT slots which contain the argument, and the code to jump to.
2585 * TRAMP_SIZE is set to the size of the emitted trampoline.
2586 * These kinds of trampolines cannot be enumerated statically, since there could
2587 * be one trampoline per method instantiation, so we emit the same code for all
2588 * trampolines, and parameterize them using two GOT slots.
2590 static void
2591 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2593 #if defined(TARGET_X86)
2594 guint8 buf [128];
2595 guint8 *code;
2597 /* Similar to the PPC code above */
2599 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2601 code = buf;
2602 /* Load mscorlib got address */
2603 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2604 /* Load arg */
2605 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2606 /* Branch to the target address */
2607 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2609 emit_bytes (acfg, buf, code - buf);
2611 *tramp_size = 15;
2612 g_assert (code - buf == *tramp_size);
2613 #elif defined(TARGET_ARM)
2614 guint8 buf [128];
2615 guint8 *code;
2617 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2618 /* Similar to arch_emit_specific_trampoline () */
2619 *tramp_size = 24;
2620 code = buf;
2621 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2622 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2623 /* Load the arg value from the GOT */
2624 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2625 /* Load the addr from the GOT */
2626 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2627 /* Branch to it */
2628 ARM_BX (code, ARMREG_R1);
2630 g_assert (code - buf == 20);
2632 /* Emit it */
2633 emit_bytes (acfg, buf, code - buf);
2634 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2635 #elif defined(TARGET_ARM64)
2636 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2637 #elif defined (TARGET_AMD64)
2639 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2640 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2641 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2642 fprintf (acfg->fp, "jmp *%%r11\n");
2644 *tramp_size = 0x11;
2645 #else
2646 g_assert_not_reached ();
2647 #endif
2650 /* END OF ARCH SPECIFIC CODE */
2652 static guint32
2653 mono_get_field_token (MonoClassField *field)
2655 MonoClass *klass = field->parent;
2656 int i;
2658 int fcount = mono_class_get_field_count (klass);
2659 MonoClassField *klass_fields = m_class_get_fields (klass);
2660 for (i = 0; i < fcount; ++i) {
2661 if (field == &klass_fields [i])
2662 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2665 g_assert_not_reached ();
2666 return 0;
2669 static inline void
2670 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2672 guint8 *p = buf;
2674 //printf ("ENCODE: %d 0x%x.\n", value, value);
2677 * Same encoding as the one used in the metadata, extended to handle values
2678 * greater than 0x1fffffff.
2680 if ((value >= 0) && (value <= 127))
2681 *p++ = value;
2682 else if ((value >= 0) && (value <= 16383)) {
2683 p [0] = 0x80 | (value >> 8);
2684 p [1] = value & 0xff;
2685 p += 2;
2686 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2687 p [0] = (value >> 24) | 0xc0;
2688 p [1] = (value >> 16) & 0xff;
2689 p [2] = (value >> 8) & 0xff;
2690 p [3] = value & 0xff;
2691 p += 4;
2693 else {
2694 p [0] = 0xff;
2695 p [1] = (value >> 24) & 0xff;
2696 p [2] = (value >> 16) & 0xff;
2697 p [3] = (value >> 8) & 0xff;
2698 p [4] = value & 0xff;
2699 p += 5;
2701 if (endbuf)
2702 *endbuf = p;
2705 static void
2706 stream_init (MonoDynamicStream *sh)
2708 sh->index = 0;
2709 sh->alloc_size = 4096;
2710 sh->data = (char *)g_malloc (4096);
2712 /* So offsets are > 0 */
2713 sh->data [0] = 0;
2714 sh->index ++;
2717 static void
2718 make_room_in_stream (MonoDynamicStream *stream, int size)
2720 if (size <= stream->alloc_size)
2721 return;
2723 while (stream->alloc_size <= size) {
2724 if (stream->alloc_size < 4096)
2725 stream->alloc_size = 4096;
2726 else
2727 stream->alloc_size *= 2;
2730 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2733 static guint32
2734 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2736 guint32 idx;
2738 make_room_in_stream (stream, stream->index + len);
2739 memcpy (stream->data + stream->index, data, len);
2740 idx = stream->index;
2741 stream->index += len;
2742 return idx;
2746 * add_to_blob:
2748 * Add data to the binary blob inside the aot image. Returns the offset inside the
2749 * blob where the data was stored.
2751 static guint32
2752 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2754 g_assert (!acfg->blob_closed);
2756 if (acfg->blob.alloc_size == 0)
2757 stream_init (&acfg->blob);
2759 return add_stream_data (&acfg->blob, (char*)data, data_len);
2762 static guint32
2763 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2765 char buf [4] = {0};
2766 guint32 count;
2768 if (acfg->blob.alloc_size == 0)
2769 stream_init (&acfg->blob);
2771 count = acfg->blob.index % align;
2773 /* we assume the stream data will be aligned */
2774 if (count)
2775 add_stream_data (&acfg->blob, buf, 4 - count);
2777 return add_stream_data (&acfg->blob, (char*)data, data_len);
2780 /* Emit a table of data into the aot image */
2781 static void
2782 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2784 if (acfg->data_outfile) {
2785 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2786 fwrite (data,1, size, acfg->data_outfile);
2787 acfg->datafile_offset += size;
2788 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2789 int align = 8 - size % 8;
2790 acfg->datafile_offset += align;
2791 guint8 align_buf [16];
2792 memset (&align_buf, 0, sizeof (align_buf));
2793 fwrite (align_buf, align, 1, acfg->data_outfile);
2794 } else if (acfg->llvm) {
2795 mono_llvm_emit_aot_data (symbol, data, size);
2796 } else {
2797 emit_section_change (acfg, RODATA_SECT, 0);
2798 emit_alignment (acfg, 8);
2799 emit_label (acfg, symbol);
2800 emit_bytes (acfg, data, size);
2805 * emit_offset_table:
2807 * Emit a table of increasing offsets in a compact form using differential encoding.
2808 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2809 * group size, the more compact the table becomes, but the slower it becomes to compute
2810 * a given entry. Returns the size of the table.
2812 static guint32
2813 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2815 gint32 current_offset;
2816 int i, buf_size, ngroups, index_entry_size;
2817 guint8 *p, *buf;
2818 guint8 *data_p, *data_buf;
2819 guint32 *index_offsets;
2821 ngroups = (noffsets + (group_size - 1)) / group_size;
2823 index_offsets = g_new0 (guint32, ngroups);
2825 buf_size = noffsets * 4;
2826 p = buf = (guint8 *)g_malloc0 (buf_size);
2828 current_offset = 0;
2829 for (i = 0; i < noffsets; ++i) {
2830 //printf ("D: %d -> %d\n", i, offsets [i]);
2831 if ((i % group_size) == 0) {
2832 index_offsets [i / group_size] = p - buf;
2833 /* Emit the full value for these entries */
2834 encode_value (offsets [i], p, &p);
2835 } else {
2836 /* The offsets are allowed to be non-increasing */
2837 //g_assert (offsets [i] >= current_offset);
2838 encode_value (offsets [i] - current_offset, p, &p);
2840 current_offset = offsets [i];
2842 data_buf = buf;
2843 data_p = p;
2845 if (ngroups && index_offsets [ngroups - 1] < 65000)
2846 index_entry_size = 2;
2847 else
2848 index_entry_size = 4;
2850 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2851 p = buf = (guint8 *)g_malloc0 (buf_size);
2853 /* Emit the header */
2854 encode_int (noffsets, p, &p);
2855 encode_int (group_size, p, &p);
2856 encode_int (ngroups, p, &p);
2857 encode_int (index_entry_size, p, &p);
2859 /* Emit the index */
2860 for (i = 0; i < ngroups; ++i) {
2861 if (index_entry_size == 2)
2862 encode_int16 (index_offsets [i], p, &p);
2863 else
2864 encode_int (index_offsets [i], p, &p);
2866 /* Emit the data */
2867 memcpy (p, data_buf, data_p - data_buf);
2868 p += data_p - data_buf;
2870 g_assert (p - buf <= buf_size);
2872 emit_aot_data (acfg, table, symbol, buf, p - buf);
2874 g_free (buf);
2875 g_free (data_buf);
2877 return (int)(p - buf);
2880 static guint32
2881 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2883 guint32 index;
2885 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2886 if (index)
2887 return index - 1;
2888 else {
2889 index = g_hash_table_size (cfg->image_hash);
2890 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2891 g_ptr_array_add (cfg->image_table, image);
2892 return index;
2896 static guint32
2897 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2899 int i;
2900 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2902 /* FIXME: Search referenced images as well */
2903 if (!acfg->typespec_classes) {
2904 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2905 for (i = 0; i < len; i++) {
2906 ERROR_DECL (error);
2907 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2908 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
2909 if (!is_ok (error)) {
2910 mono_error_cleanup (error);
2911 continue;
2913 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2916 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2919 static void
2920 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2922 static void
2923 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2925 static void
2926 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2928 static void
2929 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2931 static void
2932 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2934 guint8 *p = buf;
2937 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2938 * information.
2941 if (mono_class_is_ginst (klass)) {
2942 guint32 token;
2943 g_assert (m_class_get_type_token (klass));
2945 /* Find a typespec for a class if possible */
2946 token = find_typespec_for_class (acfg, klass);
2947 if (token) {
2948 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2949 encode_value (token, p, &p);
2950 } else {
2951 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2952 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2953 static int count = 0;
2954 guint8 *p1 = p;
2956 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2957 encode_klass_ref (acfg, gclass, p, &p);
2958 encode_ginst (acfg, inst, p, &p);
2960 count += p - p1;
2962 } else if (m_class_get_type_token (klass)) {
2963 int iindex = get_image_index (acfg, m_class_get_image (klass));
2965 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
2966 if (iindex == 0) {
2967 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2968 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
2969 } else {
2970 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2971 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
2972 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
2974 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
2975 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
2976 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
2978 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2980 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2981 if (par->gshared_constraint) {
2982 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2983 encode_type (acfg, par->gshared_constraint, p, &p);
2984 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
2985 } else {
2986 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
2987 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
2989 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2991 if (!container->is_anonymous) {
2992 encode_value (container->is_method, p, &p);
2993 if (container->is_method)
2994 encode_method_ref (acfg, container->owner.method, p, &p);
2995 else
2996 encode_klass_ref (acfg, container->owner.klass, p, &p);
2999 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3000 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3001 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3002 } else {
3003 /* Array class */
3004 g_assert (m_class_get_rank (klass) > 0);
3005 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3006 encode_value (m_class_get_rank (klass), p, &p);
3007 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3009 *endbuf = p;
3013 * encode_klass_ref:
3015 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3016 * standard metadata encoding.
3018 static void
3019 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3021 gboolean shared = FALSE;
3024 * The encoding of generic instances is large so emit them only once.
3026 if (mono_class_is_ginst (klass)) {
3027 guint32 token;
3028 g_assert (m_class_get_type_token (klass));
3030 /* Find a typespec for a class if possible */
3031 token = find_typespec_for_class (acfg, klass);
3032 if (!token)
3033 shared = TRUE;
3034 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3035 shared = TRUE;
3038 if (shared) {
3039 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3040 guint8 *buf2, *p;
3042 if (!offset) {
3043 buf2 = (guint8 *)g_malloc (1024);
3044 p = buf2;
3046 encode_klass_ref_inner (acfg, klass, p, &p);
3047 g_assert (p - buf2 < 1024);
3049 offset = add_to_blob (acfg, buf2, p - buf2);
3050 g_free (buf2);
3052 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3053 } else {
3054 offset --;
3057 p = buf;
3058 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3059 encode_value (offset, p, &p);
3060 *endbuf = p;
3061 return;
3064 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3067 static void
3068 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3070 guint32 token = mono_get_field_token (field);
3071 guint8 *p = buf;
3073 encode_klass_ref (cfg, field->parent, p, &p);
3074 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3075 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3076 *endbuf = p;
3079 static void
3080 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3082 guint8 *p = buf;
3083 int i;
3085 encode_value (inst->type_argc, p, &p);
3086 for (i = 0; i < inst->type_argc; ++i)
3087 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3088 *endbuf = p;
3091 static void
3092 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3094 guint8 *p = buf;
3095 MonoGenericInst *inst;
3097 inst = context->class_inst;
3098 if (inst) {
3099 g_assert (inst->type_argc);
3100 encode_ginst (acfg, inst, p, &p);
3101 } else {
3102 encode_value (0, p, &p);
3104 inst = context->method_inst;
3105 if (inst) {
3106 g_assert (inst->type_argc);
3107 encode_ginst (acfg, inst, p, &p);
3108 } else {
3109 encode_value (0, p, &p);
3111 *endbuf = p;
3114 static void
3115 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3117 guint8 *p = buf;
3119 // Change memory allocation in decode_type if you change
3120 g_assert (!t->has_cmods);
3122 /* t->attrs can be ignored */
3123 //g_assert (t->attrs == 0);
3125 if (t->pinned) {
3126 *p = MONO_TYPE_PINNED;
3127 ++p;
3129 if (t->byref) {
3130 *p = MONO_TYPE_BYREF;
3131 ++p;
3134 *p = t->type;
3135 p ++;
3137 switch (t->type) {
3138 case MONO_TYPE_VOID:
3139 case MONO_TYPE_BOOLEAN:
3140 case MONO_TYPE_CHAR:
3141 case MONO_TYPE_I1:
3142 case MONO_TYPE_U1:
3143 case MONO_TYPE_I2:
3144 case MONO_TYPE_U2:
3145 case MONO_TYPE_I4:
3146 case MONO_TYPE_U4:
3147 case MONO_TYPE_I8:
3148 case MONO_TYPE_U8:
3149 case MONO_TYPE_R4:
3150 case MONO_TYPE_R8:
3151 case MONO_TYPE_I:
3152 case MONO_TYPE_U:
3153 case MONO_TYPE_STRING:
3154 case MONO_TYPE_OBJECT:
3155 case MONO_TYPE_TYPEDBYREF:
3156 break;
3157 case MONO_TYPE_VALUETYPE:
3158 case MONO_TYPE_CLASS:
3159 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3160 break;
3161 case MONO_TYPE_SZARRAY:
3162 encode_klass_ref (acfg, t->data.klass, p, &p);
3163 break;
3164 case MONO_TYPE_PTR:
3165 encode_type (acfg, t->data.type, p, &p);
3166 break;
3167 case MONO_TYPE_GENERICINST: {
3168 MonoClass *gclass = t->data.generic_class->container_class;
3169 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3171 encode_klass_ref (acfg, gclass, p, &p);
3172 encode_ginst (acfg, inst, p, &p);
3173 break;
3175 case MONO_TYPE_ARRAY: {
3176 MonoArrayType *array = t->data.array;
3177 int i;
3179 encode_klass_ref (acfg, array->eklass, p, &p);
3180 encode_value (array->rank, p, &p);
3181 encode_value (array->numsizes, p, &p);
3182 for (i = 0; i < array->numsizes; ++i)
3183 encode_value (array->sizes [i], p, &p);
3184 encode_value (array->numlobounds, p, &p);
3185 for (i = 0; i < array->numlobounds; ++i)
3186 encode_value (array->lobounds [i], p, &p);
3187 break;
3189 case MONO_TYPE_VAR:
3190 case MONO_TYPE_MVAR:
3191 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3192 break;
3193 default:
3194 g_assert_not_reached ();
3197 *endbuf = p;
3200 static void
3201 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3203 guint8 *p = buf;
3204 guint32 flags = 0;
3205 int i;
3207 /* Similar to the metadata encoding */
3208 if (sig->generic_param_count)
3209 flags |= 0x10;
3210 if (sig->hasthis)
3211 flags |= 0x20;
3212 if (sig->explicit_this)
3213 flags |= 0x40;
3214 flags |= (sig->call_convention & 0x0F);
3216 *p = flags;
3217 ++p;
3218 if (sig->generic_param_count)
3219 encode_value (sig->generic_param_count, p, &p);
3220 encode_value (sig->param_count, p, &p);
3222 encode_type (acfg, sig->ret, p, &p);
3223 for (i = 0; i < sig->param_count; ++i) {
3224 if (sig->sentinelpos == i) {
3225 *p = MONO_TYPE_SENTINEL;
3226 ++p;
3228 encode_type (acfg, sig->params [i], p, &p);
3231 *endbuf = p;
3234 #define MAX_IMAGE_INDEX 250
3236 static void
3237 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3239 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3240 guint32 token = method->token;
3241 MonoJumpInfoToken *ji;
3242 guint8 *p = buf;
3245 * The encoding for most methods is as follows:
3246 * - image index encoded as a leb128
3247 * - token index encoded as a leb128
3248 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3249 * types of method encodings.
3252 /* Mark methods which can't use aot trampolines because they need the further
3253 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3255 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3256 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3257 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3259 if (method->wrapper_type) {
3260 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3262 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3264 encode_value (method->wrapper_type, p, &p);
3266 switch (method->wrapper_type) {
3267 case MONO_WRAPPER_REMOTING_INVOKE:
3268 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3269 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3270 MonoMethod *m;
3272 m = mono_marshal_method_from_wrapper (method);
3273 g_assert (m);
3274 encode_method_ref (acfg, m, p, &p);
3275 break;
3277 case MONO_WRAPPER_PROXY_ISINST:
3278 case MONO_WRAPPER_LDFLD:
3279 case MONO_WRAPPER_LDFLDA:
3280 case MONO_WRAPPER_STFLD: {
3281 g_assert (info);
3282 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3283 break;
3285 case MONO_WRAPPER_ALLOC: {
3286 /* The GC name is saved once in MonoAotFileInfo */
3287 g_assert (info->d.alloc.alloc_type != -1);
3288 encode_value (info->d.alloc.alloc_type, p, &p);
3289 break;
3291 case MONO_WRAPPER_WRITE_BARRIER: {
3292 g_assert (info);
3293 break;
3295 case MONO_WRAPPER_STELEMREF: {
3296 g_assert (info);
3297 encode_value (info->subtype, p, &p);
3298 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3299 encode_value (info->d.virtual_stelemref.kind, p, &p);
3300 break;
3302 case MONO_WRAPPER_UNKNOWN: {
3303 g_assert (info);
3304 encode_value (info->subtype, p, &p);
3305 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3306 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3307 encode_klass_ref (acfg, method->klass, p, &p);
3308 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3309 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3310 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3311 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3312 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3313 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3314 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3315 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3316 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3317 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3318 break;
3320 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3321 g_assert (info);
3322 encode_value (info->subtype, p, &p);
3323 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3324 strcpy ((char*)p, method->name);
3325 p += strlen (method->name) + 1;
3326 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3327 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3328 } else {
3329 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3330 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3332 break;
3334 case MONO_WRAPPER_SYNCHRONIZED: {
3335 MonoMethod *m;
3337 m = mono_marshal_method_from_wrapper (method);
3338 g_assert (m);
3339 g_assert (m != method);
3340 encode_method_ref (acfg, m, p, &p);
3341 break;
3343 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3344 g_assert (info);
3345 encode_value (info->subtype, p, &p);
3347 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3348 encode_value (info->d.element_addr.rank, p, &p);
3349 encode_value (info->d.element_addr.elem_size, p, &p);
3350 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3351 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3352 } else {
3353 g_assert_not_reached ();
3355 break;
3357 case MONO_WRAPPER_CASTCLASS: {
3358 g_assert (info);
3359 encode_value (info->subtype, p, &p);
3360 break;
3362 case MONO_WRAPPER_RUNTIME_INVOKE: {
3363 g_assert (info);
3364 encode_value (info->subtype, p, &p);
3365 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3366 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3367 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3368 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3369 break;
3371 case MONO_WRAPPER_DELEGATE_INVOKE:
3372 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3373 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3374 if (method->is_inflated) {
3375 /* These wrappers are identified by their class */
3376 encode_value (1, p, &p);
3377 encode_klass_ref (acfg, method->klass, p, &p);
3378 } else {
3379 MonoMethodSignature *sig = mono_method_signature (method);
3380 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3382 encode_value (0, p, &p);
3383 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3384 encode_value (info ? info->subtype : 0, p, &p);
3385 encode_signature (acfg, sig, p, &p);
3387 break;
3389 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3390 g_assert (info);
3391 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3392 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3393 break;
3395 default:
3396 g_assert_not_reached ();
3398 } else if (mono_method_signature (method)->is_inflated) {
3400 * This is a generic method, find the original token which referenced it and
3401 * encode that.
3402 * Obtain the token from information recorded by the JIT.
3404 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3405 if (ji) {
3406 image_index = get_image_index (acfg, ji->image);
3407 g_assert (image_index < MAX_IMAGE_INDEX);
3408 token = ji->token;
3410 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3411 encode_value (image_index, p, &p);
3412 encode_value (token, p, &p);
3413 } else {
3414 MonoMethod *declaring;
3415 MonoGenericContext *context = mono_method_get_context (method);
3417 g_assert (method->is_inflated);
3418 declaring = ((MonoMethodInflated*)method)->declaring;
3421 * This might be a non-generic method of a generic instance, which
3422 * doesn't have a token since the reference is generated by the JIT
3423 * like Nullable:Box/Unbox, or by generic sharing.
3425 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3426 /* Encode the klass */
3427 encode_klass_ref (acfg, method->klass, p, &p);
3428 /* Encode the method */
3429 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3430 g_assert (image_index < MAX_IMAGE_INDEX);
3431 g_assert (declaring->token);
3432 token = declaring->token;
3433 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3434 encode_value (image_index, p, &p);
3435 encode_value (token, p, &p);
3436 encode_generic_context (acfg, context, p, &p);
3438 } else if (token == 0) {
3439 /* This might be a method of a constructed type like int[,].Set */
3440 /* Obtain the token from information recorded by the JIT */
3441 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3442 if (ji) {
3443 image_index = get_image_index (acfg, ji->image);
3444 g_assert (image_index < MAX_IMAGE_INDEX);
3445 token = ji->token;
3447 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3448 encode_value (image_index, p, &p);
3449 encode_value (token, p, &p);
3450 } else {
3451 /* Array methods */
3452 g_assert (m_class_get_rank (method->klass));
3454 /* Encode directly */
3455 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3456 encode_klass_ref (acfg, method->klass, p, &p);
3457 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == m_class_get_rank (method->klass))
3458 encode_value (0, p, &p);
3459 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == m_class_get_rank (method->klass) * 2)
3460 encode_value (1, p, &p);
3461 else if (!strcmp (method->name, "Get"))
3462 encode_value (2, p, &p);
3463 else if (!strcmp (method->name, "Address"))
3464 encode_value (3, p, &p);
3465 else if (!strcmp (method->name, "Set"))
3466 encode_value (4, p, &p);
3467 else
3468 g_assert_not_reached ();
3470 } else {
3471 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3473 if (image_index >= MONO_AOT_METHODREF_MIN) {
3474 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3475 encode_value (image_index, p, &p);
3476 encode_value (mono_metadata_token_index (token), p, &p);
3477 } else {
3478 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3481 *endbuf = p;
3484 static gint
3485 compare_patches (gconstpointer a, gconstpointer b)
3487 int i, j;
3489 i = (*(MonoJumpInfo**)a)->ip.i;
3490 j = (*(MonoJumpInfo**)b)->ip.i;
3492 if (i < j)
3493 return -1;
3494 else
3495 if (i > j)
3496 return 1;
3497 else
3498 return 0;
3501 static G_GNUC_UNUSED char*
3502 patch_to_string (MonoJumpInfo *patch_info)
3504 GString *str;
3506 str = g_string_new ("");
3508 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3510 switch (patch_info->type) {
3511 case MONO_PATCH_INFO_VTABLE:
3512 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3513 break;
3514 default:
3515 break;
3517 g_string_append_printf (str, ")");
3518 return g_string_free (str, FALSE);
3522 * is_plt_patch:
3524 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3525 * PLT entry.
3527 static inline gboolean
3528 is_plt_patch (MonoJumpInfo *patch_info)
3530 switch (patch_info->type) {
3531 case MONO_PATCH_INFO_METHOD:
3532 case MONO_PATCH_INFO_INTERNAL_METHOD:
3533 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3534 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3535 case MONO_PATCH_INFO_RGCTX_FETCH:
3536 return TRUE;
3537 default:
3538 return FALSE;
3543 * get_plt_symbol:
3545 * Return the symbol identifying the plt entry PLT_OFFSET.
3547 static char*
3548 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3550 #ifdef TARGET_MACH
3552 * The Apple linker reorganizes object files, so it doesn't like branches to local
3553 * labels, since those have no relocations.
3555 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3556 #else
3557 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3558 #endif
3562 * get_plt_entry:
3564 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3566 static MonoPltEntry*
3567 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3569 MonoPltEntry *res;
3570 gboolean synchronized = FALSE;
3571 static int synchronized_symbol_idx;
3573 if (!is_plt_patch (patch_info))
3574 return NULL;
3576 if (!acfg->patch_to_plt_entry [patch_info->type])
3577 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3578 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3580 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3582 * Allocate a separate PLT slot for each such patch, since some plt
3583 * entries will refer to the method itself, and some will refer to the
3584 * wrapper.
3586 res = NULL;
3587 synchronized = TRUE;
3590 if (!res) {
3591 MonoJumpInfo *new_ji;
3593 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3595 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3596 res->plt_offset = acfg->plt_offset;
3597 res->ji = new_ji;
3598 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3599 if (acfg->aot_opts.write_symbols)
3600 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3601 if (synchronized) {
3602 /* Avoid duplicate symbols because we don't cache */
3603 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3604 if (res->debug_sym)
3605 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3606 synchronized_symbol_idx ++;
3608 if (res->debug_sym)
3609 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3610 else
3611 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3613 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3615 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3617 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3618 //mono_print_ji (patch_info); printf ("\n");
3619 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3621 acfg->plt_offset ++;
3624 return res;
3628 * get_got_offset:
3630 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3631 * JI could be found if it exists, otherwise allocates a new one.
3633 static guint32
3634 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3636 guint32 got_offset;
3637 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3639 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3640 if (got_offset)
3641 return got_offset - 1;
3643 if (llvm) {
3644 got_offset = acfg->llvm_got_offset;
3645 acfg->llvm_got_offset ++;
3646 } else {
3647 got_offset = acfg->got_offset;
3648 acfg->got_offset ++;
3651 acfg->stats.got_slots ++;
3652 acfg->stats.got_slot_types [ji->type] ++;
3654 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3655 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3656 g_ptr_array_add (info->got_patches, ji);
3658 return got_offset;
3661 /* Add a method to the list of methods which need to be emitted */
3662 static void
3663 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3665 g_assert (method);
3666 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3667 g_ptr_array_add (acfg->methods, method);
3668 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3669 acfg->nmethods = acfg->methods->len + 1;
3672 if (method->wrapper_type || extra)
3673 g_ptr_array_add (acfg->extra_methods, method);
3676 static gboolean
3677 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3679 /* One instantiation with valuetypes is generated for each async method */
3680 if (m_class_get_image (method->klass) == mono_defaults.corlib && (!strcmp (m_class_get_name (method->klass), "AsyncMethodBuilderCore") || !strcmp (m_class_get_name (method->klass), "AsyncVoidMethodBuilder")))
3681 return TRUE;
3682 else
3683 return FALSE;
3686 static guint32
3687 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3689 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3691 g_assert (index);
3693 return index - 1;
3696 static int
3697 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3699 int index;
3701 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3702 if (index)
3703 return index - 1;
3705 index = acfg->method_index;
3706 add_method_with_index (acfg, method, index, extra);
3708 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3710 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3712 acfg->method_index ++;
3714 return index;
3717 static int
3718 add_method (MonoAotCompile *acfg, MonoMethod *method)
3720 return add_method_full (acfg, method, FALSE, 0);
3723 static void
3724 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
3726 g_assert (acfg->dedup_stats);
3728 char *name = mono_aot_get_mangled_method_name (method);
3729 g_assert (name);
3731 // For stats
3732 char *stats_name = g_strdup (name);
3734 g_assert (acfg->dedup_cache);
3736 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
3737 // This AOTCompile owns this method
3738 // We do this to decide whether to write it to disk
3739 // during a dedup run (first phase, where we skip).
3741 // If never changed, then maybe can avoid a recompile
3742 // of the cache.
3744 // Files not read in during last phase.
3745 acfg->dedup_cache_changed = TRUE;
3747 // owns name
3748 g_hash_table_insert (acfg->dedup_cache, name, method);
3749 } else {
3750 // owns name
3751 g_free (name);
3754 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
3755 count++;
3756 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
3759 static void
3760 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3762 ERROR_DECL (error);
3763 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
3764 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
3765 mono_error_assert_ok (error);
3767 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
3768 /* Use the gsharedvt version */
3769 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
3770 mono_error_assert_ok (error);
3773 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
3774 mono_dedup_cache_method (acfg, method);
3776 if (!acfg->dedup_emit_mode)
3777 return;
3780 if (acfg->aot_opts.log_generics)
3781 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3783 add_method_full (acfg, method, TRUE, depth);
3786 static void
3787 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3789 add_extra_method_with_depth (acfg, method, 0);
3792 static void
3793 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3795 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3796 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3797 MonoMethod *wrapper;
3798 char *name;
3800 if (!callinfo->sig)
3801 return;
3803 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3804 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3805 g_free (name);
3807 add_method (acfg, wrapper);
3810 static MonoMethod*
3811 get_runtime_invoke_sig (MonoMethodSignature *sig)
3813 MonoMethodBuilder *mb;
3814 MonoMethod *m;
3816 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3817 m = mono_mb_create_method (mb, sig, 16);
3818 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3819 mono_mb_free (mb);
3820 return invoke;
3823 static MonoMethod*
3824 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3826 return mono_marshal_get_runtime_invoke (method, virtual_);
3829 static gboolean
3830 can_marshal_struct (MonoClass *klass)
3832 MonoClassField *field;
3833 gboolean can_marshal = TRUE;
3834 gpointer iter = NULL;
3835 MonoMarshalType *info;
3836 int i;
3838 if (mono_class_is_auto_layout (klass))
3839 return FALSE;
3841 info = mono_marshal_load_type_info (klass);
3843 /* Only allow a few field types to avoid asserts in the marshalling code */
3844 while ((field = mono_class_get_fields (klass, &iter))) {
3845 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3846 continue;
3848 switch (field->type->type) {
3849 case MONO_TYPE_I4:
3850 case MONO_TYPE_U4:
3851 case MONO_TYPE_I1:
3852 case MONO_TYPE_U1:
3853 case MONO_TYPE_BOOLEAN:
3854 case MONO_TYPE_I2:
3855 case MONO_TYPE_U2:
3856 case MONO_TYPE_CHAR:
3857 case MONO_TYPE_I8:
3858 case MONO_TYPE_U8:
3859 case MONO_TYPE_I:
3860 case MONO_TYPE_U:
3861 case MONO_TYPE_PTR:
3862 case MONO_TYPE_R4:
3863 case MONO_TYPE_R8:
3864 case MONO_TYPE_STRING:
3865 break;
3866 case MONO_TYPE_VALUETYPE:
3867 if (!m_class_is_enumtype (mono_class_from_mono_type (field->type)) && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3868 can_marshal = FALSE;
3869 break;
3870 case MONO_TYPE_SZARRAY: {
3871 gboolean has_mspec = FALSE;
3873 if (info) {
3874 for (i = 0; i < info->num_fields; ++i) {
3875 if (info->fields [i].field == field && info->fields [i].mspec)
3876 has_mspec = TRUE;
3879 if (!has_mspec)
3880 can_marshal = FALSE;
3881 break;
3883 default:
3884 can_marshal = FALSE;
3885 break;
3889 /* Special cases */
3890 /* Its hard to compute whenever these can be marshalled or not */
3891 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
3892 return TRUE;
3894 return can_marshal;
3897 static void
3898 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3900 /* Create a vtype instantiation */
3901 MonoGenericContext shared_context;
3902 MonoType **args;
3903 MonoGenericInst *inst;
3904 MonoGenericContainer *container;
3905 MonoClass **constraints;
3906 int i;
3908 memset (ctx, 0, sizeof (MonoGenericContext));
3910 if (mono_class_is_gtd (method->klass)) {
3911 shared_context = mono_class_get_generic_container (method->klass)->context;
3912 inst = shared_context.class_inst;
3914 args = g_new0 (MonoType*, inst->type_argc);
3915 for (i = 0; i < inst->type_argc; ++i) {
3916 args [i] = m_class_get_byval_arg (mono_defaults.int_class);
3918 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3920 if (method->is_generic) {
3921 container = mono_method_get_generic_container (method);
3922 g_assert (!container->is_anonymous && container->is_method);
3923 shared_context = container->context;
3924 inst = shared_context.method_inst;
3926 args = g_new0 (MonoType*, inst->type_argc);
3927 for (i = 0; i < container->type_argc; ++i) {
3928 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
3929 gboolean ref_only = FALSE;
3931 if (info && info->constraints) {
3932 constraints = info->constraints;
3934 while (*constraints) {
3935 MonoClass *cklass = *constraints;
3936 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
3937 /* Inflaring the method with our vtype would not be valid */
3938 ref_only = TRUE;
3939 constraints ++;
3943 if (ref_only)
3944 args [i] = m_class_get_byval_arg (mono_defaults.object_class);
3945 else
3946 args [i] = m_class_get_byval_arg (mono_defaults.int_class);
3948 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3952 static void
3953 add_wrappers (MonoAotCompile *acfg)
3955 MonoMethod *method, *m;
3956 int i, j;
3957 MonoMethodSignature *sig, *csig;
3958 guint32 token;
3961 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3962 * so there is only one wrapper of a given type, or inlining their contents into their
3963 * callers.
3965 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3966 ERROR_DECL (error);
3967 MonoMethod *method;
3968 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3969 gboolean skip = FALSE;
3971 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
3972 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
3974 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3975 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3976 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3977 skip = TRUE;
3979 /* Skip methods which can not be handled by get_runtime_invoke () */
3980 sig = mono_method_signature (method);
3981 if (!sig)
3982 continue;
3983 if ((sig->ret->type == MONO_TYPE_PTR) ||
3984 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3985 skip = TRUE;
3986 if (mono_class_is_open_constructed_type (sig->ret))
3987 skip = TRUE;
3989 for (j = 0; j < sig->param_count; j++) {
3990 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3991 skip = TRUE;
3992 if (mono_class_is_open_constructed_type (sig->params [j]))
3993 skip = TRUE;
3996 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3997 if (!mono_class_is_contextbound (method->klass)) {
3998 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3999 gboolean has_nullable = FALSE;
4001 for (j = 0; j < sig->param_count; j++) {
4002 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
4003 has_nullable = TRUE;
4006 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4007 /* Supported by the dynamic runtime-invoke wrapper */
4008 skip = TRUE;
4010 if (info)
4011 mono_arch_dyn_call_free (info);
4013 #endif
4015 if (acfg->aot_opts.llvm_only)
4016 /* Supported by the gsharedvt based runtime-invoke wrapper */
4017 skip = TRUE;
4019 if (!skip) {
4020 //printf ("%s\n", mono_method_full_name (method, TRUE));
4021 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4025 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4026 int nallocators;
4028 /* Runtime invoke wrappers */
4030 MonoType *void_type = m_class_get_byval_arg (mono_defaults.void_class);
4031 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4033 /* void runtime-invoke () [.cctor] */
4034 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4035 csig->ret = void_type;
4036 add_method (acfg, get_runtime_invoke_sig (csig));
4038 /* void runtime-invoke () [Finalize] */
4039 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4040 csig->hasthis = 1;
4041 csig->ret = void_type;
4042 add_method (acfg, get_runtime_invoke_sig (csig));
4044 /* void runtime-invoke (string) [exception ctor] */
4045 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4046 csig->hasthis = 1;
4047 csig->ret = void_type;
4048 csig->params [0] = string_type;
4049 add_method (acfg, get_runtime_invoke_sig (csig));
4051 /* void runtime-invoke (string, string) [exception ctor] */
4052 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4053 csig->hasthis = 1;
4054 csig->ret = void_type;
4055 csig->params [0] = string_type;
4056 csig->params [1] = string_type;
4057 add_method (acfg, get_runtime_invoke_sig (csig));
4059 /* string runtime-invoke () [Exception.ToString ()] */
4060 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4061 csig->hasthis = 1;
4062 csig->ret = string_type;
4063 add_method (acfg, get_runtime_invoke_sig (csig));
4065 /* void runtime-invoke (string, Exception) [exception ctor] */
4066 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4067 csig->hasthis = 1;
4068 csig->ret = void_type;
4069 csig->params [0] = string_type;
4070 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4071 add_method (acfg, get_runtime_invoke_sig (csig));
4073 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4074 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4075 csig->hasthis = 1;
4076 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4077 csig->params [0] = string_type;
4078 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4079 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4080 add_method (acfg, get_runtime_invoke_sig (csig));
4082 /* runtime-invoke used by finalizers */
4083 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4085 /* This is used by mono_runtime_capture_context () */
4086 method = mono_get_context_capture_method ();
4087 if (method)
4088 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4090 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4091 if (!acfg->aot_opts.llvm_only)
4092 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4093 #endif
4095 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4096 if (acfg->aot_opts.llvm_only) {
4097 int variants;
4099 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4100 for (variants = 0; variants < 4; ++variants) {
4101 for (i = 0; i < 16; ++i) {
4102 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4103 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4105 g_free (sig);
4110 /* stelemref */
4111 add_method (acfg, mono_marshal_get_stelemref ());
4113 /* Managed Allocators */
4114 nallocators = mono_gc_get_managed_allocator_types ();
4115 for (i = 0; i < nallocators; ++i) {
4116 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4117 add_method (acfg, m);
4118 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4119 add_method (acfg, m);
4120 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4121 add_method (acfg, m);
4124 /* write barriers */
4125 if (mono_gc_is_moving ()) {
4126 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4127 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4130 /* Stelemref wrappers */
4132 MonoMethod **wrappers;
4133 int nwrappers;
4135 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4136 for (i = 0; i < nwrappers; ++i)
4137 add_method (acfg, wrappers [i]);
4138 g_free (wrappers);
4141 /* castclass_with_check wrapper */
4142 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4143 /* isinst_with_check wrapper */
4144 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4146 /* JIT icall wrappers */
4147 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4148 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4152 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4153 * we use the original method instead at runtime.
4154 * Since full-aot doesn't support remoting, this is not a problem.
4156 #if 0
4157 /* remoting-invoke wrappers */
4158 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4159 ERROR_DECL (error);
4160 MonoMethodSignature *sig;
4162 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4163 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4164 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4166 sig = mono_method_signature (method);
4168 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4169 m = mono_marshal_get_remoting_invoke_with_check (method);
4171 add_method (acfg, m);
4174 #endif
4176 /* delegate-invoke wrappers */
4177 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4178 ERROR_DECL (error);
4179 MonoClass *klass;
4180 MonoCustomAttrInfo *cattr;
4182 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4183 klass = mono_class_get_checked (acfg->image, token, error);
4185 if (!klass) {
4186 mono_error_cleanup (error);
4187 continue;
4190 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4191 continue;
4193 if (!mono_class_is_gtd (klass)) {
4194 method = mono_get_delegate_invoke (klass);
4196 m = mono_marshal_get_delegate_invoke (method, NULL);
4198 add_method (acfg, m);
4200 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4201 if (method)
4202 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4204 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4205 if (method)
4206 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4208 cattr = mono_custom_attrs_from_class_checked (klass, error);
4209 if (!is_ok (error)) {
4210 mono_error_cleanup (error);
4211 continue;
4214 if (cattr) {
4215 int j;
4217 for (j = 0; j < cattr->num_attrs; ++j)
4218 if (cattr->attrs [j].ctor && (!strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoNativeFunctionWrapperAttribute") || !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedFunctionPointerAttribute")))
4219 break;
4220 if (j < cattr->num_attrs) {
4221 MonoMethod *invoke;
4222 MonoMethod *wrapper;
4223 MonoMethod *del_invoke;
4225 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4226 invoke = mono_get_delegate_invoke (klass);
4227 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4228 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4229 add_method (acfg, wrapper);
4230 add_method (acfg, del_invoke);
4233 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4234 ERROR_DECL (error);
4235 MonoGenericContext ctx;
4236 MonoMethod *inst, *gshared;
4239 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4241 /* Invoke */
4242 method = mono_get_delegate_invoke (klass);
4243 create_gsharedvt_inst (acfg, method, &ctx);
4245 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4246 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4248 m = mono_marshal_get_delegate_invoke (inst, NULL);
4249 g_assert (m->is_inflated);
4251 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4252 mono_error_assert_ok (error);
4254 add_extra_method (acfg, gshared);
4256 /* begin-invoke */
4257 method = mono_get_delegate_begin_invoke (klass);
4258 if (method) {
4259 create_gsharedvt_inst (acfg, method, &ctx);
4261 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4262 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4264 m = mono_marshal_get_delegate_begin_invoke (inst);
4265 g_assert (m->is_inflated);
4267 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4268 mono_error_assert_ok (error);
4270 add_extra_method (acfg, gshared);
4273 /* end-invoke */
4274 method = mono_get_delegate_end_invoke (klass);
4275 if (method) {
4276 create_gsharedvt_inst (acfg, method, &ctx);
4278 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4279 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4281 m = mono_marshal_get_delegate_end_invoke (inst);
4282 g_assert (m->is_inflated);
4284 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4285 mono_error_assert_ok (error);
4287 add_extra_method (acfg, gshared);
4292 /* array access wrappers */
4293 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4294 ERROR_DECL (error);
4295 MonoClass *klass;
4297 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4298 klass = mono_class_get_checked (acfg->image, token, error);
4300 if (!klass) {
4301 mono_error_cleanup (error);
4302 continue;
4305 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4306 MonoMethod *m, *wrapper;
4308 /* Add runtime-invoke wrappers too */
4310 m = mono_class_get_method_from_name (klass, "Get", -1);
4311 g_assert (m);
4312 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4313 add_extra_method (acfg, wrapper);
4314 if (!acfg->aot_opts.llvm_only)
4315 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4317 m = mono_class_get_method_from_name (klass, "Set", -1);
4318 g_assert (m);
4319 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4320 add_extra_method (acfg, wrapper);
4321 if (!acfg->aot_opts.llvm_only)
4322 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4326 /* Synchronized wrappers */
4327 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4328 ERROR_DECL (error);
4329 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4330 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4331 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4333 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4334 if (method->is_generic) {
4335 // FIXME:
4336 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4337 ERROR_DECL (error);
4338 MonoGenericContext ctx;
4339 MonoMethod *inst, *gshared, *m;
4342 * Create a generic wrapper for a generic instance, and AOT that.
4344 create_gsharedvt_inst (acfg, method, &ctx);
4345 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4346 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4347 m = mono_marshal_get_synchronized_wrapper (inst);
4348 g_assert (m->is_inflated);
4349 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4350 mono_error_assert_ok (error);
4352 add_method (acfg, gshared);
4353 } else {
4354 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4359 /* pinvoke wrappers */
4360 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4361 ERROR_DECL (error);
4362 MonoMethod *method;
4363 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4365 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4366 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4368 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4369 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4370 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4373 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4374 if (acfg->aot_opts.llvm_only) {
4375 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4376 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE, FALSE);
4381 /* native-to-managed wrappers */
4382 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4383 ERROR_DECL (error);
4384 MonoMethod *method;
4385 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4386 MonoCustomAttrInfo *cattr;
4387 int j;
4389 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4390 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4393 * Only generate native-to-managed wrappers for methods which have an
4394 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4395 * name to avoid defining a new assembly to contain it.
4397 cattr = mono_custom_attrs_from_method_checked (method, error);
4398 if (!is_ok (error)) {
4399 char *name = mono_method_get_full_name (method);
4400 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4401 g_free (name);
4404 if (cattr) {
4405 for (j = 0; j < cattr->num_attrs; ++j)
4406 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4407 break;
4408 if (j < cattr->num_attrs) {
4409 MonoCustomAttrEntry *e = &cattr->attrs [j];
4410 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4411 const char *p = (const char*)e->data;
4412 const char *named;
4413 int slen, num_named, named_type;
4414 char *n;
4415 MonoType *t;
4416 MonoClass *klass;
4417 char *export_name = NULL;
4418 MonoMethod *wrapper;
4420 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4421 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4422 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See https://docs.microsoft.com/xamarin/ios/internals/limitations#reverse-callbacks",
4423 mono_method_full_name (method, TRUE));
4424 exit (1);
4427 g_assert (sig->param_count == 1);
4428 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type (sig->params [0])), "Type"));
4431 * Decode the cattr manually since we can't create objects
4432 * during aot compilation.
4435 /* Skip prolog */
4436 p += 2;
4438 /* From load_cattr_value () in reflection.c */
4439 slen = mono_metadata_decode_value (p, &p);
4440 n = (char *)g_memdup (p, slen + 1);
4441 n [slen] = 0;
4442 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4443 g_assert (t);
4444 mono_error_assert_ok (error);
4445 g_free (n);
4447 klass = mono_class_from_mono_type (t);
4448 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4450 p += slen;
4452 num_named = read16 (p);
4453 p += 2;
4455 g_assert (num_named < 2);
4456 if (num_named == 1) {
4457 int name_len;
4458 char *name;
4460 /* parse ExportSymbol attribute */
4461 named = p;
4462 named_type = *named;
4463 named += 1;
4464 /* data_type = *named; */
4465 named += 1;
4467 name_len = mono_metadata_decode_blob_size (named, &named);
4468 name = (char *)g_malloc (name_len + 1);
4469 memcpy (name, named, name_len);
4470 name [name_len] = 0;
4471 named += name_len;
4473 g_assert (named_type == 0x54);
4474 g_assert (!strcmp (name, "ExportSymbol"));
4476 /* load_cattr_value (), string case */
4477 g_assert (*named != (char)0xff);
4478 slen = mono_metadata_decode_value (named, &named);
4479 export_name = (char *)g_malloc (slen + 1);
4480 memcpy (export_name, named, slen);
4481 export_name [slen] = 0;
4482 named += slen;
4485 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4486 mono_error_assert_ok (error);
4488 add_method (acfg, wrapper);
4489 if (export_name)
4490 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4492 g_free (cattr);
4495 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4496 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4497 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4501 /* StructureToPtr/PtrToStructure wrappers */
4502 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4503 ERROR_DECL (error);
4504 MonoClass *klass;
4506 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4507 klass = mono_class_get_checked (acfg->image, token, error);
4509 if (!klass) {
4510 mono_error_cleanup (error);
4511 continue;
4514 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4515 !(m_class_get_nested_in (klass) && strstr (m_class_get_name (m_class_get_nested_in (klass)), "<PrivateImplementationDetails>") == m_class_get_name (m_class_get_nested_in (klass)))) {
4516 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4517 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4522 static gboolean
4523 has_type_vars (MonoClass *klass)
4525 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4526 return TRUE;
4527 if (m_class_get_rank (klass))
4528 return has_type_vars (m_class_get_element_class (klass));
4529 if (mono_class_is_ginst (klass)) {
4530 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4531 if (context->class_inst) {
4532 int i;
4534 for (i = 0; i < context->class_inst->type_argc; ++i)
4535 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4536 return TRUE;
4539 if (mono_class_is_gtd (klass))
4540 return TRUE;
4541 return FALSE;
4544 static gboolean
4545 is_vt_inst (MonoGenericInst *inst)
4547 int i;
4549 for (i = 0; i < inst->type_argc; ++i) {
4550 MonoType *t = inst->type_argv [i];
4551 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4552 return TRUE;
4554 return FALSE;
4557 static gboolean
4558 method_has_type_vars (MonoMethod *method)
4560 if (has_type_vars (method->klass))
4561 return TRUE;
4563 if (method->is_inflated) {
4564 MonoGenericContext *context = mono_method_get_context (method);
4565 if (context->method_inst) {
4566 int i;
4568 for (i = 0; i < context->method_inst->type_argc; ++i)
4569 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4570 return TRUE;
4573 return FALSE;
4576 static
4577 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4579 return opts->mode == MONO_AOT_MODE_FULL;
4582 static
4583 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
4585 return opts->interp;
4588 static
4589 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4591 return opts->mode == MONO_AOT_MODE_HYBRID;
4594 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4596 static void
4597 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4599 /* This might lead to a huge code blowup so only do it if neccesary */
4600 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4601 return;
4603 add_generic_class_with_depth (acfg, klass, 0, ref);
4606 static gboolean
4607 check_type_depth (MonoType *t, int depth)
4609 int i;
4611 if (depth > 8)
4612 return TRUE;
4614 switch (t->type) {
4615 case MONO_TYPE_GENERICINST: {
4616 MonoGenericClass *gklass = t->data.generic_class;
4617 MonoGenericInst *ginst = gklass->context.class_inst;
4619 if (ginst) {
4620 for (i = 0; i < ginst->type_argc; ++i) {
4621 if (check_type_depth (ginst->type_argv [i], depth + 1))
4622 return TRUE;
4625 break;
4627 default:
4628 break;
4631 return FALSE;
4634 static void
4635 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4638 * add_generic_class:
4640 * Add all methods of a generic class.
4642 static void
4643 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4645 MonoMethod *method;
4646 MonoClassField *field;
4647 gpointer iter;
4648 gboolean use_gsharedvt = FALSE;
4650 if (!acfg->ginst_hash)
4651 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4653 mono_class_init (klass);
4655 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4656 return;
4658 if (has_type_vars (klass))
4659 return;
4661 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
4662 return;
4664 if (mono_class_has_failure (klass))
4665 return;
4667 if (!acfg->ginst_hash)
4668 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4670 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4671 return;
4673 if (check_type_depth (m_class_get_byval_arg (klass), 0))
4674 return;
4676 if (acfg->aot_opts.log_generics) {
4677 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
4678 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
4679 g_free (s);
4682 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4685 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4686 * Enable this only for some classes since gsharedvt might not support all methods.
4688 if ((acfg->opts & MONO_OPT_GSHAREDVT) && m_class_get_image (klass) == 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) &&
4689 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
4690 use_gsharedvt = TRUE;
4692 iter = NULL;
4693 while ((method = mono_class_get_methods (klass, &iter))) {
4694 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4696 * This is partial sharing, and we can't handle it yet
4698 continue;
4701 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4702 /* Already added */
4703 add_types_from_method_header (acfg, method);
4704 continue;
4707 if (method->is_generic)
4708 /* FIXME: */
4709 continue;
4712 * FIXME: Instances which are referenced by these methods are not added,
4713 * for example Array.Resize<int> for List<int>.Add ().
4715 add_extra_method_with_depth (acfg, method, depth + 1);
4718 iter = NULL;
4719 while ((field = mono_class_get_fields (klass, &iter))) {
4720 if (field->type->type == MONO_TYPE_GENERICINST)
4721 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4724 if (m_class_is_delegate (klass)) {
4725 method = mono_get_delegate_invoke (klass);
4727 method = mono_marshal_get_delegate_invoke (method, NULL);
4729 if (acfg->aot_opts.log_generics)
4730 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4732 add_method (acfg, method);
4735 /* Add superclasses */
4736 if (m_class_get_parent (klass))
4737 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
4739 const char *klass_name = m_class_get_name (klass);
4740 const char *klass_name_space = m_class_get_name_space (klass);
4741 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
4743 * For ICollection<T>, add instances of the helper methods
4744 * in Array, since a T[] could be cast to ICollection<T>.
4746 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
4747 (!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"))) {
4748 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4749 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
4750 gpointer iter;
4751 char *name_prefix;
4753 if (!strcmp (klass_name, "IEnumerator`1"))
4754 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
4755 else
4756 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
4758 /* Add the T[]/InternalEnumerator class */
4759 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
4760 ERROR_DECL (error);
4761 MonoClass *nclass;
4763 iter = NULL;
4764 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
4765 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
4766 break;
4768 g_assert (nclass);
4769 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
4770 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4771 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4774 iter = NULL;
4775 while ((method = mono_class_get_methods (array_class, &iter))) {
4776 if (strstr (method->name, name_prefix)) {
4777 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4779 add_extra_method_with_depth (acfg, m, depth);
4783 g_free (name_prefix);
4786 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4787 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
4788 ERROR_DECL (error);
4789 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4790 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4791 MonoGenericContext ctx;
4792 MonoType *args [16];
4794 memset (&ctx, 0, sizeof (ctx));
4796 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4798 args [0] = m_class_get_byval_arg (tclass);
4799 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4801 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
4802 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4804 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4805 MonoClass *gcomparer_inst;
4806 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4807 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
4808 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4810 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4814 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4815 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
4816 ERROR_DECL (error);
4817 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4818 MonoClass *iface, *gcomparer, *iface_inst;
4819 MonoGenericContext ctx;
4820 MonoType *args [16];
4822 memset (&ctx, 0, sizeof (ctx));
4824 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4825 g_assert (iface);
4826 args [0] = m_class_get_byval_arg (tclass);
4827 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4829 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
4830 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4832 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4833 MonoClass *gcomparer_inst;
4834 ERROR_DECL (error);
4836 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4837 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
4838 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4839 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4843 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4844 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
4845 MonoClass *enum_comparer;
4846 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4847 MonoGenericContext ctx;
4848 MonoType *args [16];
4850 if (mono_class_is_enum (tclass)) {
4851 MonoClass *enum_comparer_inst;
4852 ERROR_DECL (error);
4854 memset (&ctx, 0, sizeof (ctx));
4855 args [0] = m_class_get_byval_arg (tclass);
4856 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4858 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4859 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
4860 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4861 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4865 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4866 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
4867 MonoClass *comparer;
4868 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4869 MonoGenericContext ctx;
4870 MonoType *args [16];
4872 if (mono_class_is_enum (tclass)) {
4873 MonoClass *comparer_inst;
4874 ERROR_DECL (error);
4876 memset (&ctx, 0, sizeof (ctx));
4877 args [0] = m_class_get_byval_arg (tclass);
4878 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4880 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4881 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
4882 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4883 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4888 static void
4889 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4891 int i;
4892 MonoGenericContext ctx;
4893 MonoType *args [16];
4895 if (acfg->aot_opts.no_instances)
4896 return;
4898 memset (&ctx, 0, sizeof (ctx));
4900 for (i = 0; i < ninsts; ++i) {
4901 ERROR_DECL (error);
4902 MonoClass *generic_inst;
4903 args [0] = insts [i];
4904 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4905 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
4906 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4907 add_generic_class (acfg, generic_inst, force, "");
4911 static void
4912 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4914 ERROR_DECL (error);
4915 MonoMethodHeader *header;
4916 MonoMethodSignature *sig;
4917 int j, depth;
4919 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4921 sig = mono_method_signature (method);
4923 if (sig) {
4924 for (j = 0; j < sig->param_count; ++j)
4925 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4926 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4929 header = mono_method_get_header_checked (method, error);
4931 if (header) {
4932 for (j = 0; j < header->num_locals; ++j)
4933 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4934 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4935 mono_metadata_free_mh (header);
4936 } else {
4937 mono_error_cleanup (error); /* FIXME report the error */
4943 * add_generic_instances:
4945 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4947 static void
4948 add_generic_instances (MonoAotCompile *acfg)
4950 int i;
4951 guint32 token;
4952 MonoMethod *method;
4953 MonoGenericContext *context;
4955 if (acfg->aot_opts.no_instances)
4956 return;
4958 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4959 ERROR_DECL (error);
4960 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4961 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4963 if (!method) {
4964 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
4965 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4966 mono_error_cleanup (error);
4967 continue;
4970 if (m_class_get_image (method->klass) != acfg->image)
4971 continue;
4973 context = mono_method_get_context (method);
4975 if (context && ((context->class_inst && context->class_inst->is_open)))
4976 continue;
4979 * For open methods, create an instantiation which can be passed to the JIT.
4980 * FIXME: Handle class_inst as well.
4982 if (context && context->method_inst && context->method_inst->is_open) {
4983 ERROR_DECL (error);
4984 MonoGenericContext shared_context;
4985 MonoGenericInst *inst;
4986 MonoType **type_argv;
4987 int i;
4988 MonoMethod *declaring_method;
4989 gboolean supported = TRUE;
4991 /* Check that the context doesn't contain open constructed types */
4992 if (context->class_inst) {
4993 inst = context->class_inst;
4994 for (i = 0; i < inst->type_argc; ++i) {
4995 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)
4996 continue;
4997 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4998 supported = FALSE;
5001 if (context->method_inst) {
5002 inst = context->method_inst;
5003 for (i = 0; i < inst->type_argc; ++i) {
5004 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)
5005 continue;
5006 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5007 supported = FALSE;
5011 if (!supported)
5012 continue;
5014 memset (&shared_context, 0, sizeof (MonoGenericContext));
5016 inst = context->class_inst;
5017 if (inst) {
5018 type_argv = g_new0 (MonoType*, inst->type_argc);
5019 for (i = 0; i < inst->type_argc; ++i) {
5020 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)
5021 type_argv [i] = m_class_get_byval_arg (mono_defaults.object_class);
5022 else
5023 type_argv [i] = inst->type_argv [i];
5026 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5027 g_free (type_argv);
5030 inst = context->method_inst;
5031 if (inst) {
5032 type_argv = g_new0 (MonoType*, inst->type_argc);
5033 for (i = 0; i < inst->type_argc; ++i) {
5034 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)
5035 type_argv [i] = m_class_get_byval_arg (mono_defaults.object_class);
5036 else
5037 type_argv [i] = inst->type_argv [i];
5040 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5041 g_free (type_argv);
5044 if (method->is_generic || mono_class_is_gtd (method->klass))
5045 declaring_method = method;
5046 else
5047 declaring_method = mono_method_get_declaring_generic_method (method);
5049 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5050 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5054 * If the method is fully sharable, it was already added in place of its
5055 * generic definition.
5057 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5058 continue;
5061 * FIXME: Partially shared methods are not shared here, so we end up with
5062 * many identical methods.
5064 add_extra_method (acfg, method);
5067 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5068 ERROR_DECL (error);
5069 MonoClass *klass;
5071 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5073 klass = mono_class_get_checked (acfg->image, token, error);
5074 if (!klass || m_class_get_rank (klass)) {
5075 mono_error_cleanup (error);
5076 continue;
5079 add_generic_class (acfg, klass, FALSE, "typespec");
5082 /* Add types of args/locals */
5083 for (i = 0; i < acfg->methods->len; ++i) {
5084 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5085 add_types_from_method_header (acfg, method);
5088 if (acfg->image == mono_defaults.corlib) {
5089 MonoClass *klass;
5090 MonoType *insts [256];
5091 int ninsts = 0;
5093 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5094 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5095 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5096 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5097 MonoType *int32_type = m_class_get_byval_arg (mono_defaults.int32_class);
5098 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5099 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5100 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5101 MonoType *object_type = m_class_get_byval_arg (mono_defaults.object_class);
5103 insts [ninsts ++] = byte_type;
5104 insts [ninsts ++] = sbyte_type;
5105 insts [ninsts ++] = int16_type;
5106 insts [ninsts ++] = uint16_type;
5107 insts [ninsts ++] = int32_type;
5108 insts [ninsts ++] = uint32_type;
5109 insts [ninsts ++] = int64_type;
5110 insts [ninsts ++] = uint64_type;
5111 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5112 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5113 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5114 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5116 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5117 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5118 if (klass)
5119 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5120 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5121 if (klass)
5122 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5124 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5126 MonoClass *enum_comparer;
5127 MonoType *insts [16];
5128 int ninsts;
5130 ninsts = 0;
5131 insts [ninsts ++] = int32_type;
5132 insts [ninsts ++] = uint32_type;
5133 insts [ninsts ++] = uint16_type;
5134 insts [ninsts ++] = byte_type;
5135 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5136 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5138 ninsts = 0;
5139 insts [ninsts ++] = int16_type;
5140 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5141 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5143 ninsts = 0;
5144 insts [ninsts ++] = sbyte_type;
5145 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5146 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5148 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5149 ninsts = 0;
5150 insts [ninsts ++] = int64_type;
5151 insts [ninsts ++] = uint64_type;
5152 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5155 /* Add instances of the array generic interfaces for primitive types */
5156 /* This will add instances of the InternalArray_ helper methods in Array too */
5157 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5158 if (klass)
5159 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5161 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5162 if (klass)
5163 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5165 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5166 if (klass)
5167 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5170 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5171 * used for all instances of GetGenericValueImpl by the AOT runtime.
5174 MonoGenericContext ctx;
5175 MonoType *args [16];
5176 MonoMethod *get_method;
5177 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5179 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5181 if (get_method) {
5182 ERROR_DECL (error);
5183 memset (&ctx, 0, sizeof (ctx));
5184 args [0] = object_type;
5185 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5186 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5187 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5191 /* Same for CompareExchange<T>/Exchange<T> */
5193 MonoGenericContext ctx;
5194 MonoType *args [16];
5195 MonoMethod *m;
5196 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5197 gpointer iter = NULL;
5199 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5200 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5201 ERROR_DECL (error);
5202 memset (&ctx, 0, sizeof (ctx));
5203 args [0] = object_type;
5204 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5205 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5206 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5211 /* Same for Volatile.Read/Write<T> */
5213 MonoGenericContext ctx;
5214 MonoType *args [16];
5215 MonoMethod *m;
5216 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5217 gpointer iter = NULL;
5219 if (volatile_klass) {
5220 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5221 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5222 ERROR_DECL (error);
5223 memset (&ctx, 0, sizeof (ctx));
5224 args [0] = object_type;
5225 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5226 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5227 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5233 /* object[] accessor wrappers. */
5234 for (i = 1; i < 4; ++i) {
5235 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5236 MonoMethod *m;
5238 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5239 g_assert (m);
5241 m = mono_marshal_get_array_accessor_wrapper (m);
5242 add_extra_method (acfg, m);
5244 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5245 g_assert (m);
5247 m = mono_marshal_get_array_accessor_wrapper (m);
5248 add_extra_method (acfg, m);
5250 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5251 g_assert (m);
5253 m = mono_marshal_get_array_accessor_wrapper (m);
5254 add_extra_method (acfg, m);
5260 * is_direct_callable:
5262 * Return whenever the method identified by JI is directly callable without
5263 * going through the PLT.
5265 static gboolean
5266 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5268 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5269 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5270 if (callee_cfg) {
5271 gboolean direct_callable = TRUE;
5273 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5274 direct_callable = FALSE;
5276 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5277 direct_callable = FALSE;
5278 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5279 // FIXME: Maybe call the wrapper directly ?
5280 direct_callable = FALSE;
5282 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5283 /* Disable this so all calls go through load_method (), see the
5284 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5285 * mono_debugger_agent_init ().
5287 direct_callable = FALSE;
5290 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5291 /* sgen does some initialization when the allocator method is created */
5292 direct_callable = FALSE;
5293 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5294 /* we don't know at compile time whether sgen is concurrent or not */
5295 direct_callable = FALSE;
5297 if (direct_callable)
5298 return TRUE;
5300 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5301 if (acfg->aot_opts.direct_pinvoke)
5302 return TRUE;
5303 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5304 if (acfg->aot_opts.direct_icalls)
5305 return TRUE;
5306 return FALSE;
5309 return FALSE;
5312 #ifdef MONO_ARCH_AOT_SUPPORTED
5313 static const char *
5314 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5316 MonoImage *image = m_class_get_image (method->klass);
5317 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5318 MonoTableInfo *tables = image->tables;
5319 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5320 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5321 guint32 im_cols [MONO_IMPLMAP_SIZE];
5322 char *import;
5324 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5325 if (import != NULL)
5326 return import;
5328 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5329 return NULL;
5331 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5333 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5334 return NULL;
5336 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5338 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5340 return import;
5342 #else
5343 static const char *
5344 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5346 return NULL;
5348 #endif
5350 static gint
5351 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5353 if (a->native_offset == b->native_offset)
5354 return a->il_offset - b->il_offset;
5355 else
5356 return a->native_offset - b->native_offset;
5360 * compute_line_numbers:
5362 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5363 * entry.
5365 static MonoDebugSourceLocation**
5366 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5368 MonoDebugMethodInfo *minfo;
5369 MonoDebugLineNumberEntry *ln_array;
5370 MonoDebugSourceLocation *loc;
5371 int i, prev_line, prev_il_offset;
5372 int *native_to_il_offset = NULL;
5373 MonoDebugSourceLocation **res;
5374 gboolean first;
5376 minfo = mono_debug_lookup_method (method);
5377 if (!minfo)
5378 return NULL;
5379 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5380 if (debug_info->code_size != code_size)
5381 return NULL;
5383 g_assert (code_size);
5385 /* Compute the native->IL offset mapping */
5387 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5388 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5390 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5392 native_to_il_offset = g_new0 (int, code_size + 1);
5394 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5395 int j;
5396 MonoDebugLineNumberEntry *lne = &ln_array [i];
5398 if (i == 0) {
5399 for (j = 0; j < lne->native_offset; ++j)
5400 native_to_il_offset [j] = -1;
5403 if (i < debug_info->num_line_numbers - 1) {
5404 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5406 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5407 native_to_il_offset [j] = lne->il_offset;
5408 } else {
5409 for (j = lne->native_offset; j < code_size; ++j)
5410 native_to_il_offset [j] = lne->il_offset;
5413 g_free (ln_array);
5415 /* Compute the native->line number mapping */
5416 res = g_new0 (MonoDebugSourceLocation*, code_size);
5417 prev_il_offset = -1;
5418 prev_line = -1;
5419 first = TRUE;
5420 for (i = 0; i < code_size; ++i) {
5421 int il_offset = native_to_il_offset [i];
5423 if (il_offset == -1 || il_offset == prev_il_offset)
5424 continue;
5425 prev_il_offset = il_offset;
5426 loc = mono_debug_method_lookup_location (minfo, il_offset);
5427 if (!(loc && loc->source_file))
5428 continue;
5429 if (loc->row == prev_line) {
5430 mono_debug_free_source_location (loc);
5431 continue;
5433 prev_line = loc->row;
5434 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5435 if (first)
5436 /* This will cover the prolog too */
5437 res [0] = loc;
5438 else
5439 res [i] = loc;
5440 first = FALSE;
5442 return res;
5445 static int
5446 get_file_index (MonoAotCompile *acfg, const char *source_file)
5448 int findex;
5450 // FIXME: Free these
5451 if (!acfg->dwarf_ln_filenames)
5452 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5453 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5454 if (!findex) {
5455 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5456 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5457 emit_unset_mode (acfg);
5458 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5460 return findex;
5463 #ifdef TARGET_ARM64
5464 #define INST_LEN 4
5465 #else
5466 #define INST_LEN 1
5467 #endif
5470 * emit_and_reloc_code:
5472 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5473 * is true, calls are made through the GOT too. This is used for emitting trampolines
5474 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5475 * since trampolines are needed to make PTL work.
5477 static void
5478 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5480 int i, pindex, start_index;
5481 GPtrArray *patches;
5482 MonoJumpInfo *patch_info;
5483 MonoDebugSourceLocation **locs = NULL;
5484 gboolean skip, prologue_end = FALSE;
5485 #ifdef MONO_ARCH_AOT_SUPPORTED
5486 gboolean direct_call, external_call;
5487 guint32 got_slot;
5488 const char *direct_call_target = 0;
5489 const char *direct_pinvoke;
5490 #endif
5492 if (acfg->gas_line_numbers && method && debug_info) {
5493 locs = compute_line_numbers (method, code_len, debug_info);
5494 if (!locs) {
5495 int findex = get_file_index (acfg, "<unknown>");
5496 emit_unset_mode (acfg);
5497 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5501 /* Collect and sort relocations */
5502 patches = g_ptr_array_new ();
5503 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5504 g_ptr_array_add (patches, patch_info);
5505 g_ptr_array_sort (patches, compare_patches);
5507 start_index = 0;
5508 for (i = 0; i < code_len; i += INST_LEN) {
5509 patch_info = NULL;
5510 for (pindex = start_index; pindex < patches->len; ++pindex) {
5511 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5512 if (patch_info->ip.i >= i)
5513 break;
5516 if (locs && locs [i]) {
5517 MonoDebugSourceLocation *loc = locs [i];
5518 int findex;
5519 const char *options;
5521 findex = get_file_index (acfg, loc->source_file);
5522 emit_unset_mode (acfg);
5523 if (!prologue_end)
5524 options = " prologue_end";
5525 else
5526 options = "";
5527 prologue_end = TRUE;
5528 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5529 mono_debug_free_source_location (loc);
5532 skip = FALSE;
5533 #ifdef MONO_ARCH_AOT_SUPPORTED
5534 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5535 start_index = pindex;
5537 switch (patch_info->type) {
5538 case MONO_PATCH_INFO_NONE:
5539 break;
5540 case MONO_PATCH_INFO_GOT_OFFSET: {
5541 int code_size;
5543 arch_emit_got_offset (acfg, code + i, &code_size);
5544 i += code_size - INST_LEN;
5545 skip = TRUE;
5546 patch_info->type = MONO_PATCH_INFO_NONE;
5547 break;
5549 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5550 int code_size, index;
5551 char *selector = (char *)patch_info->data.target;
5553 if (!acfg->objc_selector_to_index)
5554 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5555 if (!acfg->objc_selectors)
5556 acfg->objc_selectors = g_ptr_array_new ();
5557 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5558 if (index)
5559 index --;
5560 else {
5561 index = acfg->objc_selector_index;
5562 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5563 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5564 acfg->objc_selector_index ++;
5567 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5568 i += code_size - INST_LEN;
5569 skip = TRUE;
5570 patch_info->type = MONO_PATCH_INFO_NONE;
5571 break;
5573 default: {
5575 * If this patch is a call, try emitting a direct call instead of
5576 * through a PLT entry. This is possible if the called method is in
5577 * the same assembly and requires no initialization.
5579 direct_call = FALSE;
5580 external_call = FALSE;
5581 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5582 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5583 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5585 // Don't compile inflated methods if we're doing dedup
5586 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
5587 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
5588 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
5589 g_free (name);
5591 direct_call = TRUE;
5592 direct_call_target = callee_cfg->asm_symbol;
5593 patch_info->type = MONO_PATCH_INFO_NONE;
5594 acfg->stats.direct_calls ++;
5598 acfg->stats.all_calls ++;
5599 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5600 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5601 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5602 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5603 else
5604 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5605 if (direct_pinvoke) {
5606 direct_call = TRUE;
5607 g_assert (strlen (direct_pinvoke) < 1000);
5608 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5611 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5612 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5613 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5614 /* Call to a C function implementing a jit icall */
5615 direct_call = TRUE;
5616 external_call = TRUE;
5617 g_assert (strlen (sym) < 1000);
5618 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5620 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5621 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5622 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5623 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5624 /* Call to a jit icall without a wrapper */
5625 direct_call = TRUE;
5626 external_call = TRUE;
5627 g_assert (strlen (sym) < 1000);
5628 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5632 if (direct_call) {
5633 patch_info->type = MONO_PATCH_INFO_NONE;
5634 acfg->stats.direct_calls ++;
5637 if (!got_only && !direct_call) {
5638 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5639 if (plt_entry) {
5640 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5641 direct_call = TRUE;
5642 direct_call_target = plt_entry->symbol;
5644 /* Nullify the patch */
5645 patch_info->type = MONO_PATCH_INFO_NONE;
5646 plt_entry->jit_used = TRUE;
5650 if (direct_call) {
5651 int call_size;
5653 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5654 i += call_size - INST_LEN;
5655 } else {
5656 int code_size;
5658 got_slot = get_got_offset (acfg, FALSE, patch_info);
5660 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5661 i += code_size - INST_LEN;
5663 skip = TRUE;
5667 #endif /* MONO_ARCH_AOT_SUPPORTED */
5669 if (!skip) {
5670 /* Find next patch */
5671 patch_info = NULL;
5672 for (pindex = start_index; pindex < patches->len; ++pindex) {
5673 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5674 if (patch_info->ip.i >= i)
5675 break;
5678 /* Try to emit multiple bytes at once */
5679 if (pindex < patches->len && patch_info->ip.i > i) {
5680 int limit;
5682 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5683 if (locs && locs [limit])
5684 break;
5687 emit_code_bytes (acfg, code + i, limit - i);
5688 i = limit - INST_LEN;
5689 } else {
5690 emit_code_bytes (acfg, code + i, INST_LEN);
5695 g_ptr_array_free (patches, TRUE);
5696 g_free (locs);
5700 * sanitize_symbol:
5702 * Return a modified version of S which only includes characters permissible in symbols.
5704 static char*
5705 sanitize_symbol (MonoAotCompile *acfg, char *s)
5707 gboolean process = FALSE;
5708 int i, len;
5709 GString *gs;
5710 char *res;
5712 if (!s)
5713 return s;
5715 len = strlen (s);
5716 for (i = 0; i < len; ++i)
5717 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5718 process = TRUE;
5719 if (!process)
5720 return s;
5722 gs = g_string_sized_new (len);
5723 for (i = 0; i < len; ++i) {
5724 guint8 c = s [i];
5725 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5726 g_string_append_c (gs, c);
5727 } else if (c > 0x7f) {
5728 /* multi-byte utf8 */
5729 g_string_append_printf (gs, "_0x%x", c);
5730 i ++;
5731 c = s [i];
5732 while (c >> 6 == 0x2) {
5733 g_string_append_printf (gs, "%x", c);
5734 i ++;
5735 c = s [i];
5737 g_string_append_printf (gs, "_");
5738 i --;
5739 } else {
5740 g_string_append_c (gs, '_');
5744 res = mono_mempool_strdup (acfg->mempool, gs->str);
5745 g_string_free (gs, TRUE);
5746 return res;
5749 static char*
5750 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5752 char *name1, *name2, *cached;
5753 int i, j, len, count;
5754 MonoMethod *cached_method;
5756 name1 = mono_method_full_name (method, TRUE);
5758 #ifdef TARGET_MACH
5759 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5760 if ((!prefix || !*prefix) && name1 [0] == 'L')
5761 prefix = "_";
5762 #endif
5764 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5765 char adjustedPrefix [MAX_SYMBOL_SIZE];
5766 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5767 #endif
5769 len = strlen (name1);
5770 name2 = (char *)malloc (strlen (prefix) + len + 16);
5771 memcpy (name2, prefix, strlen (prefix));
5772 j = strlen (prefix);
5773 for (i = 0; i < len; ++i) {
5774 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5775 name2 [j ++] = '_';
5776 } else if (isalnum (name1 [i])) {
5777 name2 [j ++] = name1 [i];
5778 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5779 i += 2;
5780 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5781 name2 [j ++] = '_';
5782 i++;
5783 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5784 } else
5785 name2 [j ++] = '_';
5787 name2 [j] = '\0';
5789 g_free (name1);
5791 count = 0;
5792 while (TRUE) {
5793 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5794 if (!(cached_method && cached_method != method))
5795 break;
5796 sprintf (name2 + j, "_%d", count);
5797 count ++;
5800 cached = g_strdup (name2);
5801 g_hash_table_insert (cache, cached, method);
5803 return name2;
5806 static void
5807 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5809 MonoMethod *method;
5810 int method_index;
5811 guint8 *code;
5812 char *debug_sym = NULL;
5813 char *symbol = NULL;
5814 int func_alignment = AOT_FUNC_ALIGNMENT;
5815 char *export_name;
5817 g_assert (!ignore_cfg (cfg));
5819 method = cfg->orig_method;
5820 code = cfg->native_code;
5822 method_index = get_method_index (acfg, method);
5823 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5825 /* Make the labels local */
5826 emit_section_change (acfg, ".text", 0);
5827 emit_alignment_code (acfg, func_alignment);
5829 if (acfg->global_symbols && acfg->need_no_dead_strip)
5830 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5832 emit_label (acfg, cfg->asm_symbol);
5834 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5836 * Write a C style symbol for every method, this has two uses:
5837 * - it works on platforms where the dwarf debugging info is not
5838 * yet supported.
5839 * - it allows the setting of breakpoints of aot-ed methods.
5842 // Comment out to force dedup to link these symbols and forbid compiling
5843 // in duplicated code. This is an "assert when linking if broken" trick.
5844 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
5845 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
5846 /*else*/
5847 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5849 cfg->asm_debug_symbol = g_strdup (debug_sym);
5851 if (acfg->need_no_dead_strip)
5852 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5854 // Comment out to force dedup to link these symbols and forbid compiling
5855 // in duplicated code. This is an "assert when linking if broken" trick.
5856 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
5857 /*emit_global_inner (acfg, debug_sym, TRUE);*/
5858 /*else*/
5859 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5861 emit_label (acfg, debug_sym);
5864 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5865 if (export_name) {
5866 /* Emit a global symbol for the method */
5867 emit_global_inner (acfg, export_name, TRUE);
5868 emit_label (acfg, export_name);
5871 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
5872 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5874 acfg->stats.code_size += cfg->code_len;
5876 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5878 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 ()));
5880 emit_line (acfg);
5882 if (acfg->aot_opts.write_symbols) {
5883 if (debug_sym)
5884 emit_symbol_size (acfg, debug_sym, ".");
5885 else
5886 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5887 g_free (debug_sym);
5890 emit_label (acfg, symbol);
5892 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
5894 g_free (symbol);
5898 * encode_patch:
5900 * Encode PATCH_INFO into its disk representation.
5902 static void
5903 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5905 guint8 *p = buf;
5907 switch (patch_info->type) {
5908 case MONO_PATCH_INFO_NONE:
5909 break;
5910 case MONO_PATCH_INFO_IMAGE:
5911 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5912 break;
5913 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5914 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5915 case MONO_PATCH_INFO_GC_NURSERY_START:
5916 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5917 break;
5918 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5919 encode_value (patch_info->data.index, p, &p);
5920 break;
5921 case MONO_PATCH_INFO_METHOD_REL:
5922 encode_value ((gint)patch_info->data.offset, p, &p);
5923 break;
5924 case MONO_PATCH_INFO_SWITCH: {
5925 gpointer *table = (gpointer *)patch_info->data.table->table;
5926 int k;
5928 encode_value (patch_info->data.table->table_size, p, &p);
5929 for (k = 0; k < patch_info->data.table->table_size; k++)
5930 encode_value ((int)(gssize)table [k], p, &p);
5931 break;
5933 case MONO_PATCH_INFO_METHODCONST:
5934 case MONO_PATCH_INFO_METHOD:
5935 case MONO_PATCH_INFO_METHOD_JUMP:
5936 case MONO_PATCH_INFO_ICALL_ADDR:
5937 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5938 case MONO_PATCH_INFO_METHOD_RGCTX:
5939 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5940 encode_method_ref (acfg, patch_info->data.method, p, &p);
5941 break;
5942 case MONO_PATCH_INFO_AOT_JIT_INFO:
5943 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5944 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5945 encode_value (patch_info->data.index, p, &p);
5946 break;
5947 case MONO_PATCH_INFO_INTERNAL_METHOD:
5948 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5949 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
5950 guint32 len = strlen (patch_info->data.name);
5952 encode_value (len, p, &p);
5954 memcpy (p, patch_info->data.name, len);
5955 p += len;
5956 *p++ = '\0';
5957 break;
5959 case MONO_PATCH_INFO_LDSTR: {
5960 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5961 guint32 token = patch_info->data.token->token;
5962 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5963 encode_value (image_index, p, &p);
5964 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5965 break;
5967 case MONO_PATCH_INFO_RVA:
5968 case MONO_PATCH_INFO_DECLSEC:
5969 case MONO_PATCH_INFO_LDTOKEN:
5970 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5971 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5972 encode_value (patch_info->data.token->token, p, &p);
5973 encode_value (patch_info->data.token->has_context, p, &p);
5974 if (patch_info->data.token->has_context)
5975 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5976 break;
5977 case MONO_PATCH_INFO_EXC_NAME: {
5978 MonoClass *ex_class;
5980 ex_class =
5981 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
5982 "System", (const char *)patch_info->data.target);
5983 encode_klass_ref (acfg, ex_class, p, &p);
5984 break;
5986 case MONO_PATCH_INFO_R4:
5987 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5988 break;
5989 case MONO_PATCH_INFO_R8:
5990 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5991 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5992 break;
5993 case MONO_PATCH_INFO_VTABLE:
5994 case MONO_PATCH_INFO_CLASS:
5995 case MONO_PATCH_INFO_IID:
5996 case MONO_PATCH_INFO_ADJUSTED_IID:
5997 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5998 break;
5999 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6000 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6001 if (patch_info->data.del_tramp->method) {
6002 encode_value (1, p, &p);
6003 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6004 } else {
6005 encode_value (0, p, &p);
6007 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6008 break;
6009 case MONO_PATCH_INFO_FIELD:
6010 case MONO_PATCH_INFO_SFLDA:
6011 encode_field_info (acfg, patch_info->data.field, p, &p);
6012 break;
6013 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6014 break;
6015 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6016 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6017 break;
6018 case MONO_PATCH_INFO_RGCTX_FETCH:
6019 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6020 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6021 guint32 offset;
6022 guint8 *buf2, *p2;
6025 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
6026 * reference the same method, so encode the method only once.
6028 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
6029 if (!offset) {
6030 buf2 = (guint8 *)g_malloc (1024);
6031 p2 = buf2;
6033 encode_method_ref (acfg, entry->method, p2, &p2);
6034 g_assert (p2 - buf2 < 1024);
6036 offset = add_to_blob (acfg, buf2, p2 - buf2);
6037 g_free (buf2);
6039 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
6040 } else {
6041 offset --;
6044 encode_value (offset, p, &p);
6045 g_assert ((int)entry->info_type < 256);
6046 g_assert (entry->data->type < 256);
6047 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6048 encode_patch (acfg, entry->data, p, &p);
6049 break;
6051 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6052 case MONO_PATCH_INFO_AOT_MODULE:
6053 break;
6054 case MONO_PATCH_INFO_SIGNATURE:
6055 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6056 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6057 break;
6058 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6059 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6060 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6061 break;
6062 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6063 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6064 int i;
6066 encode_method_ref (acfg, info->method, p, &p);
6067 encode_value (info->num_entries, p, &p);
6068 for (i = 0; i < info->num_entries; ++i) {
6069 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6071 encode_value (template_->info_type, p, &p);
6072 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6073 case MONO_PATCH_INFO_CLASS:
6074 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
6075 break;
6076 case MONO_PATCH_INFO_FIELD:
6077 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6078 break;
6079 default:
6080 g_assert_not_reached ();
6081 break;
6084 break;
6086 case MONO_PATCH_INFO_LDSTR_LIT: {
6087 const char *s = (const char *)patch_info->data.target;
6088 int len = strlen (s);
6090 encode_value (len, p, &p);
6091 memcpy (p, s, len + 1);
6092 p += len + 1;
6093 break;
6095 case MONO_PATCH_INFO_VIRT_METHOD:
6096 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6097 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6098 break;
6099 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6100 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
6101 break;
6102 default:
6103 g_warning ("unable to handle jump info %d", patch_info->type);
6104 g_assert_not_reached ();
6107 *endbuf = p;
6110 static void
6111 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
6113 guint8 *p = buf;
6114 guint32 pindex, offset;
6115 MonoJumpInfo *patch_info;
6117 encode_value (n_patches, p, &p);
6119 for (pindex = 0; pindex < patches->len; ++pindex) {
6120 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6122 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6123 /* Nothing to do */
6124 continue;
6126 offset = get_got_offset (acfg, llvm, patch_info);
6127 encode_value (offset, p, &p);
6130 *endbuf = p;
6133 static void
6134 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6136 MonoMethod *method;
6137 int pindex, buf_size, n_patches;
6138 GPtrArray *patches;
6139 MonoJumpInfo *patch_info;
6140 guint32 method_index;
6141 guint8 *p, *buf;
6142 guint32 first_got_offset;
6144 method = cfg->orig_method;
6146 method_index = get_method_index (acfg, method);
6148 /* Sort relocations */
6149 patches = g_ptr_array_new ();
6150 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6151 g_ptr_array_add (patches, patch_info);
6152 g_ptr_array_sort (patches, compare_patches);
6154 first_got_offset = acfg->cfgs [method_index]->got_offset;
6156 /**********************/
6157 /* Encode method info */
6158 /**********************/
6160 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6161 p = buf = (guint8 *)g_malloc (buf_size);
6163 if (mono_class_get_cctor (method->klass)) {
6164 encode_value (1, p, &p);
6165 encode_klass_ref (acfg, method->klass, p, &p);
6166 } else {
6167 /* Not needed when loading the method */
6168 encode_value (0, p, &p);
6171 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6173 n_patches = 0;
6174 for (pindex = 0; pindex < patches->len; ++pindex) {
6175 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6177 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6178 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6179 patch_info->type = MONO_PATCH_INFO_NONE;
6180 /* Nothing to do */
6181 continue;
6184 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6185 /* Stored in a GOT slot initialized at module load time */
6186 patch_info->type = MONO_PATCH_INFO_NONE;
6187 continue;
6190 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6191 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6192 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6193 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6194 /* Stored in a GOT slot initialized at module load time */
6195 patch_info->type = MONO_PATCH_INFO_NONE;
6196 continue;
6199 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6200 /* Calls are made through the PLT */
6201 patch_info->type = MONO_PATCH_INFO_NONE;
6202 continue;
6205 n_patches ++;
6208 if (n_patches)
6209 g_assert (cfg->has_got_slots);
6211 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6213 g_ptr_array_free (patches, TRUE);
6215 acfg->stats.info_size += p - buf;
6217 g_assert (p - buf < buf_size);
6219 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6220 g_free (buf);
6223 static guint32
6224 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6226 guint32 cache_index;
6227 guint32 offset;
6229 /* Reuse the unwind module to canonize and store unwind info entries */
6230 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6232 /* Use +/- 1 to distinguish 0s from missing entries */
6233 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6234 if (offset)
6235 return offset - 1;
6236 else {
6237 guint8 buf [16];
6238 guint8 *p;
6241 * It would be easier to use assembler symbols, but the caller needs an
6242 * offset now.
6244 offset = acfg->unwind_info_offset;
6245 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6246 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6248 p = buf;
6249 encode_value (encoded_len, p, &p);
6251 acfg->unwind_info_offset += encoded_len + (p - buf);
6252 return offset;
6256 static void
6257 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6259 int i, k, buf_size;
6260 guint32 debug_info_size, seq_points_size;
6261 guint8 *code;
6262 MonoMethodHeader *header;
6263 guint8 *p, *buf, *debug_info;
6264 MonoJitInfo *jinfo = cfg->jit_info;
6265 guint32 flags;
6266 gboolean use_unwind_ops = FALSE;
6267 MonoSeqPointInfo *seq_points;
6269 code = cfg->native_code;
6270 header = cfg->header;
6272 if (!acfg->aot_opts.nodebug) {
6273 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6274 } else {
6275 debug_info = NULL;
6276 debug_info_size = 0;
6279 seq_points = cfg->seq_point_info;
6280 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6282 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6283 if (jinfo->has_try_block_holes) {
6284 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6285 buf_size += table->num_holes * 16;
6288 p = buf = (guint8 *)g_malloc (buf_size);
6290 use_unwind_ops = cfg->unwind_ops != NULL;
6292 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);
6294 encode_value (flags, p, &p);
6296 if (use_unwind_ops) {
6297 guint32 encoded_len;
6298 guint8 *encoded;
6299 guint32 unwind_desc;
6301 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6303 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6304 encode_value (unwind_desc, p, &p);
6306 g_free (encoded);
6307 } else {
6308 encode_value (jinfo->unwind_info, p, &p);
6311 /*Encode the number of holes before the number of clauses to make decoding easier*/
6312 if (jinfo->has_try_block_holes) {
6313 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6314 encode_value (table->num_holes, p, &p);
6317 if (jinfo->has_arch_eh_info) {
6319 * In AOT mode, the code length is calculated from the address of the previous method,
6320 * which could include alignment padding, so calculating the start of the epilog as
6321 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6323 encode_value (jinfo->code_size, p, &p);
6326 /* Exception table */
6327 if (cfg->compile_llvm) {
6329 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6330 * since the information is only available to llc. Instead, we let llc save the data
6331 * into the LSDA, and read it from there at runtime.
6333 /* The assembly might be CIL stripped so emit the data ourselves */
6334 if (header->num_clauses)
6335 encode_value (header->num_clauses, p, &p);
6337 for (k = 0; k < header->num_clauses; ++k) {
6338 MonoExceptionClause *clause;
6340 clause = &header->clauses [k];
6342 encode_value (clause->flags, p, &p);
6343 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6344 if (clause->data.catch_class) {
6345 guint8 *buf2, *p2;
6346 int len;
6348 buf2 = (guint8 *)g_malloc (4096);
6349 p2 = buf2;
6350 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6351 len = p2 - buf2;
6352 g_assert (len < 4096);
6353 encode_value (len, p, &p);
6354 memcpy (p, buf2, len);
6355 p += p2 - buf2;
6356 g_free (buf2);
6357 } else {
6358 encode_value (0, p, &p);
6362 /* Emit the IL ranges too, since they might not be available at runtime */
6363 encode_value (clause->try_offset, p, &p);
6364 encode_value (clause->try_len, p, &p);
6365 encode_value (clause->handler_offset, p, &p);
6366 encode_value (clause->handler_len, p, &p);
6368 /* Emit a list of nesting clauses */
6369 for (i = 0; i < header->num_clauses; ++i) {
6370 gint32 cindex1 = k;
6371 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6372 gint32 cindex2 = i;
6373 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6375 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6376 encode_value (i, p, &p);
6378 encode_value (-1, p, &p);
6380 } else {
6381 if (jinfo->num_clauses)
6382 encode_value (jinfo->num_clauses, p, &p);
6384 for (k = 0; k < jinfo->num_clauses; ++k) {
6385 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6387 encode_value (ei->flags, p, &p);
6388 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6389 /* Not used for catch clauses */
6390 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6391 encode_value (ei->exvar_offset, p, &p);
6392 #else
6393 encode_value (ei->exvar_offset, p, &p);
6394 #endif
6396 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6397 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6398 else {
6399 if (ei->data.catch_class) {
6400 guint8 *buf2, *p2;
6401 int len;
6403 buf2 = (guint8 *)g_malloc (4096);
6404 p2 = buf2;
6405 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6406 len = p2 - buf2;
6407 g_assert (len < 4096);
6408 encode_value (len, p, &p);
6409 memcpy (p, buf2, len);
6410 p += p2 - buf2;
6411 g_free (buf2);
6412 } else {
6413 encode_value (0, p, &p);
6417 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6418 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6419 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6423 if (jinfo->has_try_block_holes) {
6424 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6425 for (i = 0; i < table->num_holes; ++i) {
6426 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6427 encode_value (hole->clause, p, &p);
6428 encode_value (hole->length, p, &p);
6429 encode_value (hole->offset, p, &p);
6433 if (jinfo->has_arch_eh_info) {
6434 MonoArchEHJitInfo *eh_info;
6436 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6437 encode_value (eh_info->stack_size, p, &p);
6438 encode_value (eh_info->epilog_size, p, &p);
6441 if (jinfo->has_generic_jit_info) {
6442 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6443 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6444 guint8 *buf2, *p2;
6445 int len;
6447 encode_value (gi->nlocs, p, &p);
6448 if (gi->nlocs) {
6449 for (i = 0; i < gi->nlocs; ++i) {
6450 MonoDwarfLocListEntry *entry = &gi->locations [i];
6452 encode_value (entry->is_reg ? 1 : 0, p, &p);
6453 encode_value (entry->reg, p, &p);
6454 if (!entry->is_reg)
6455 encode_value (entry->offset, p, &p);
6456 if (i == 0)
6457 g_assert (entry->from == 0);
6458 else
6459 encode_value (entry->from, p, &p);
6460 encode_value (entry->to, p, &p);
6462 } else {
6463 if (!cfg->compile_llvm) {
6464 encode_value (gi->has_this ? 1 : 0, p, &p);
6465 encode_value (gi->this_reg, p, &p);
6466 encode_value (gi->this_offset, p, &p);
6471 * Need to encode jinfo->method too, since it is not equal to 'method'
6472 * when using generic sharing.
6474 buf2 = (guint8 *)g_malloc (4096);
6475 p2 = buf2;
6476 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6477 len = p2 - buf2;
6478 g_assert (len < 4096);
6479 encode_value (len, p, &p);
6480 memcpy (p, buf2, len);
6481 p += p2 - buf2;
6482 g_free (buf2);
6484 if (gsctx && gsctx->is_gsharedvt) {
6485 encode_value (1, p, &p);
6486 } else {
6487 encode_value (0, p, &p);
6491 if (seq_points_size)
6492 p += mono_seq_point_info_write (seq_points, p);
6494 g_assert (debug_info_size < buf_size);
6496 encode_value (debug_info_size, p, &p);
6497 if (debug_info_size) {
6498 memcpy (p, debug_info, debug_info_size);
6499 p += debug_info_size;
6500 g_free (debug_info);
6503 /* GC Map */
6504 if (cfg->gc_map) {
6505 encode_value (cfg->gc_map_size, p, &p);
6506 /* The GC map requires 4 bytes of alignment */
6507 while ((gsize)p % 4)
6508 p ++;
6509 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6510 p += cfg->gc_map_size;
6513 acfg->stats.ex_info_size += p - buf;
6515 g_assert (p - buf < buf_size);
6517 /* Emit info */
6518 /* The GC Map requires 4 byte alignment */
6519 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6520 g_free (buf);
6523 static guint32
6524 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6526 ERROR_DECL (error);
6527 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
6528 guint8 *p, *buf;
6529 int i, buf_size, res;
6530 gboolean no_special_static, cant_encode;
6531 gpointer iter = NULL;
6533 if (!klass) {
6534 mono_error_cleanup (error);
6536 buf_size = 16;
6538 p = buf = (guint8 *)g_malloc (buf_size);
6540 /* Mark as unusable */
6541 encode_value (-1, p, &p);
6543 res = add_to_blob (acfg, buf, p - buf);
6544 g_free (buf);
6546 return res;
6549 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
6550 p = buf = (guint8 *)g_malloc (buf_size);
6552 g_assert (klass);
6554 mono_class_init (klass);
6556 mono_class_get_nested_types (klass, &iter);
6557 g_assert (m_class_is_nested_classes_inited (klass));
6559 mono_class_setup_vtable (klass);
6562 * Emit all the information which is required for creating vtables so
6563 * the runtime does not need to create the MonoMethod structures which
6564 * take up a lot of space.
6567 no_special_static = !mono_class_has_special_static_fields (klass);
6569 /* Check whenever we have enough info to encode the vtable */
6570 cant_encode = FALSE;
6571 MonoMethod **klass_vtable = m_class_get_vtable (klass);
6572 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6573 MonoMethod *cm = klass_vtable [i];
6575 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6576 cant_encode = TRUE;
6579 mono_class_has_finalizer (klass);
6580 if (mono_class_has_failure (klass))
6581 cant_encode = TRUE;
6583 if (mono_class_is_gtd (klass) || cant_encode) {
6584 encode_value (-1, p, &p);
6585 } else {
6586 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6587 encode_value (m_class_get_vtable_size (klass), p, &p);
6588 encode_value ((m_class_has_weak_fields (klass) << 9) | (mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (m_class_has_static_refs (klass) << 6) | (m_class_has_references (klass) << 5) | ((m_class_is_blittable (klass) << 4) | (has_nested ? 1 : 0) << 3) | (m_class_has_cctor (klass) << 2) | (m_class_has_finalize (klass) << 1) | m_class_is_ghcimpl (klass), p, &p);
6589 if (m_class_has_cctor (klass))
6590 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6591 if (m_class_has_finalize (klass))
6592 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6594 encode_value (m_class_get_instance_size (klass), p, &p);
6595 encode_value (mono_class_data_size (klass), p, &p);
6596 encode_value (m_class_get_packing_size (klass), p, &p);
6597 encode_value (m_class_get_min_align (klass), p, &p);
6599 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6600 MonoMethod *cm = klass_vtable [i];
6602 if (cm)
6603 encode_method_ref (acfg, cm, p, &p);
6604 else
6605 encode_value (0, p, &p);
6609 acfg->stats.class_info_size += p - buf;
6611 g_assert (p - buf < buf_size);
6612 res = add_to_blob (acfg, buf, p - buf);
6613 g_free (buf);
6615 return res;
6618 static char*
6619 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6621 char *debug_sym = NULL;
6622 char *prefix;
6624 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6625 /* Need to add a prefix to create unique symbols */
6626 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6627 } else {
6628 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6629 prefix = mangle_symbol_alloc ("plt_");
6630 #else
6631 prefix = g_strdup ("plt_");
6632 #endif
6635 switch (ji->type) {
6636 case MONO_PATCH_INFO_METHOD:
6637 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6638 break;
6639 case MONO_PATCH_INFO_INTERNAL_METHOD:
6640 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6641 break;
6642 case MONO_PATCH_INFO_RGCTX_FETCH:
6643 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6644 break;
6645 case MONO_PATCH_INFO_ICALL_ADDR:
6646 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6647 char *s = get_debug_sym (ji->data.method, "", cache);
6649 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6650 g_free (s);
6651 break;
6653 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6654 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6655 break;
6656 default:
6657 break;
6660 g_free (prefix);
6662 return sanitize_symbol (acfg, debug_sym);
6666 * Calls made from AOTed code are routed through a table of jumps similar to the
6667 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6668 * control to the AOT runtime through a trampoline.
6670 static void
6671 emit_plt (MonoAotCompile *acfg)
6673 int i;
6675 if (acfg->aot_opts.llvm_only) {
6676 g_assert (acfg->plt_offset == 1);
6677 return;
6680 emit_line (acfg);
6682 emit_section_change (acfg, ".text", 0);
6683 emit_alignment_code (acfg, 16);
6684 emit_info_symbol (acfg, "plt");
6685 emit_label (acfg, acfg->plt_symbol);
6687 for (i = 0; i < acfg->plt_offset; ++i) {
6688 char *debug_sym = NULL;
6689 MonoPltEntry *plt_entry = NULL;
6691 if (i == 0)
6693 * The first plt entry is unused.
6695 continue;
6697 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6699 debug_sym = plt_entry->debug_sym;
6701 if (acfg->thumb_mixed && !plt_entry->jit_used)
6702 /* Emit only a thumb version */
6703 continue;
6705 /* Skip plt entries not actually called */
6706 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6707 continue;
6709 if (acfg->llvm && !acfg->thumb_mixed) {
6710 emit_label (acfg, plt_entry->llvm_symbol);
6711 if (acfg->llvm) {
6712 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6713 #if defined(TARGET_MACH)
6714 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6715 #endif
6719 if (debug_sym) {
6720 if (acfg->need_no_dead_strip) {
6721 emit_unset_mode (acfg);
6722 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6724 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6725 emit_label (acfg, debug_sym);
6728 emit_label (acfg, plt_entry->symbol);
6730 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6732 if (debug_sym)
6733 emit_symbol_size (acfg, debug_sym, ".");
6736 if (acfg->thumb_mixed) {
6737 /* Make sure the ARM symbols don't alias the thumb ones */
6738 emit_zero_bytes (acfg, 16);
6741 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6742 * code.
6744 for (i = 0; i < acfg->plt_offset; ++i) {
6745 char *debug_sym = NULL;
6746 MonoPltEntry *plt_entry = NULL;
6748 if (i == 0)
6749 continue;
6751 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6753 /* Skip plt entries not actually called by LLVM code */
6754 if (!plt_entry->llvm_used)
6755 continue;
6757 if (acfg->aot_opts.write_symbols) {
6758 if (plt_entry->debug_sym)
6759 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6762 if (debug_sym) {
6763 #if defined(TARGET_MACH)
6764 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6765 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6766 #endif
6767 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6768 emit_label (acfg, debug_sym);
6770 fprintf (acfg->fp, "\n.thumb_func\n");
6772 emit_label (acfg, plt_entry->llvm_symbol);
6774 if (acfg->llvm)
6775 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6777 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6779 if (debug_sym) {
6780 emit_symbol_size (acfg, debug_sym, ".");
6781 g_free (debug_sym);
6786 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6788 emit_info_symbol (acfg, "plt_end");
6790 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
6794 * emit_trampoline_full:
6796 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6797 * create_jit_info_for_trampoline ().
6799 static G_GNUC_UNUSED void
6800 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6802 char start_symbol [MAX_SYMBOL_SIZE];
6803 char end_symbol [MAX_SYMBOL_SIZE];
6804 char symbol [MAX_SYMBOL_SIZE];
6805 guint32 buf_size, info_offset;
6806 MonoJumpInfo *patch_info;
6807 guint8 *buf, *p;
6808 GPtrArray *patches;
6809 char *name;
6810 guint8 *code;
6811 guint32 code_size;
6812 MonoJumpInfo *ji;
6813 GSList *unwind_ops;
6815 g_assert (info);
6817 name = info->name;
6818 code = info->code;
6819 code_size = info->code_size;
6820 ji = info->ji;
6821 unwind_ops = info->unwind_ops;
6823 /* Emit code */
6825 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6827 emit_section_change (acfg, ".text", 0);
6828 emit_global (acfg, start_symbol, TRUE);
6829 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6830 emit_label (acfg, start_symbol);
6832 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6833 emit_label (acfg, symbol);
6836 * The code should access everything through the GOT, so we pass
6837 * TRUE here.
6839 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6841 emit_symbol_size (acfg, start_symbol, ".");
6843 if (emit_tinfo) {
6844 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6845 emit_label (acfg, end_symbol);
6848 /* Emit info */
6850 /* Sort relocations */
6851 patches = g_ptr_array_new ();
6852 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6853 if (patch_info->type != MONO_PATCH_INFO_NONE)
6854 g_ptr_array_add (patches, patch_info);
6855 g_ptr_array_sort (patches, compare_patches);
6857 buf_size = patches->len * 128 + 128;
6858 buf = (guint8 *)g_malloc (buf_size);
6859 p = buf;
6861 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6862 g_assert (p - buf < buf_size);
6863 g_ptr_array_free (patches, TRUE);
6865 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6867 info_offset = add_to_blob (acfg, buf, p - buf);
6869 emit_section_change (acfg, RODATA_SECT, 0);
6870 emit_global (acfg, symbol, FALSE);
6871 emit_label (acfg, symbol);
6873 emit_int32 (acfg, info_offset);
6875 if (emit_tinfo) {
6876 guint8 *encoded;
6877 guint32 encoded_len;
6878 guint32 uw_offset;
6881 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6883 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6884 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6885 g_free (encoded);
6887 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6888 emit_int32 (acfg, uw_offset);
6891 /* Emit debug info */
6892 if (unwind_ops) {
6893 char symbol2 [MAX_SYMBOL_SIZE];
6895 sprintf (symbol, "%s", name);
6896 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6898 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
6900 if (acfg->dwarf)
6901 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6904 g_free (buf);
6907 static G_GNUC_UNUSED void
6908 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6910 emit_trampoline_full (acfg, got_offset, info, TRUE);
6913 static void
6914 emit_trampolines (MonoAotCompile *acfg)
6916 char symbol [MAX_SYMBOL_SIZE];
6917 char end_symbol [MAX_SYMBOL_SIZE];
6918 int i, tramp_got_offset;
6919 int ntype;
6920 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6921 int tramp_type;
6922 #endif
6924 if ((!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only) && !acfg->aot_opts.interp)
6925 return;
6927 g_assert (acfg->image->assembly);
6929 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6930 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6931 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6932 MonoTrampInfo *info;
6935 * Emit the generic trampolines.
6937 * We could save some code by treating the generic trampolines as a wrapper
6938 * method, but that approach has its own complexities, so we choose the simpler
6939 * method.
6941 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6942 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6943 #ifdef DISABLE_REMOTING
6944 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6945 continue;
6946 #endif
6947 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6948 emit_trampoline (acfg, acfg->got_offset, info);
6949 mono_tramp_info_free (info);
6952 /* Emit the exception related code pieces */
6953 mono_arch_get_restore_context (&info, TRUE);
6954 emit_trampoline (acfg, acfg->got_offset, info);
6955 mono_tramp_info_free (info);
6957 mono_arch_get_call_filter (&info, TRUE);
6958 emit_trampoline (acfg, acfg->got_offset, info);
6959 mono_tramp_info_free (info);
6961 mono_arch_get_throw_exception (&info, TRUE);
6962 emit_trampoline (acfg, acfg->got_offset, info);
6963 mono_tramp_info_free (info);
6965 mono_arch_get_rethrow_exception (&info, TRUE);
6966 emit_trampoline (acfg, acfg->got_offset, info);
6967 mono_tramp_info_free (info);
6969 mono_arch_get_throw_corlib_exception (&info, TRUE);
6970 emit_trampoline (acfg, acfg->got_offset, info);
6971 mono_tramp_info_free (info);
6973 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6974 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6975 emit_trampoline (acfg, acfg->got_offset, info);
6976 mono_tramp_info_free (info);
6978 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6979 emit_trampoline (acfg, acfg->got_offset, info);
6980 mono_tramp_info_free (info);
6981 #endif
6983 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6984 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6985 if (info) {
6986 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6988 /* Create a separate out trampoline for more information in stack traces */
6989 info->name = g_strdup ("gsharedvt_out_trampoline");
6990 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6991 mono_tramp_info_free (info);
6993 #endif
6995 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6997 GSList *l = mono_arch_get_trampolines (TRUE);
6999 while (l) {
7000 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7002 emit_trampoline (acfg, acfg->got_offset, info);
7003 l = l->next;
7006 #endif
7008 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7009 int offset;
7011 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7012 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7013 emit_trampoline (acfg, acfg->got_offset, info);
7014 mono_tramp_info_free (info);
7016 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7017 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7018 emit_trampoline (acfg, acfg->got_offset, info);
7019 mono_tramp_info_free (info);
7022 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7023 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7024 emit_trampoline (acfg, acfg->got_offset, info);
7025 mono_tramp_info_free (info);
7026 #endif
7029 GSList *l;
7031 /* delegate_invoke_impl trampolines */
7032 l = mono_arch_get_delegate_invoke_impls ();
7033 while (l) {
7034 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7036 emit_trampoline (acfg, acfg->got_offset, info);
7037 l = l->next;
7041 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
7042 mono_arch_get_interp_to_native_trampoline (&info);
7043 emit_trampoline (acfg, acfg->got_offset, info);
7046 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7048 /* Emit trampolines which are numerous */
7051 * These include the following:
7052 * - specific trampolines
7053 * - static rgctx invoke trampolines
7054 * - imt trampolines
7055 * These trampolines have the same code, they are parameterized by GOT
7056 * slots.
7057 * They are defined in this file, in the arch_... routines instead of
7058 * in tramp-<ARCH>.c, since it is easier to do it this way.
7062 * When running in aot-only mode, we can't create specific trampolines at
7063 * runtime, so we create a few, and save them in the AOT file.
7064 * Normal trampolines embed their argument as a literal inside the
7065 * trampoline code, we can't do that here, so instead we embed an offset
7066 * which needs to be added to the trampoline address to get the address of
7067 * the GOT slot which contains the argument value.
7068 * The generated trampolines jump to the generic trampolines using another
7069 * GOT slot, which will be setup by the AOT loader to point to the
7070 * generic trampoline code of the given type.
7074 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7075 * each class).
7078 emit_section_change (acfg, ".text", 0);
7080 tramp_got_offset = acfg->got_offset;
7082 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7083 switch (ntype) {
7084 case MONO_AOT_TRAMP_SPECIFIC:
7085 sprintf (symbol, "specific_trampolines");
7086 break;
7087 case MONO_AOT_TRAMP_STATIC_RGCTX:
7088 sprintf (symbol, "static_rgctx_trampolines");
7089 break;
7090 case MONO_AOT_TRAMP_IMT:
7091 sprintf (symbol, "imt_trampolines");
7092 break;
7093 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7094 sprintf (symbol, "gsharedvt_arg_trampolines");
7095 break;
7096 default:
7097 g_assert_not_reached ();
7100 sprintf (end_symbol, "%s_e", symbol);
7102 if (acfg->aot_opts.write_symbols)
7103 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7105 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7106 emit_info_symbol (acfg, symbol);
7108 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7110 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7111 int tramp_size = 0;
7113 switch (ntype) {
7114 case MONO_AOT_TRAMP_SPECIFIC:
7115 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7116 tramp_got_offset += 2;
7117 break;
7118 case MONO_AOT_TRAMP_STATIC_RGCTX:
7119 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7120 tramp_got_offset += 2;
7121 break;
7122 case MONO_AOT_TRAMP_IMT:
7123 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7124 tramp_got_offset += 1;
7125 break;
7126 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7127 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7128 tramp_got_offset += 2;
7129 break;
7130 default:
7131 g_assert_not_reached ();
7133 if (!acfg->trampoline_size [ntype]) {
7134 g_assert (tramp_size);
7135 acfg->trampoline_size [ntype] = tramp_size;
7139 emit_label (acfg, end_symbol);
7140 emit_int32 (acfg, 0);
7143 arch_emit_specific_trampoline_pages (acfg);
7145 /* Reserve some entries at the end of the GOT for our use */
7146 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7149 acfg->got_offset += acfg->num_trampoline_got_entries;
7152 static gboolean
7153 str_begins_with (const char *str1, const char *str2)
7155 int len = strlen (str2);
7156 return strncmp (str1, str2, len) == 0;
7159 void*
7160 mono_aot_readonly_field_override (MonoClassField *field)
7162 ReadOnlyValue *rdv;
7163 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7164 char *p = rdv->name;
7165 int len;
7166 len = strlen (m_class_get_name_space (field->parent));
7167 if (strncmp (p, m_class_get_name_space (field->parent), len))
7168 continue;
7169 p += len;
7170 if (*p++ != '.')
7171 continue;
7172 len = strlen (m_class_get_name (field->parent));
7173 if (strncmp (p, m_class_get_name (field->parent), len))
7174 continue;
7175 p += len;
7176 if (*p++ != '.')
7177 continue;
7178 if (strcmp (p, field->name))
7179 continue;
7180 switch (rdv->type) {
7181 case MONO_TYPE_I1:
7182 return &rdv->value.i1;
7183 case MONO_TYPE_I2:
7184 return &rdv->value.i2;
7185 case MONO_TYPE_I4:
7186 return &rdv->value.i4;
7187 default:
7188 break;
7191 return NULL;
7194 static void
7195 add_readonly_value (MonoAotOptions *opts, const char *val)
7197 ReadOnlyValue *rdv;
7198 const char *fval;
7199 const char *tval;
7200 /* the format of val is:
7201 * namespace.typename.fieldname=type/value
7202 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7204 fval = strrchr (val, '/');
7205 if (!fval) {
7206 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7207 exit (1);
7209 tval = strrchr (val, '=');
7210 if (!tval) {
7211 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7212 exit (1);
7214 rdv = g_new0 (ReadOnlyValue, 1);
7215 rdv->name = (char *)g_malloc0 (tval - val + 1);
7216 memcpy (rdv->name, val, tval - val);
7217 tval++;
7218 fval++;
7219 if (strncmp (tval, "i1", 2) == 0) {
7220 rdv->value.i1 = atoi (fval);
7221 rdv->type = MONO_TYPE_I1;
7222 } else if (strncmp (tval, "i2", 2) == 0) {
7223 rdv->value.i2 = atoi (fval);
7224 rdv->type = MONO_TYPE_I2;
7225 } else if (strncmp (tval, "i4", 2) == 0) {
7226 rdv->value.i4 = atoi (fval);
7227 rdv->type = MONO_TYPE_I4;
7228 } else {
7229 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7230 exit (1);
7232 rdv->next = readonly_values;
7233 readonly_values = rdv;
7236 static gchar *
7237 clean_path (gchar * path)
7239 if (!path)
7240 return NULL;
7242 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7243 return path;
7245 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7246 g_free (path);
7248 return clean;
7251 static gchar *
7252 wrap_path (gchar * path)
7254 int len;
7255 if (!path)
7256 return NULL;
7258 // If the string contains no spaces, just return the original string.
7259 if (strstr (path, " ") == NULL)
7260 return path;
7262 // If the string is already wrapped in quotes, return it.
7263 len = strlen (path);
7264 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7265 return path;
7267 // If the string contains spaces, then wrap it in quotes.
7268 gchar *clean = g_strdup_printf ("\"%s\"", path);
7270 return clean;
7273 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7274 static void
7275 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7277 ptrdiff_t len = end-start;
7278 if (len > 0)
7279 g_ptr_array_add (args, g_strndup (start, len));
7282 static GPtrArray *
7283 mono_aot_split_options (const char *aot_options)
7285 enum MonoAotOptionState {
7286 MONO_AOT_OPTION_STATE_DEFAULT,
7287 MONO_AOT_OPTION_STATE_STRING,
7288 MONO_AOT_OPTION_STATE_ESCAPE,
7291 GPtrArray *args = g_ptr_array_new ();
7292 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7293 gchar const *opt_start = aot_options;
7294 gboolean end_of_string = FALSE;
7295 gchar cur;
7297 g_return_val_if_fail (aot_options != NULL, NULL);
7299 while ((cur = *aot_options) != '\0') {
7300 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7301 goto next;
7303 switch (cur) {
7304 case '"':
7305 // If we find a quote, then if we're in the default case then
7306 // it means we've found the start of a string, if not then it
7307 // means we've found the end of the string and should switch
7308 // back to the default case.
7309 switch (state) {
7310 case MONO_AOT_OPTION_STATE_DEFAULT:
7311 state = MONO_AOT_OPTION_STATE_STRING;
7312 break;
7313 case MONO_AOT_OPTION_STATE_STRING:
7314 state = MONO_AOT_OPTION_STATE_DEFAULT;
7315 break;
7316 case MONO_AOT_OPTION_STATE_ESCAPE:
7317 g_assert_not_reached ();
7318 break;
7320 break;
7321 case '\\':
7322 // If we've found an escaping operator, then this means we
7323 // should not process the next character if inside a string.
7324 if (state == MONO_AOT_OPTION_STATE_STRING)
7325 state = MONO_AOT_OPTION_STATE_ESCAPE;
7326 break;
7327 case ',':
7328 // If we're in the default state then this means we've found
7329 // an option, store it for later processing.
7330 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7331 goto new_opt;
7332 break;
7335 next:
7336 aot_options++;
7337 restart:
7338 // If the next character is end of string, then process the last option.
7339 if (*(aot_options) == '\0') {
7340 end_of_string = TRUE;
7341 goto new_opt;
7343 continue;
7345 new_opt:
7346 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7347 opt_start = ++aot_options;
7348 if (end_of_string)
7349 break;
7350 goto restart; // Check for null and continue loop
7353 return args;
7356 static void
7357 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7359 GPtrArray* args;
7361 args = mono_aot_split_options (aot_options ? aot_options : "");
7362 for (int i = 0; i < args->len; ++i) {
7363 const char *arg = (const char *)g_ptr_array_index (args, i);
7365 if (str_begins_with (arg, "outfile=")) {
7366 opts->outfile = g_strdup (arg + strlen ("outfile="));
7367 } else if (str_begins_with (arg, "llvm-outfile=")) {
7368 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7369 } else if (str_begins_with (arg, "temp-path=")) {
7370 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7371 } else if (str_begins_with (arg, "save-temps")) {
7372 opts->save_temps = TRUE;
7373 } else if (str_begins_with (arg, "keep-temps")) {
7374 opts->save_temps = TRUE;
7375 } else if (str_begins_with (arg, "write-symbols")) {
7376 opts->write_symbols = TRUE;
7377 } else if (str_begins_with (arg, "no-write-symbols")) {
7378 opts->write_symbols = FALSE;
7379 // Intentionally undocumented -- one-off experiment
7380 } else if (str_begins_with (arg, "metadata-only")) {
7381 opts->metadata_only = TRUE;
7382 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7383 opts->bind_to_runtime_version = TRUE;
7384 } else if (str_begins_with (arg, "full")) {
7385 opts->mode = MONO_AOT_MODE_FULL;
7386 } else if (str_begins_with (arg, "hybrid")) {
7387 opts->mode = MONO_AOT_MODE_HYBRID;
7388 } else if (str_begins_with (arg, "interp")) {
7389 opts->interp = TRUE;
7390 } else if (str_begins_with (arg, "threads=")) {
7391 opts->nthreads = atoi (arg + strlen ("threads="));
7392 } else if (str_begins_with (arg, "static")) {
7393 opts->static_link = TRUE;
7394 opts->no_dlsym = TRUE;
7395 } else if (str_begins_with (arg, "asmonly")) {
7396 opts->asm_only = TRUE;
7397 } else if (str_begins_with (arg, "asmwriter")) {
7398 opts->asm_writer = TRUE;
7399 } else if (str_begins_with (arg, "nodebug")) {
7400 opts->nodebug = TRUE;
7401 } else if (str_begins_with (arg, "dwarfdebug")) {
7402 opts->dwarf_debug = TRUE;
7403 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7404 } else if (str_begins_with (arg, "nopagetrampolines")) {
7405 opts->use_trampolines_page = FALSE;
7406 } else if (str_begins_with (arg, "ntrampolines=")) {
7407 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7408 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7409 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7410 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7411 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7412 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7413 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7414 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7415 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7416 } else if (str_begins_with (arg, "tool-prefix=")) {
7417 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7418 } else if (str_begins_with (arg, "ld-flags=")) {
7419 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7420 } else if (str_begins_with (arg, "soft-debug")) {
7421 opts->soft_debug = TRUE;
7422 // Intentionally undocumented x2-- deprecated
7423 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7424 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7425 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7426 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7427 } else if (str_begins_with (arg, "msym-dir=")) {
7428 mini_debug_options.no_seq_points_compact_data = FALSE;
7429 opts->gen_msym_dir = TRUE;
7430 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7431 } else if (str_begins_with (arg, "direct-pinvoke")) {
7432 opts->direct_pinvoke = TRUE;
7433 } else if (str_begins_with (arg, "direct-icalls")) {
7434 opts->direct_icalls = TRUE;
7435 } else if (str_begins_with (arg, "no-direct-calls")) {
7436 opts->no_direct_calls = TRUE;
7437 } else if (str_begins_with (arg, "print-skipped")) {
7438 opts->print_skipped_methods = TRUE;
7439 } else if (str_begins_with (arg, "stats")) {
7440 opts->stats = TRUE;
7441 // Intentionally undocumented-- has no known function other than to debug the compiler
7442 } else if (str_begins_with (arg, "no-instances")) {
7443 opts->no_instances = TRUE;
7444 // Intentionally undocumented x4-- Used for internal debugging of compiler
7445 } else if (str_begins_with (arg, "log-generics")) {
7446 opts->log_generics = TRUE;
7447 } else if (str_begins_with (arg, "log-instances=")) {
7448 opts->log_instances = TRUE;
7449 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7450 } else if (str_begins_with (arg, "log-instances")) {
7451 opts->log_instances = TRUE;
7452 } else if (str_begins_with (arg, "internal-logfile=")) {
7453 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7454 } else if (str_begins_with (arg, "dedup-skip")) {
7455 opts->dedup = TRUE;
7456 } else if (str_begins_with (arg, "dedup-include=")) {
7457 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
7458 } else if (str_begins_with (arg, "mtriple=")) {
7459 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7460 } else if (str_begins_with (arg, "llvm-path=")) {
7461 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7462 } else if (!strcmp (arg, "llvm")) {
7463 opts->llvm = TRUE;
7464 } else if (str_begins_with (arg, "readonly-value=")) {
7465 add_readonly_value (opts, arg + strlen ("readonly-value="));
7466 } else if (str_begins_with (arg, "info")) {
7467 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7468 exit (0);
7469 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7470 } else if (str_begins_with (arg, "gc-maps")) {
7471 mini_gc_enable_gc_maps_for_aot ();
7472 // Intentionally undocumented: Used for internal debugging
7473 } else if (str_begins_with (arg, "dump")) {
7474 opts->dump_json = TRUE;
7475 } else if (str_begins_with (arg, "llvmonly")) {
7476 opts->mode = MONO_AOT_MODE_FULL;
7477 opts->llvm = TRUE;
7478 opts->llvm_only = TRUE;
7479 } else if (str_begins_with (arg, "data-outfile=")) {
7480 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7481 } else if (str_begins_with (arg, "profile=")) {
7482 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7483 } else if (!strcmp (arg, "profile-only")) {
7484 opts->profile_only = TRUE;
7485 } else if (!strcmp (arg, "verbose")) {
7486 opts->verbose = TRUE;
7487 } else if (str_begins_with (arg, "llvmopts=")){
7488 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
7489 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7490 printf ("Supported options for --aot:\n");
7491 printf (" asmonly\n");
7492 printf (" bind-to-runtime-version\n");
7493 printf (" bitcode\n");
7494 printf (" data-outfile=\n");
7495 printf (" direct-icalls\n");
7496 printf (" direct-pinvoke\n");
7497 printf (" dwarfdebug\n");
7498 printf (" full\n");
7499 printf (" hybrid\n");
7500 printf (" info\n");
7501 printf (" keep-temps\n");
7502 printf (" llvm\n");
7503 printf (" llvmonly\n");
7504 printf (" llvm-outfile=\n");
7505 printf (" llvm-path=\n");
7506 printf (" msym-dir=\n");
7507 printf (" mtriple\n");
7508 printf (" nimt-trampolines=\n");
7509 printf (" nodebug\n");
7510 printf (" no-direct-calls\n");
7511 printf (" no-write-symbols\n");
7512 printf (" nrgctx-trampolines=\n");
7513 printf (" nrgctx-fetch-trampolines=\n");
7514 printf (" ngsharedvt-trampolines=\n");
7515 printf (" ntrampolines=\n");
7516 printf (" outfile=\n");
7517 printf (" profile=\n");
7518 printf (" profile-only\n");
7519 printf (" print-skipped-methods\n");
7520 printf (" readonly-value=\n");
7521 printf (" save-temps\n");
7522 printf (" soft-debug\n");
7523 printf (" static\n");
7524 printf (" stats\n");
7525 printf (" temp-path=\n");
7526 printf (" tool-prefix=\n");
7527 printf (" threads=\n");
7528 printf (" write-symbols\n");
7529 printf (" verbose\n");
7530 printf (" help/?\n");
7531 exit (0);
7532 } else {
7533 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7534 exit (1);
7537 g_free ((gpointer) arg);
7540 if (opts->use_trampolines_page) {
7541 opts->ntrampolines = 0;
7542 opts->nrgctx_trampolines = 0;
7543 opts->nimt_trampolines = 0;
7544 opts->ngsharedvt_arg_trampolines = 0;
7547 g_ptr_array_free (args, /*free_seg=*/TRUE);
7550 static void
7551 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7553 MonoMethod *method = (MonoMethod*)key;
7554 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7555 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7556 MonoJumpInfoToken *new_ji;
7558 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7559 new_ji->image = ji->image;
7560 new_ji->token = ji->token;
7561 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7564 static gboolean
7565 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7567 if (m_class_get_type_token (klass))
7568 return TRUE;
7569 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR))
7570 return TRUE;
7571 if (m_class_get_rank (klass))
7572 return can_encode_class (acfg, m_class_get_element_class (klass));
7573 return FALSE;
7576 static gboolean
7577 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7579 if (method->wrapper_type) {
7580 switch (method->wrapper_type) {
7581 case MONO_WRAPPER_NONE:
7582 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7583 case MONO_WRAPPER_XDOMAIN_INVOKE:
7584 case MONO_WRAPPER_STFLD:
7585 case MONO_WRAPPER_LDFLD:
7586 case MONO_WRAPPER_LDFLDA:
7587 case MONO_WRAPPER_STELEMREF:
7588 case MONO_WRAPPER_PROXY_ISINST:
7589 case MONO_WRAPPER_ALLOC:
7590 case MONO_WRAPPER_REMOTING_INVOKE:
7591 case MONO_WRAPPER_UNKNOWN:
7592 case MONO_WRAPPER_WRITE_BARRIER:
7593 case MONO_WRAPPER_DELEGATE_INVOKE:
7594 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7595 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7596 case MONO_WRAPPER_SYNCHRONIZED:
7597 break;
7598 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7599 case MONO_WRAPPER_CASTCLASS: {
7600 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7602 if (info)
7603 return TRUE;
7604 else
7605 return FALSE;
7606 break;
7608 default:
7609 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7610 return FALSE;
7612 } else {
7613 if (!method->token) {
7614 /* The method is part of a constructed type like Int[,].Set (). */
7615 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7616 if (m_class_get_rank (method->klass))
7617 return TRUE;
7618 return FALSE;
7622 return TRUE;
7625 static gboolean
7626 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7628 switch (patch_info->type) {
7629 case MONO_PATCH_INFO_METHOD:
7630 case MONO_PATCH_INFO_METHODCONST:
7631 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7632 MonoMethod *method = patch_info->data.method;
7634 return can_encode_method (acfg, method);
7636 case MONO_PATCH_INFO_VTABLE:
7637 case MONO_PATCH_INFO_CLASS:
7638 case MONO_PATCH_INFO_IID:
7639 case MONO_PATCH_INFO_ADJUSTED_IID:
7640 if (!can_encode_class (acfg, patch_info->data.klass)) {
7641 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7642 return FALSE;
7644 break;
7645 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7646 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7647 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7648 return FALSE;
7650 break;
7652 case MONO_PATCH_INFO_RGCTX_FETCH:
7653 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7654 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7656 if (!can_encode_method (acfg, entry->method))
7657 return FALSE;
7658 if (!can_encode_patch (acfg, entry->data))
7659 return FALSE;
7660 break;
7662 default:
7663 break;
7666 return TRUE;
7669 static gboolean
7670 is_concrete_type (MonoType *t)
7672 MonoClass *klass;
7673 int i;
7675 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7676 return FALSE;
7677 if (t->type == MONO_TYPE_GENERICINST) {
7678 MonoGenericContext *orig_ctx;
7679 MonoGenericInst *inst;
7680 MonoType *arg;
7682 if (!MONO_TYPE_ISSTRUCT (t))
7683 return TRUE;
7684 klass = mono_class_from_mono_type (t);
7685 orig_ctx = &mono_class_get_generic_class (klass)->context;
7687 inst = orig_ctx->class_inst;
7688 if (inst) {
7689 for (i = 0; i < inst->type_argc; ++i) {
7690 arg = mini_get_underlying_type (inst->type_argv [i]);
7691 if (!is_concrete_type (arg))
7692 return FALSE;
7695 inst = orig_ctx->method_inst;
7696 if (inst) {
7697 for (i = 0; i < inst->type_argc; ++i) {
7698 arg = mini_get_underlying_type (inst->type_argv [i]);
7699 if (!is_concrete_type (arg))
7700 return FALSE;
7704 return TRUE;
7707 /* LOCKING: Assumes the loader lock is held */
7708 static void
7709 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
7711 MonoMethod *wrapper;
7712 gboolean concrete = TRUE;
7713 gboolean add_in = gsharedvt_in;
7714 gboolean add_out = gsharedvt_out;
7716 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7717 add_in = FALSE;
7718 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7719 add_out = FALSE;
7721 if (!add_in && !add_out)
7722 return;
7724 if (mini_is_gsharedvt_variable_signature (sig))
7725 return;
7727 if (add_in)
7728 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7729 if (add_out)
7730 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7732 if (sig->has_type_parameters) {
7733 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
7734 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7735 int i;
7737 //printf ("%s\n", mono_signature_full_name (sig));
7739 copy->ret = mini_get_underlying_type (sig->ret);
7740 if (!is_concrete_type (copy->ret))
7741 concrete = FALSE;
7742 for (i = 0; i < sig->param_count; ++i) {
7743 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7744 if (!is_concrete_type (copy->params [i]))
7745 concrete = FALSE;
7747 copy->has_type_parameters = 0;
7748 if (!concrete)
7749 return;
7750 sig = copy;
7753 //printf ("%s\n", mono_signature_full_name (sig));
7755 if (gsharedvt_in) {
7756 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7757 add_extra_method (acfg, wrapper);
7759 if (gsharedvt_out) {
7760 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7761 add_extra_method (acfg, wrapper);
7763 if (interp_in) {
7764 wrapper = mini_get_interp_in_wrapper (sig);
7765 add_extra_method (acfg, wrapper);
7766 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
7771 * compile_method:
7773 * AOT compile a given method.
7774 * This function might be called by multiple threads, so it must be thread-safe.
7776 static void
7777 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7779 MonoCompile *cfg;
7780 MonoJumpInfo *patch_info;
7781 gboolean skip;
7782 int index, depth;
7783 MonoMethod *wrapped;
7784 GTimer *jit_timer;
7785 JitFlags flags;
7787 if (acfg->aot_opts.metadata_only)
7788 return;
7790 mono_acfg_lock (acfg);
7791 index = get_method_index (acfg, method);
7792 mono_acfg_unlock (acfg);
7794 /* fixme: maybe we can also precompile wrapper methods */
7795 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7796 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7797 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7798 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7799 return;
7802 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7803 return;
7805 wrapped = mono_marshal_method_from_wrapper (method);
7806 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7807 // FIXME: The wrapper should be generic too, but it is not
7808 return;
7810 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7811 return;
7813 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7814 return;
7816 mono_atomic_inc_i32 (&acfg->stats.mcount);
7818 #if 0
7819 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7820 mono_atomic_inc_i32 (&acfg->stats.genericcount);
7821 return;
7823 #endif
7825 //acfg->aot_opts.print_skipped_methods = TRUE;
7828 * Since these methods are the only ones which are compiled with
7829 * AOT support, and they are not used by runtime startup/shutdown code,
7830 * the runtime will not see AOT methods during AOT compilation,so it
7831 * does not need to support them by creating a fake GOT etc.
7833 flags = JIT_FLAG_AOT;
7834 if (mono_aot_mode_is_full (&acfg->aot_opts))
7835 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7836 if (acfg->llvm)
7837 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7838 if (acfg->aot_opts.llvm_only)
7839 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7840 if (acfg->aot_opts.no_direct_calls)
7841 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7842 if (acfg->aot_opts.direct_pinvoke)
7843 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7845 jit_timer = mono_time_track_start ();
7846 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7847 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7849 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7850 if (acfg->aot_opts.print_skipped_methods)
7851 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7852 mono_atomic_inc_i32 (&acfg->stats.genericcount);
7853 return;
7855 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7856 /* Some instances cannot be JITted due to constraints etc. */
7857 if (!method->is_inflated)
7858 report_loader_error (acfg, &cfg->error, FALSE, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (&cfg->error));
7859 /* Let the exception happen at runtime */
7860 return;
7863 if (cfg->disable_aot) {
7864 if (acfg->aot_opts.print_skipped_methods)
7865 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7866 mono_atomic_inc_i32 (&acfg->stats.ocount);
7867 return;
7869 cfg->method_index = index;
7871 /* Nullify patches which need no aot processing */
7872 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7873 switch (patch_info->type) {
7874 case MONO_PATCH_INFO_LABEL:
7875 case MONO_PATCH_INFO_BB:
7876 patch_info->type = MONO_PATCH_INFO_NONE;
7877 break;
7878 default:
7879 break;
7883 /* Collect method->token associations from the cfg */
7884 mono_acfg_lock (acfg);
7885 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7886 mono_acfg_unlock (acfg);
7887 g_hash_table_destroy (cfg->token_info_hash);
7888 cfg->token_info_hash = NULL;
7891 * Check for absolute addresses.
7893 skip = FALSE;
7894 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7895 switch (patch_info->type) {
7896 case MONO_PATCH_INFO_ABS:
7897 /* unable to handle this */
7898 skip = TRUE;
7899 break;
7900 default:
7901 break;
7905 if (skip) {
7906 if (acfg->aot_opts.print_skipped_methods)
7907 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7908 mono_atomic_inc_i32 (&acfg->stats.abscount);
7909 return;
7912 /* Lock for the rest of the code */
7913 mono_acfg_lock (acfg);
7915 if (cfg->gsharedvt)
7916 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7917 else if (cfg->gshared)
7918 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7919 else if (cfg->method->wrapper_type)
7920 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7921 else
7922 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7925 * Check for methods/klasses we can't encode.
7927 skip = FALSE;
7928 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7929 if (!can_encode_patch (acfg, patch_info))
7930 skip = TRUE;
7933 if (skip) {
7934 if (acfg->aot_opts.print_skipped_methods)
7935 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7936 acfg->stats.ocount++;
7937 mono_acfg_unlock (acfg);
7938 return;
7941 if (!cfg->compile_llvm)
7942 acfg->has_jitted_code = TRUE;
7944 if (method->is_inflated && acfg->aot_opts.log_instances) {
7945 if (acfg->instances_logfile)
7946 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7947 else
7948 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7951 /* Adds generic instances referenced by this method */
7953 * The depth is used to avoid infinite loops when generic virtual recursion is
7954 * encountered.
7956 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7957 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
7958 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7959 switch (patch_info->type) {
7960 case MONO_PATCH_INFO_RGCTX_FETCH:
7961 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7962 case MONO_PATCH_INFO_METHOD:
7963 case MONO_PATCH_INFO_METHOD_RGCTX: {
7964 MonoMethod *m = NULL;
7966 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7967 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7969 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7970 m = e->data->data.method;
7971 } else {
7972 m = patch_info->data.method;
7975 if (!m)
7976 break;
7977 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
7978 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7979 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7980 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7981 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7982 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7983 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7984 } else {
7985 add_extra_method_with_depth (acfg, m, depth + 1);
7986 add_types_from_method_header (acfg, m);
7989 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7991 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7992 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7994 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7995 add_extra_method_with_depth (acfg, m, depth + 1);
7997 break;
7999 case MONO_PATCH_INFO_VTABLE: {
8000 MonoClass *klass = patch_info->data.klass;
8002 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8003 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8004 break;
8006 case MONO_PATCH_INFO_SFLDA: {
8007 MonoClass *klass = patch_info->data.field->parent;
8009 /* The .cctor needs to run at runtime. */
8010 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))
8011 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8012 break;
8014 default:
8015 break;
8020 /* Determine whenever the method has GOT slots */
8021 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8022 switch (patch_info->type) {
8023 case MONO_PATCH_INFO_GOT_OFFSET:
8024 case MONO_PATCH_INFO_NONE:
8025 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8026 case MONO_PATCH_INFO_GC_NURSERY_START:
8027 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8028 break;
8029 case MONO_PATCH_INFO_IMAGE:
8030 /* The assembly is stored in GOT slot 0 */
8031 if (patch_info->data.image != acfg->image)
8032 cfg->has_got_slots = TRUE;
8033 break;
8034 default:
8035 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8036 cfg->has_got_slots = TRUE;
8037 break;
8041 if (!cfg->has_got_slots)
8042 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8044 /* Add gsharedvt wrappers for signatures used by the method */
8045 if (acfg->aot_opts.llvm_only) {
8046 GSList *l;
8048 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8049 /* These only need out wrappers */
8050 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE, FALSE);
8052 for (l = cfg->signatures; l; l = l->next) {
8053 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8055 /* These only need in wrappers */
8056 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8058 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8059 /* The interpreter uses these wrappers to call aot-ed code */
8060 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8061 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE, TRUE);
8065 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8067 /* Make a copy of the patch info which is in the mempool */
8069 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8071 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8072 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8074 if (!patches)
8075 patches = new_patch_info;
8076 else
8077 patches_end->next = new_patch_info;
8078 patches_end = new_patch_info;
8080 cfg->patch_info = patches;
8082 /* Make a copy of the unwind info */
8084 GSList *l, *unwind_ops;
8085 MonoUnwindOp *op;
8087 unwind_ops = NULL;
8088 for (l = cfg->unwind_ops; l; l = l->next) {
8089 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8090 memcpy (op, l->data, sizeof (MonoUnwindOp));
8091 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8093 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8095 /* Make a copy of the argument/local info */
8097 ERROR_DECL (error);
8098 MonoInst **args, **locals;
8099 MonoMethodSignature *sig;
8100 MonoMethodHeader *header;
8101 int i;
8103 sig = mono_method_signature (method);
8104 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8105 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8106 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8107 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8109 cfg->args = args;
8111 header = mono_method_get_header_checked (method, error);
8112 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8113 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8114 for (i = 0; i < header->num_locals; ++i) {
8115 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8116 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8118 mono_metadata_free_mh (header);
8119 cfg->locals = locals;
8122 /* Free some fields used by cfg to conserve memory */
8123 mono_empty_compile (cfg);
8125 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8127 while (index >= acfg->cfgs_size) {
8128 MonoCompile **new_cfgs;
8129 int new_size;
8131 new_size = acfg->cfgs_size * 2;
8132 new_cfgs = g_new0 (MonoCompile*, new_size);
8133 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8134 g_free (acfg->cfgs);
8135 acfg->cfgs = new_cfgs;
8136 acfg->cfgs_size = new_size;
8138 acfg->cfgs [index] = cfg;
8140 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8142 /* Update global stats while holding a lock. */
8143 mono_update_jit_stats (cfg);
8146 if (cfg->orig_method->wrapper_type)
8147 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8150 mono_acfg_unlock (acfg);
8152 mono_atomic_inc_i32 (&acfg->stats.ccount);
8155 static mono_thread_start_return_t WINAPI
8156 compile_thread_main (gpointer user_data)
8158 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8159 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8160 int i;
8162 ERROR_DECL (error);
8163 MonoInternalThread *internal = mono_thread_internal_current ();
8164 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8165 mono_error_assert_ok (error);
8166 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8167 mono_error_assert_ok (error);
8169 for (i = 0; i < methods->len; ++i)
8170 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8172 return 0;
8175 /* Used by the LLVM backend */
8176 guint32
8177 mono_aot_get_got_offset (MonoJumpInfo *ji)
8179 return get_got_offset (llvm_acfg, TRUE, ji);
8183 * mono_aot_is_shared_got_offset:
8185 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8186 * when the AOT image is loaded.
8188 gboolean
8189 mono_aot_is_shared_got_offset (int offset)
8191 return offset < llvm_acfg->nshared_got_entries;
8194 char*
8195 mono_aot_get_method_name (MonoCompile *cfg)
8197 if (llvm_acfg->aot_opts.static_link)
8198 /* Include the assembly name too to avoid duplicate symbol errors */
8199 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8200 else
8201 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8205 * mono_aot_is_linkonce_method:
8207 * Return whenever METHOD should be emitted with linkonce linkage,
8208 * eliminating duplicate copies when compiling in static mode.
8210 gboolean
8211 mono_aot_is_linkonce_method (MonoMethod *method)
8213 return FALSE;
8214 #if 0
8215 WrapperInfo *info;
8217 // FIXME: Add more cases
8218 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8219 return FALSE;
8220 info = mono_marshal_get_wrapper_info (method);
8221 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8222 return TRUE;
8223 return FALSE;
8224 #endif
8227 static gboolean
8228 append_mangled_type (GString *s, MonoType *t)
8230 if (t->byref)
8231 g_string_append_printf (s, "b");
8232 switch (t->type) {
8233 case MONO_TYPE_VOID:
8234 g_string_append_printf (s, "void_");
8235 break;
8236 case MONO_TYPE_I1:
8237 g_string_append_printf (s, "i1");
8238 break;
8239 case MONO_TYPE_U1:
8240 g_string_append_printf (s, "u1");
8241 break;
8242 case MONO_TYPE_I2:
8243 g_string_append_printf (s, "i2");
8244 break;
8245 case MONO_TYPE_U2:
8246 g_string_append_printf (s, "u2");
8247 break;
8248 case MONO_TYPE_I4:
8249 g_string_append_printf (s, "i4");
8250 break;
8251 case MONO_TYPE_U4:
8252 g_string_append_printf (s, "u4");
8253 break;
8254 case MONO_TYPE_I8:
8255 g_string_append_printf (s, "i8");
8256 break;
8257 case MONO_TYPE_U8:
8258 g_string_append_printf (s, "u8");
8259 break;
8260 case MONO_TYPE_I:
8261 g_string_append_printf (s, "ii");
8262 break;
8263 case MONO_TYPE_U:
8264 g_string_append_printf (s, "ui");
8265 break;
8266 case MONO_TYPE_R4:
8267 g_string_append_printf (s, "fl");
8268 break;
8269 case MONO_TYPE_R8:
8270 g_string_append_printf (s, "do");
8271 break;
8272 default: {
8273 char *fullname = mono_type_full_name (t);
8274 GString *temp;
8275 char *temps;
8276 int i, len;
8279 * Have to create a mangled name which is:
8280 * - a valid symbol
8281 * - unique
8283 temp = g_string_new ("");
8284 len = strlen (fullname);
8285 for (i = 0; i < len; ++i) {
8286 char c = fullname [i];
8287 if (isalnum (c)) {
8288 g_string_append_c (temp, c);
8289 } else if (c == '_') {
8290 g_string_append_c (temp, '_');
8291 g_string_append_c (temp, '_');
8292 } else {
8293 g_string_append_c (temp, '_');
8294 g_string_append_printf (temp, "%x", (int)c);
8297 temps = g_string_free (temp, FALSE);
8298 /* Include the length to avoid different length type names aliasing each other */
8299 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8300 g_free (temps);
8303 if (t->attrs)
8304 g_string_append_printf (s, "_attrs_%d", t->attrs);
8305 return TRUE;
8308 static gboolean
8309 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8311 int i;
8312 gboolean supported;
8314 supported = append_mangled_type (s, sig->ret);
8315 if (!supported)
8316 return FALSE;
8317 if (sig->hasthis)
8318 g_string_append_printf (s, "this_");
8319 if (sig->pinvoke)
8320 g_string_append_printf (s, "pinvoke_");
8321 for (i = 0; i < sig->param_count; ++i) {
8322 supported = append_mangled_type (s, sig->params [i]);
8323 if (!supported)
8324 return FALSE;
8327 return TRUE;
8330 static void
8331 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8333 const char *label;
8335 switch (wrapper_type) {
8336 case MONO_WRAPPER_REMOTING_INVOKE:
8337 label = "remoting_invoke";
8338 break;
8339 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8340 label = "remoting_invoke_check";
8341 break;
8342 case MONO_WRAPPER_XDOMAIN_INVOKE:
8343 label = "remoting_invoke_xdomain";
8344 break;
8345 case MONO_WRAPPER_PROXY_ISINST:
8346 label = "proxy_isinst";
8347 break;
8348 case MONO_WRAPPER_LDFLD:
8349 label = "ldfld";
8350 break;
8351 case MONO_WRAPPER_LDFLDA:
8352 label = "ldflda";
8353 break;
8354 case MONO_WRAPPER_STFLD:
8355 label = "stfld";
8356 break;
8357 case MONO_WRAPPER_ALLOC:
8358 label = "alloc";
8359 break;
8360 case MONO_WRAPPER_WRITE_BARRIER:
8361 label = "write_barrier";
8362 break;
8363 case MONO_WRAPPER_STELEMREF:
8364 label = "stelemref";
8365 break;
8366 case MONO_WRAPPER_UNKNOWN:
8367 label = "unknown";
8368 break;
8369 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8370 label = "man2native";
8371 break;
8372 case MONO_WRAPPER_SYNCHRONIZED:
8373 label = "synch";
8374 break;
8375 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8376 label = "man2man";
8377 break;
8378 case MONO_WRAPPER_CASTCLASS:
8379 label = "castclass";
8380 break;
8381 case MONO_WRAPPER_RUNTIME_INVOKE:
8382 label = "run_invoke";
8383 break;
8384 case MONO_WRAPPER_DELEGATE_INVOKE:
8385 label = "del_inv";
8386 break;
8387 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8388 label = "del_beg_inv";
8389 break;
8390 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8391 label = "del_end_inv";
8392 break;
8393 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8394 label = "native2man";
8395 break;
8396 default:
8397 g_assert_not_reached ();
8400 g_string_append_printf (s, "%s_", label);
8403 static void
8404 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8406 const char *label;
8408 switch (subtype)
8410 case WRAPPER_SUBTYPE_NONE:
8411 return;
8412 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8413 label = "elem_addr";
8414 break;
8415 case WRAPPER_SUBTYPE_STRING_CTOR:
8416 label = "str_ctor";
8417 break;
8418 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8419 label = "virt_stelem";
8420 break;
8421 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8422 label = "fast_mon_enter";
8423 break;
8424 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8425 label = "fast_mon_enter_4";
8426 break;
8427 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8428 label = "fast_monitor_exit";
8429 break;
8430 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8431 label = "ptr2struct";
8432 break;
8433 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8434 label = "struct2ptr";
8435 break;
8436 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8437 label = "castclass_w_cache";
8438 break;
8439 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8440 label = "isinst_w_cache";
8441 break;
8442 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8443 label = "run_inv_norm";
8444 break;
8445 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8446 label = "run_inv_dyn";
8447 break;
8448 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8449 label = "run_inv_dir";
8450 break;
8451 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8452 label = "run_inv_vir";
8453 break;
8454 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8455 label = "icall";
8456 break;
8457 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8458 label = "native_func_aot";
8459 break;
8460 case WRAPPER_SUBTYPE_PINVOKE:
8461 label = "pinvoke";
8462 break;
8463 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8464 label = "synch_inner";
8465 break;
8466 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8467 label = "gshared_in";
8468 break;
8469 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8470 label = "gshared_out";
8471 break;
8472 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8473 label = "array_acc";
8474 break;
8475 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8476 label = "generic_arry_help";
8477 break;
8478 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8479 label = "del_inv_virt";
8480 break;
8481 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8482 label = "del_inv_bound";
8483 break;
8484 case WRAPPER_SUBTYPE_INTERP_IN:
8485 label = "interp_in";
8486 break;
8487 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8488 label = "gsharedvt_in_sig";
8489 break;
8490 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8491 label = "gsharedvt_out_sig";
8492 break;
8493 default:
8494 g_assert_not_reached ();
8497 g_string_append_printf (s, "%s_", label);
8500 static char *
8501 sanitize_mangled_string (const char *input)
8503 GString *s = g_string_new ("");
8505 for (int i=0; input [i] != '\0'; i++) {
8506 char c = input [i];
8507 switch (c) {
8508 case '.':
8509 g_string_append (s, "_dot_");
8510 break;
8511 case ' ':
8512 g_string_append (s, "_");
8513 break;
8514 case '`':
8515 g_string_append (s, "_bt_");
8516 break;
8517 case '<':
8518 g_string_append (s, "_le_");
8519 break;
8520 case '>':
8521 g_string_append (s, "_gt_");
8522 break;
8523 case '/':
8524 g_string_append (s, "_sl_");
8525 break;
8526 case '[':
8527 g_string_append (s, "_lbrack_");
8528 break;
8529 case ']':
8530 g_string_append (s, "_rbrack_");
8531 break;
8532 case '(':
8533 g_string_append (s, "_lparen_");
8534 break;
8535 case '-':
8536 g_string_append (s, "_dash_");
8537 break;
8538 case ')':
8539 g_string_append (s, "_rparen_");
8540 break;
8541 case ',':
8542 g_string_append (s, "_comma_");
8543 break;
8544 case ':':
8545 g_string_append (s, "_colon_");
8546 break;
8547 default:
8548 g_string_append_c (s, c);
8552 return g_string_free (s, FALSE);
8555 static gboolean
8556 append_mangled_klass (GString *s, MonoClass *klass)
8558 char *klass_desc = mono_class_full_name (klass);
8559 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
8560 g_free (klass_desc);
8562 // Success
8563 return TRUE;
8566 static gboolean
8567 append_mangled_method (GString *s, MonoMethod *method);
8569 static gboolean
8570 append_mangled_wrapper (GString *s, MonoMethod *method)
8572 gboolean success = TRUE;
8573 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8574 g_string_append_printf (s, "wrapper_");
8575 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
8577 append_mangled_wrapper_type (s, method->wrapper_type);
8579 switch (method->wrapper_type) {
8580 case MONO_WRAPPER_REMOTING_INVOKE:
8581 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8582 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8583 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8584 g_assert (m);
8585 success = success && append_mangled_method (s, m);
8586 break;
8588 case MONO_WRAPPER_PROXY_ISINST:
8589 case MONO_WRAPPER_LDFLD:
8590 case MONO_WRAPPER_LDFLDA:
8591 case MONO_WRAPPER_STFLD: {
8592 g_assert (info);
8593 success = success && append_mangled_klass (s, info->d.proxy.klass);
8594 break;
8596 case MONO_WRAPPER_ALLOC: {
8597 /* The GC name is saved once in MonoAotFileInfo */
8598 g_assert (info->d.alloc.alloc_type != -1);
8599 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8600 // SlowAlloc, etc
8601 g_string_append_printf (s, "%s_", method->name);
8602 break;
8604 case MONO_WRAPPER_WRITE_BARRIER: {
8605 g_string_append_printf (s, "%s_", method->name);
8606 break;
8608 case MONO_WRAPPER_STELEMREF: {
8609 append_mangled_wrapper_subtype (s, info->subtype);
8610 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8611 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8612 break;
8614 case MONO_WRAPPER_UNKNOWN: {
8615 append_mangled_wrapper_subtype (s, info->subtype);
8616 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8617 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8618 success = success && append_mangled_klass (s, method->klass);
8619 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8620 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8621 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8622 success = success && append_mangled_method (s, info->d.array_accessor.method);
8623 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
8624 append_mangled_signature (s, info->d.interp_in.sig);
8625 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8626 append_mangled_signature (s, info->d.gsharedvt.sig);
8627 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8628 append_mangled_signature (s, info->d.gsharedvt.sig);
8629 break;
8631 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8632 append_mangled_wrapper_subtype (s, info->subtype);
8633 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8634 g_string_append_printf (s, "%s", method->name);
8635 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8636 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8637 } else {
8638 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8639 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8641 break;
8643 case MONO_WRAPPER_SYNCHRONIZED: {
8644 MonoMethod *m;
8646 m = mono_marshal_method_from_wrapper (method);
8647 g_assert (m);
8648 g_assert (m != method);
8649 success = success && append_mangled_method (s, m);
8650 break;
8652 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8653 append_mangled_wrapper_subtype (s, info->subtype);
8655 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8656 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8657 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8658 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8659 success = success && append_mangled_method (s, info->d.string_ctor.method);
8660 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
8661 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
8662 } else {
8663 success = FALSE;
8665 break;
8667 case MONO_WRAPPER_CASTCLASS: {
8668 append_mangled_wrapper_subtype (s, info->subtype);
8669 break;
8671 case MONO_WRAPPER_RUNTIME_INVOKE: {
8672 append_mangled_wrapper_subtype (s, info->subtype);
8673 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8674 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8675 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8676 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8677 break;
8679 case MONO_WRAPPER_DELEGATE_INVOKE:
8680 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8681 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8682 if (method->is_inflated) {
8683 /* These wrappers are identified by their class */
8684 g_string_append_printf (s, "i_");
8685 success = success && append_mangled_klass (s, method->klass);
8686 } else {
8687 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8689 g_string_append_printf (s, "u_");
8690 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8691 append_mangled_wrapper_subtype (s, info->subtype);
8692 g_string_append_printf (s, "u_sigstart");
8694 break;
8696 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8697 g_assert (info);
8698 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8699 success = success && append_mangled_klass (s, method->klass);
8700 break;
8702 default:
8703 g_assert_not_reached ();
8705 return success && append_mangled_signature (s, mono_method_signature (method));
8708 static void
8709 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
8711 int i;
8713 for (i = 0; i < ginst->type_argc; ++i) {
8714 if (i > 0)
8715 g_string_append (str, ", ");
8716 MonoType *type = ginst->type_argv [i];
8717 switch (type->type) {
8718 case MONO_TYPE_VAR:
8719 case MONO_TYPE_MVAR: {
8720 MonoType *constraint = NULL;
8721 if (type->data.generic_param)
8722 constraint = type->data.generic_param->gshared_constraint;
8723 if (constraint) {
8724 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
8725 g_string_append (str, "gshared:");
8726 mono_type_get_desc (str, constraint, TRUE);
8727 break;
8729 // Else falls through to common case
8731 default:
8732 mono_type_get_desc (str, type, TRUE);
8737 static void
8738 append_mangled_context (GString *str, MonoGenericContext *context)
8740 GString *res = g_string_new ("");
8742 g_string_append_printf (res, "gens_");
8743 g_string_append (res, "00");
8745 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8746 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8747 g_assert (good);
8749 if (context->class_inst)
8750 append_mangled_ginst (res, context->class_inst);
8751 if (context->method_inst) {
8752 if (context->class_inst)
8753 g_string_append (res, "11");
8754 append_mangled_ginst (res, context->method_inst);
8756 g_string_append_printf (str, "gens_%s", res->str);
8757 g_free (res);
8760 static gboolean
8761 append_mangled_method (GString *s, MonoMethod *method)
8763 if (method->wrapper_type)
8764 return append_mangled_wrapper (s, method);
8766 if (method->is_inflated) {
8767 g_string_append_printf (s, "inflated_");
8768 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8769 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8771 append_mangled_context (s, &imethod->context);
8772 g_string_append_printf (s, "_declared_by_");
8773 append_mangled_method (s, imethod->declaring);
8774 } else if (method->is_generic) {
8775 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
8777 g_string_append_printf (s, "generic_");
8778 append_mangled_klass (s, method->klass);
8779 g_string_append_printf (s, "_%s_", method->name);
8781 MonoGenericContainer *container = mono_method_get_generic_container (method);
8782 g_string_append_printf (s, "_%s");
8783 append_mangled_context (s, &container->context);
8785 return append_mangled_signature (s, mono_method_signature (method));
8786 } else {
8787 g_string_append_printf (s, "_");
8788 append_mangled_klass (s, method->klass);
8789 g_string_append_printf (s, "_%s_", method->name);
8790 if (!append_mangled_signature (s, mono_method_signature (method))) {
8791 g_string_free (s, TRUE);
8792 return FALSE;
8796 return TRUE;
8800 * mono_aot_get_mangled_method_name:
8802 * Return a unique mangled name for METHOD, or NULL.
8804 char*
8805 mono_aot_get_mangled_method_name (MonoMethod *method)
8807 // FIXME: use static cache (mempool?)
8808 // We call this a *lot*
8810 GString *s = g_string_new ("aot_");
8811 if (!append_mangled_method (s, method)) {
8812 g_string_free (s, TRUE);
8813 return NULL;
8814 } else {
8815 char *out = g_string_free (s, FALSE);
8816 // Scrub method and class names
8817 char *cleaned = sanitize_mangled_string (out);
8818 g_free (out);
8819 return cleaned;
8823 gboolean
8824 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8826 return is_direct_callable (llvm_acfg, NULL, patch_info);
8829 void
8830 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8832 MonoPltEntry *plt_entry;
8834 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8835 plt_entry->llvm_used = FALSE;
8838 char*
8839 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8841 const char *sym = NULL;
8843 if (llvm_acfg->aot_opts.direct_icalls) {
8844 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8845 /* Call to a C function implementing a jit icall */
8846 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8847 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8848 MonoMethod *method = (MonoMethod *)data;
8849 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8850 sym = mono_lookup_icall_symbol (method);
8851 else if (llvm_acfg->aot_opts.direct_pinvoke)
8852 sym = get_pinvoke_import (llvm_acfg, method);
8854 if (sym)
8855 return g_strdup (sym);
8857 return NULL;
8860 char*
8861 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8863 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8864 MonoPltEntry *plt_entry;
8865 const char *sym = NULL;
8867 ji->type = type;
8868 ji->data.target = data;
8870 if (!can_encode_patch (llvm_acfg, ji))
8871 return NULL;
8873 if (llvm_acfg->aot_opts.direct_icalls) {
8874 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8875 /* Call to a C function implementing a jit icall */
8876 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8877 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8878 MonoMethod *method = (MonoMethod *)data;
8879 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8880 sym = mono_lookup_icall_symbol (method);
8882 if (sym)
8883 return g_strdup (sym);
8886 plt_entry = get_plt_entry (llvm_acfg, ji);
8887 plt_entry->llvm_used = TRUE;
8889 #if defined(TARGET_MACH)
8890 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8891 #else
8892 return g_strdup_printf (plt_entry->llvm_symbol);
8893 #endif
8897 mono_aot_get_method_index (MonoMethod *method)
8899 g_assert (llvm_acfg);
8900 return get_method_index (llvm_acfg, method);
8903 MonoJumpInfo*
8904 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8906 MonoJumpInfo *res;
8908 mono_acfg_lock (llvm_acfg);
8909 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8910 mono_acfg_unlock (llvm_acfg);
8912 return res;
8915 static int
8916 execute_system (const char * command)
8918 int status = 0;
8920 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
8921 // We need an extra set of quotes around the whole command to properly handle commands
8922 // with spaces since internally the command is called through "cmd /c.
8923 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8925 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8926 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8927 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8928 status = _wsystem (wstr);
8929 g_free (wstr);
8931 g_free (quoted_command);
8932 #elif defined (HAVE_SYSTEM)
8933 status = system (command);
8934 #else
8935 g_assert_not_reached ();
8936 #endif
8938 return status;
8941 #ifdef ENABLE_LLVM
8944 * emit_llvm_file:
8946 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8947 * tools.
8949 static gboolean
8950 emit_llvm_file (MonoAotCompile *acfg)
8952 char *command, *opts, *tempbc, *optbc, *output_fname;
8954 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8955 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8956 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8957 } else {
8958 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8959 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8962 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8965 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8966 * a lot of time, and doesn't seem to save much space.
8967 * The following optimizations cannot be enabled:
8968 * - 'tailcallelim'
8969 * - 'jump-threading' changes our blockaddress references to int constants.
8970 * - 'basiccg' fails because it contains:
8971 * if (CS && !isa<IntrinsicInst>(II)) {
8972 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8973 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8974 * The opt list below was produced by taking the output of:
8975 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8976 * then removing tailcallelim + the global opts.
8977 * strip-dead-prototypes deletes unused intrinsics definitions.
8979 /* The dse pass is disabled because of #13734 and #17616 */
8981 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8982 * // If we have no DataLayout information around, then the size of the store
8983 * // is inferrable from the pointee type. If they are the same type, then
8984 * // we know that the store is safe.
8985 * if (AA.getDataLayout() == 0 &&
8986 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8987 * return OverwriteComplete;
8988 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8990 if (acfg->aot_opts.llvm_opts) {
8991 opts = g_strdup (acfg->aot_opts.llvm_opts);
8992 } else if (acfg->aot_opts.llvm_only) {
8993 // FIXME: This doesn't work yet
8994 opts = g_strdup ("");
8995 } else {
8996 #if LLVM_API_VERSION > 100
8997 opts = g_strdup ("-O2 -disable-tail-calls");
8998 #else
8999 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");
9000 #endif
9003 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9004 aot_printf (acfg, "Executing opt: %s\n", command);
9005 if (execute_system (command) != 0)
9006 return FALSE;
9007 g_free (opts);
9009 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9010 /* Nothing else to do */
9011 return TRUE;
9013 if (acfg->aot_opts.llvm_only) {
9014 /* Use the stock clang from xcode */
9015 // FIXME: arch
9016 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);
9018 aot_printf (acfg, "Executing clang: %s\n", command);
9019 if (execute_system (command) != 0)
9020 return FALSE;
9021 return TRUE;
9024 if (!acfg->llc_args)
9025 acfg->llc_args = g_string_new ("");
9027 /* Verbose asm slows down llc greatly */
9028 g_string_append (acfg->llc_args, " -asm-verbose=false");
9030 if (acfg->aot_opts.mtriple)
9031 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9033 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9035 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9037 #if LLVM_API_VERSION > 100
9038 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9039 #endif
9041 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
9042 /* ios requires PIC code now */
9043 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9044 #else
9045 if (llvm_acfg->aot_opts.static_link)
9046 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9047 else
9048 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9049 #endif
9051 if (acfg->llvm_owriter) {
9052 /* Emit an object file directly */
9053 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9054 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9055 } else {
9056 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9058 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9059 g_free (output_fname);
9061 aot_printf (acfg, "Executing llc: %s\n", command);
9063 if (execute_system (command) != 0)
9064 return FALSE;
9065 return TRUE;
9067 #endif
9069 static void
9070 emit_code (MonoAotCompile *acfg)
9072 int oindex, i, prev_index;
9073 gboolean saved_unbox_info = FALSE;
9074 char symbol [MAX_SYMBOL_SIZE];
9076 if (acfg->aot_opts.llvm_only)
9077 return;
9079 #if defined(TARGET_POWERPC64)
9080 sprintf (symbol, ".Lgot_addr");
9081 emit_section_change (acfg, ".text", 0);
9082 emit_alignment (acfg, 8);
9083 emit_label (acfg, symbol);
9084 emit_pointer (acfg, acfg->got_symbol);
9085 #endif
9088 * This global symbol is used to compute the address of each method using the
9089 * code_offsets array. It is also used to compute the memory ranges occupied by
9090 * AOT code, so it must be equal to the address of the first emitted method.
9092 emit_section_change (acfg, ".text", 0);
9093 emit_alignment_code (acfg, 8);
9094 emit_info_symbol (acfg, "jit_code_start");
9097 * Emit some padding so the local symbol for the first method doesn't have the
9098 * same address as 'methods'.
9100 emit_padding (acfg, 16);
9102 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9103 MonoCompile *cfg;
9104 MonoMethod *method;
9106 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9108 cfg = acfg->cfgs [i];
9110 if (!cfg)
9111 continue;
9113 method = cfg->orig_method;
9115 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9116 gboolean dedupable = mono_aot_can_dedup (method);
9118 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9119 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9120 mono_dedup_cache_method (acfg, method);
9122 // Don't compile inflated methods if we're in first phase of
9123 // dedup
9125 // In second phase, we emit methods that
9126 // are dedupable. We also emit later methods
9127 // which are referenced by them and added later.
9128 // For this reason, when in the dedup_include mode,
9129 // we never set skip.
9130 if (acfg->aot_opts.dedup)
9131 cfg->skip = TRUE;
9134 // Don't compile anything in this mode
9135 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9136 cfg->skip = TRUE;
9138 // Compile everything in this mode
9139 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9140 cfg->skip = FALSE;
9142 /*if (dedup_collect) {*/
9143 /*char *name = mono_aot_get_mangled_method_name (method);*/
9145 /*if (ignore_cfg (cfg))*/
9146 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9147 /*else*/
9148 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9150 /*g_free (name);*/
9151 /*}*/
9153 if (ignore_cfg (cfg))
9154 continue;
9156 /* Emit unbox trampoline */
9157 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9158 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9160 emit_section_change (acfg, ".text", 0);
9162 if (acfg->thumb_mixed && cfg->compile_llvm) {
9163 emit_set_thumb_mode (acfg);
9164 fprintf (acfg->fp, "\n.thumb_func\n");
9167 emit_label (acfg, symbol);
9169 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9171 if (acfg->thumb_mixed && cfg->compile_llvm)
9172 emit_set_arm_mode (acfg);
9174 if (!saved_unbox_info) {
9175 char user_symbol [128];
9176 GSList *unwind_ops;
9177 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9179 emit_label (acfg, "ut_end");
9181 unwind_ops = mono_unwind_get_cie_program ();
9182 save_unwind_info (acfg, user_symbol, unwind_ops);
9183 mono_free_unwind_info (unwind_ops);
9185 /* Save the unbox trampoline size */
9186 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9188 saved_unbox_info = TRUE;
9192 if (cfg->compile_llvm) {
9193 acfg->stats.llvm_count ++;
9194 } else {
9195 emit_method_code (acfg, cfg);
9199 emit_section_change (acfg, ".text", 0);
9200 emit_alignment_code (acfg, 8);
9201 emit_info_symbol (acfg, "jit_code_end");
9203 /* To distinguish it from the next symbol */
9204 emit_padding (acfg, 4);
9207 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9208 * from optimizing them away, since it doesn't see that code_offsets references them.
9209 * JITted methods don't need this since they are referenced using assembler local
9210 * symbols.
9211 * FIXME: This is why write-symbols doesn't work on OSX ?
9213 if (acfg->llvm && acfg->need_no_dead_strip) {
9214 fprintf (acfg->fp, "\n");
9215 for (i = 0; i < acfg->nmethods; ++i) {
9216 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9217 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9222 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9223 * This is PIE code, and the linker can update it if needed.
9226 sprintf (symbol, "method_addresses");
9227 emit_section_change (acfg, ".text", 1);
9228 emit_alignment_code (acfg, 8);
9229 emit_info_symbol (acfg, symbol);
9230 if (acfg->aot_opts.write_symbols)
9231 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9232 emit_unset_mode (acfg);
9233 if (acfg->need_no_dead_strip)
9234 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9236 for (i = 0; i < acfg->nmethods; ++i) {
9237 #ifdef MONO_ARCH_AOT_SUPPORTED
9238 int call_size;
9240 if (!ignore_cfg (acfg->cfgs [i])) {
9241 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9242 } else {
9243 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9245 #endif
9248 sprintf (symbol, "method_addresses_end");
9249 emit_label (acfg, symbol);
9250 emit_line (acfg);
9252 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9253 sprintf (symbol, "unbox_trampolines");
9254 emit_section_change (acfg, RODATA_SECT, 0);
9255 emit_alignment (acfg, 8);
9256 emit_info_symbol (acfg, symbol);
9258 prev_index = -1;
9259 for (i = 0; i < acfg->nmethods; ++i) {
9260 MonoCompile *cfg;
9261 MonoMethod *method;
9262 int index;
9264 cfg = acfg->cfgs [i];
9265 if (ignore_cfg (cfg))
9266 continue;
9268 method = cfg->orig_method;
9270 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9271 index = get_method_index (acfg, method);
9273 emit_int32 (acfg, index);
9274 /* Make sure the table is sorted by index */
9275 g_assert (index > prev_index);
9276 prev_index = index;
9279 sprintf (symbol, "unbox_trampolines_end");
9280 emit_info_symbol (acfg, symbol);
9281 emit_int32 (acfg, 0);
9283 /* Emit a separate table with the trampoline addresses/offsets */
9284 sprintf (symbol, "unbox_trampoline_addresses");
9285 emit_section_change (acfg, ".text", 0);
9286 emit_alignment_code (acfg, 8);
9287 emit_info_symbol (acfg, symbol);
9289 for (i = 0; i < acfg->nmethods; ++i) {
9290 MonoCompile *cfg;
9291 MonoMethod *method;
9292 int index;
9294 cfg = acfg->cfgs [i];
9295 if (ignore_cfg (cfg))
9296 continue;
9298 method = cfg->orig_method;
9300 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9301 #ifdef MONO_ARCH_AOT_SUPPORTED
9302 int call_size;
9304 index = get_method_index (acfg, method);
9305 sprintf (symbol, "ut_%d", index);
9307 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9308 #endif
9311 emit_int32 (acfg, 0);
9314 static void
9315 emit_info (MonoAotCompile *acfg)
9317 int oindex, i;
9318 gint32 *offsets;
9320 offsets = g_new0 (gint32, acfg->nmethods);
9322 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9323 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9325 if (acfg->cfgs [i]) {
9326 emit_method_info (acfg, acfg->cfgs [i]);
9327 offsets [i] = acfg->cfgs [i]->method_info_offset;
9328 } else {
9329 offsets [i] = 0;
9333 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9335 g_free (offsets);
9338 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9340 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9341 #define mix(a,b,c) { \
9342 a -= c; a ^= rot(c, 4); c += b; \
9343 b -= a; b ^= rot(a, 6); a += c; \
9344 c -= b; c ^= rot(b, 8); b += a; \
9345 a -= c; a ^= rot(c,16); c += b; \
9346 b -= a; b ^= rot(a,19); a += c; \
9347 c -= b; c ^= rot(b, 4); b += a; \
9349 #define final(a,b,c) { \
9350 c ^= b; c -= rot(b,14); \
9351 a ^= c; a -= rot(c,11); \
9352 b ^= a; b -= rot(a,25); \
9353 c ^= b; c -= rot(b,16); \
9354 a ^= c; a -= rot(c,4); \
9355 b ^= a; b -= rot(a,14); \
9356 c ^= b; c -= rot(b,24); \
9359 static guint
9360 mono_aot_type_hash (MonoType *t1)
9362 guint hash = t1->type;
9364 hash |= t1->byref << 6; /* do not collide with t1->type values */
9365 switch (t1->type) {
9366 case MONO_TYPE_VALUETYPE:
9367 case MONO_TYPE_CLASS:
9368 case MONO_TYPE_SZARRAY:
9369 /* check if the distribution is good enough */
9370 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
9371 case MONO_TYPE_PTR:
9372 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9373 case MONO_TYPE_ARRAY:
9374 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
9375 case MONO_TYPE_GENERICINST:
9376 return ((hash << 5) - hash) ^ 0;
9377 default:
9378 return hash;
9383 * mono_aot_method_hash:
9385 * Return a hash code for methods which only depends on metadata.
9387 guint32
9388 mono_aot_method_hash (MonoMethod *method)
9390 MonoMethodSignature *sig;
9391 MonoClass *klass;
9392 int i, hindex;
9393 int hashes_count;
9394 guint32 *hashes_start, *hashes;
9395 guint32 a, b, c;
9396 MonoGenericInst *class_ginst = NULL;
9397 MonoGenericInst *ginst = NULL;
9399 /* Similar to the hash in mono_method_get_imt_slot () */
9401 sig = mono_method_signature (method);
9403 if (mono_class_is_ginst (method->klass))
9404 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9405 if (method->is_inflated)
9406 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9408 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9409 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9410 hashes = hashes_start;
9412 /* Some wrappers are assigned to random classes */
9413 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9414 klass = method->klass;
9415 else
9416 klass = mono_defaults.object_class;
9418 if (!method->wrapper_type) {
9419 char *full_name;
9421 if (mono_class_is_ginst (klass))
9422 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
9423 else
9424 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
9426 hashes [0] = mono_metadata_str_hash (full_name);
9427 hashes [1] = 0;
9428 g_free (full_name);
9429 } else {
9430 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
9431 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
9433 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9434 /* The method name includes a stringified pointer */
9435 hashes [2] = 0;
9436 else
9437 hashes [2] = mono_metadata_str_hash (method->name);
9438 hashes [3] = method->wrapper_type;
9439 hashes [4] = mono_aot_type_hash (sig->ret);
9440 hindex = 5;
9441 for (i = 0; i < sig->param_count; i++) {
9442 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9444 if (class_ginst) {
9445 for (i = 0; i < class_ginst->type_argc; ++i)
9446 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9448 if (ginst) {
9449 for (i = 0; i < ginst->type_argc; ++i)
9450 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9452 g_assert (hindex == hashes_count);
9454 /* Setup internal state */
9455 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9457 /* Handle most of the hashes */
9458 while (hashes_count > 3) {
9459 a += hashes [0];
9460 b += hashes [1];
9461 c += hashes [2];
9462 mix (a,b,c);
9463 hashes_count -= 3;
9464 hashes += 3;
9467 /* Handle the last 3 hashes (all the case statements fall through) */
9468 switch (hashes_count) {
9469 case 3 : c += hashes [2];
9470 case 2 : b += hashes [1];
9471 case 1 : a += hashes [0];
9472 final (a,b,c);
9473 case 0: /* nothing left to add */
9474 break;
9477 g_free (hashes_start);
9479 return c;
9481 #undef rot
9482 #undef mix
9483 #undef final
9486 * mono_aot_get_array_helper_from_wrapper;
9488 * Get the helper method in Array called by an array wrapper method.
9490 MonoMethod*
9491 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9493 MonoMethod *m;
9494 const char *prefix;
9495 MonoGenericContext ctx;
9496 MonoType *args [16];
9497 char *mname, *iname, *s, *s2, *helper_name = NULL;
9499 prefix = "System.Collections.Generic";
9500 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9501 s2 = strstr (s, "`1.");
9502 g_assert (s2);
9503 s2 [0] = '\0';
9504 iname = s;
9505 mname = s2 + 3;
9507 //printf ("X: %s %s\n", iname, mname);
9509 if (!strcmp (iname, "IList"))
9510 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9511 else
9512 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9513 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9514 g_assert (m);
9515 g_free (helper_name);
9516 g_free (s);
9518 if (m->is_generic) {
9519 ERROR_DECL (error);
9520 memset (&ctx, 0, sizeof (ctx));
9521 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
9522 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9523 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
9524 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9527 return m;
9530 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9532 typedef struct HashEntry {
9533 guint32 key, value, index;
9534 struct HashEntry *next;
9535 } HashEntry;
9538 * emit_extra_methods:
9540 * Emit methods which are not in the METHOD table, like wrappers.
9542 static void
9543 emit_extra_methods (MonoAotCompile *acfg)
9545 int i, table_size, buf_size;
9546 guint8 *p, *buf;
9547 guint32 *info_offsets;
9548 guint32 hash;
9549 GPtrArray *table;
9550 HashEntry *entry, *new_entry;
9551 int nmethods, max_chain_length;
9552 int *chain_lengths;
9554 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9556 /* Emit method info */
9557 nmethods = 0;
9558 for (i = 0; i < acfg->extra_methods->len; ++i) {
9559 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9560 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9562 if (ignore_cfg (cfg))
9563 continue;
9565 buf_size = 10240;
9566 p = buf = (guint8 *)g_malloc (buf_size);
9568 nmethods ++;
9570 method = cfg->method_to_register;
9572 encode_method_ref (acfg, method, p, &p);
9574 g_assert ((p - buf) < buf_size);
9576 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9577 g_free (buf);
9581 * Construct a chained hash table for mapping indexes in extra_method_info to
9582 * method indexes.
9584 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9585 table = g_ptr_array_sized_new (table_size);
9586 for (i = 0; i < table_size; ++i)
9587 g_ptr_array_add (table, NULL);
9588 chain_lengths = g_new0 (int, table_size);
9589 max_chain_length = 0;
9590 for (i = 0; i < acfg->extra_methods->len; ++i) {
9591 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9592 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9593 guint32 key, value;
9595 if (ignore_cfg (cfg))
9596 continue;
9598 key = info_offsets [i];
9599 value = get_method_index (acfg, method);
9601 hash = mono_aot_method_hash (method) % table_size;
9602 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9604 chain_lengths [hash] ++;
9605 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9607 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9608 new_entry->key = key;
9609 new_entry->value = value;
9611 entry = (HashEntry *)g_ptr_array_index (table, hash);
9612 if (entry == NULL) {
9613 new_entry->index = hash;
9614 g_ptr_array_index (table, hash) = new_entry;
9615 } else {
9616 while (entry->next)
9617 entry = entry->next;
9619 entry->next = new_entry;
9620 new_entry->index = table->len;
9621 g_ptr_array_add (table, new_entry);
9624 g_free (chain_lengths);
9626 //printf ("MAX: %d\n", max_chain_length);
9628 buf_size = table->len * 12 + 4;
9629 p = buf = (guint8 *)g_malloc (buf_size);
9630 encode_int (table_size, p, &p);
9632 for (i = 0; i < table->len; ++i) {
9633 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9635 if (entry == NULL) {
9636 encode_int (0, p, &p);
9637 encode_int (0, p, &p);
9638 encode_int (0, p, &p);
9639 } else {
9640 //g_assert (entry->key > 0);
9641 encode_int (entry->key, p, &p);
9642 encode_int (entry->value, p, &p);
9643 if (entry->next)
9644 encode_int (entry->next->index, p, &p);
9645 else
9646 encode_int (0, p, &p);
9649 g_assert (p - buf <= buf_size);
9651 /* Emit the table */
9652 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9654 g_free (buf);
9657 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9658 * This is used by mono_aot_find_jit_info ().
9660 buf_size = acfg->extra_methods->len * 8 + 4;
9661 p = buf = (guint8 *)g_malloc (buf_size);
9662 encode_int (acfg->extra_methods->len, p, &p);
9663 for (i = 0; i < acfg->extra_methods->len; ++i) {
9664 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9666 encode_int (get_method_index (acfg, method), p, &p);
9667 encode_int (info_offsets [i], p, &p);
9669 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9671 g_free (buf);
9672 g_free (info_offsets);
9673 g_ptr_array_free (table, TRUE);
9676 static void
9677 generate_aotid (guint8* aotid)
9679 gpointer rand_handle;
9680 ERROR_DECL (error);
9682 mono_rand_open ();
9683 rand_handle = mono_rand_init (NULL, 0);
9685 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
9686 mono_error_assert_ok (error);
9688 mono_rand_close (rand_handle);
9691 static void
9692 emit_exception_info (MonoAotCompile *acfg)
9694 int i;
9695 gint32 *offsets;
9696 SeqPointData sp_data;
9697 gboolean seq_points_to_file = FALSE;
9699 offsets = g_new0 (gint32, acfg->nmethods);
9700 for (i = 0; i < acfg->nmethods; ++i) {
9701 if (acfg->cfgs [i]) {
9702 MonoCompile *cfg = acfg->cfgs [i];
9704 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9705 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9706 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9707 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9708 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9710 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9711 offsets [i] = cfg->ex_info_offset;
9713 if (method_seq_points_to_file) {
9714 if (!seq_points_to_file) {
9715 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9716 seq_points_to_file = TRUE;
9718 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9720 } else {
9721 offsets [i] = 0;
9725 if (seq_points_to_file) {
9726 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9727 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9728 char *image_basename = g_path_get_basename (acfg->image->name);
9729 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9730 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9732 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9733 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9734 exit (1);
9737 mono_seq_point_data_write (&sp_data, aot_file_path);
9738 mono_seq_point_data_free (&sp_data);
9740 g_free (aotid);
9741 g_free (dir);
9742 g_free (image_basename);
9743 g_free (aot_file);
9744 g_free (aot_file_path);
9747 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9748 g_free (offsets);
9751 static void
9752 emit_unwind_info (MonoAotCompile *acfg)
9754 int i;
9755 char symbol [128];
9757 if (acfg->aot_opts.llvm_only) {
9758 g_assert (acfg->unwind_ops->len == 0);
9759 return;
9763 * The unwind info contains a lot of duplicates so we emit each unique
9764 * entry once, and only store the offset from the start of the table in the
9765 * exception info.
9768 sprintf (symbol, "unwind_info");
9769 emit_section_change (acfg, RODATA_SECT, 1);
9770 emit_alignment (acfg, 8);
9771 emit_info_symbol (acfg, symbol);
9773 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9774 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9775 guint8 *unwind_info;
9776 guint32 unwind_info_len;
9777 guint8 buf [16];
9778 guint8 *p;
9780 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9782 p = buf;
9783 encode_value (unwind_info_len, p, &p);
9784 emit_bytes (acfg, buf, p - buf);
9785 emit_bytes (acfg, unwind_info, unwind_info_len);
9787 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9791 static void
9792 emit_class_info (MonoAotCompile *acfg)
9794 int i;
9795 gint32 *offsets;
9797 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9798 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9799 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9801 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);
9802 g_free (offsets);
9805 typedef struct ClassNameTableEntry {
9806 guint32 token, index;
9807 struct ClassNameTableEntry *next;
9808 } ClassNameTableEntry;
9810 static void
9811 emit_class_name_table (MonoAotCompile *acfg)
9813 int i, table_size, buf_size;
9814 guint32 token, hash;
9815 MonoClass *klass;
9816 GPtrArray *table;
9817 char *full_name;
9818 guint8 *buf, *p;
9819 ClassNameTableEntry *entry, *new_entry;
9822 * Construct a chained hash table for mapping class names to typedef tokens.
9824 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9825 table = g_ptr_array_sized_new (table_size);
9826 for (i = 0; i < table_size; ++i)
9827 g_ptr_array_add (table, NULL);
9828 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9829 ERROR_DECL (error);
9830 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9831 klass = mono_class_get_checked (acfg->image, token, error);
9832 if (!klass) {
9833 mono_error_cleanup (error);
9834 continue;
9836 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9837 hash = mono_metadata_str_hash (full_name) % table_size;
9838 g_free (full_name);
9840 /* FIXME: Allocate from the mempool */
9841 new_entry = g_new0 (ClassNameTableEntry, 1);
9842 new_entry->token = token;
9844 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9845 if (entry == NULL) {
9846 new_entry->index = hash;
9847 g_ptr_array_index (table, hash) = new_entry;
9848 } else {
9849 while (entry->next)
9850 entry = entry->next;
9852 entry->next = new_entry;
9853 new_entry->index = table->len;
9854 g_ptr_array_add (table, new_entry);
9858 /* Emit the table */
9859 buf_size = table->len * 4 + 4;
9860 p = buf = (guint8 *)g_malloc0 (buf_size);
9862 /* FIXME: Optimize memory usage */
9863 g_assert (table_size < 65000);
9864 encode_int16 (table_size, p, &p);
9865 g_assert (table->len < 65000);
9866 for (i = 0; i < table->len; ++i) {
9867 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9869 if (entry == NULL) {
9870 encode_int16 (0, p, &p);
9871 encode_int16 (0, p, &p);
9872 } else {
9873 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9874 if (entry->next)
9875 encode_int16 (entry->next->index, p, &p);
9876 else
9877 encode_int16 (0, p, &p);
9879 g_free (entry);
9881 g_assert (p - buf <= buf_size);
9882 g_ptr_array_free (table, TRUE);
9884 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9886 g_free (buf);
9889 static void
9890 emit_image_table (MonoAotCompile *acfg)
9892 int i, buf_size;
9893 guint8 *buf, *p;
9896 * The image table is small but referenced in a lot of places.
9897 * So we emit it at once, and reference its elements by an index.
9899 buf_size = acfg->image_table->len * 28 + 4;
9900 for (i = 0; i < acfg->image_table->len; i++) {
9901 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9902 MonoAssemblyName *aname = &image->assembly->aname;
9904 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9907 buf = p = (guint8 *)g_malloc0 (buf_size);
9908 encode_int (acfg->image_table->len, p, &p);
9909 for (i = 0; i < acfg->image_table->len; i++) {
9910 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9911 MonoAssemblyName *aname = &image->assembly->aname;
9913 /* FIXME: Support multi-module assemblies */
9914 g_assert (image->assembly->image == image);
9916 encode_string (image->assembly_name, p, &p);
9917 encode_string (image->guid, p, &p);
9918 encode_string (aname->culture ? aname->culture : "", p, &p);
9919 encode_string ((const char*)aname->public_key_token, p, &p);
9921 while (GPOINTER_TO_UINT (p) % 8 != 0)
9922 p ++;
9924 encode_int (aname->flags, p, &p);
9925 encode_int (aname->major, p, &p);
9926 encode_int (aname->minor, p, &p);
9927 encode_int (aname->build, p, &p);
9928 encode_int (aname->revision, p, &p);
9930 g_assert (p - buf <= buf_size);
9932 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9934 g_free (buf);
9937 static void
9938 emit_weak_field_indexes (MonoAotCompile *acfg)
9940 GHashTable *indexes;
9941 GHashTableIter iter;
9942 gpointer key, value;
9943 int buf_size;
9944 guint8 *buf, *p;
9946 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
9947 mono_assembly_init_weak_fields (acfg->image);
9948 indexes = acfg->image->weak_field_indexes;
9949 g_assert (indexes);
9951 buf_size = (g_hash_table_size (indexes) + 1) * 4;
9952 buf = p = (guint8 *)g_malloc0 (buf_size);
9954 encode_int (g_hash_table_size (indexes), p, &p);
9955 g_hash_table_iter_init (&iter, indexes);
9956 while (g_hash_table_iter_next (&iter, &key, &value)) {
9957 guint32 index = GPOINTER_TO_UINT (key);
9958 encode_int (index, p, &p);
9960 g_assert (p - buf <= buf_size);
9962 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
9964 g_free (buf);
9967 static void
9968 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9970 int i, first_plt_got_patch = 0, buf_size;
9971 guint8 *p, *buf;
9972 guint32 *got_info_offsets;
9973 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9975 /* Add the patches needed by the PLT to the GOT */
9976 if (!llvm) {
9977 acfg->plt_got_offset_base = acfg->got_offset;
9978 first_plt_got_patch = info->got_patches->len;
9979 for (i = 1; i < acfg->plt_offset; ++i) {
9980 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9982 g_ptr_array_add (info->got_patches, plt_entry->ji);
9984 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9987 acfg->got_offset += acfg->plt_offset;
9991 * FIXME:
9992 * - optimize offsets table.
9993 * - reduce number of exported symbols.
9994 * - emit info for a klass only once.
9995 * - determine when a method uses a GOT slot which is guaranteed to be already
9996 * initialized.
9997 * - clean up and document the code.
9998 * - use String.Empty in class libs.
10001 /* Encode info required to decode shared GOT entries */
10002 buf_size = info->got_patches->len * 128;
10003 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10004 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10005 if (!llvm) {
10006 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10007 /* Unused */
10008 if (acfg->plt_offset)
10009 acfg->plt_got_info_offsets [0] = 0;
10011 for (i = 0; i < info->got_patches->len; ++i) {
10012 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10013 guint8 *p2;
10015 p = buf;
10017 encode_value (ji->type, p, &p);
10018 p2 = p;
10019 encode_patch (acfg, ji, p, &p);
10020 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10021 g_assert (p - buf <= buf_size);
10022 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10024 if (!llvm && i >= first_plt_got_patch)
10025 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10026 acfg->stats.got_info_size += p - buf;
10029 /* Emit got_info_offsets table */
10031 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10032 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);
10035 static void
10036 emit_got (MonoAotCompile *acfg)
10038 char symbol [MAX_SYMBOL_SIZE];
10040 if (acfg->aot_opts.llvm_only)
10041 return;
10043 /* Don't make GOT global so accesses to it don't need relocations */
10044 sprintf (symbol, "%s", acfg->got_symbol);
10046 #ifdef TARGET_MACH
10047 emit_unset_mode (acfg);
10048 fprintf (acfg->fp, ".section __DATA, __bss\n");
10049 emit_alignment (acfg, 8);
10050 if (acfg->llvm)
10051 emit_info_symbol (acfg, "jit_got");
10052 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
10053 #else
10054 emit_section_change (acfg, ".bss", 0);
10055 emit_alignment (acfg, 8);
10056 if (acfg->aot_opts.write_symbols)
10057 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10058 emit_label (acfg, symbol);
10059 if (acfg->llvm)
10060 emit_info_symbol (acfg, "jit_got");
10061 if (acfg->got_offset > 0)
10062 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
10063 #endif
10065 sprintf (symbol, "got_end");
10066 emit_label (acfg, symbol);
10069 typedef struct GlobalsTableEntry {
10070 guint32 value, index;
10071 struct GlobalsTableEntry *next;
10072 } GlobalsTableEntry;
10074 #ifdef TARGET_WIN32_MSVC
10075 #define DLL_ENTRY_POINT "DllMain"
10077 static void
10078 emit_library_info (MonoAotCompile *acfg)
10080 // Only include for shared libraries linked directly from generated object.
10081 if (link_shared_library (acfg)) {
10082 char *name = NULL;
10083 char symbol [MAX_SYMBOL_SIZE];
10085 // Ask linker to export all global symbols.
10086 emit_section_change (acfg, ".drectve", 0);
10087 for (guint i = 0; i < acfg->globals->len; ++i) {
10088 name = (char *)g_ptr_array_index (acfg->globals, i);
10089 g_assert (name != NULL);
10090 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10091 emit_string (acfg, symbol);
10094 // Emit DLLMain function, needed by MSVC linker for DLL's.
10095 // NOTE, DllMain should not go into exports above.
10096 emit_section_change (acfg, ".text", 0);
10097 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10098 emit_label (acfg, DLL_ENTRY_POINT);
10100 // Simple implementation of DLLMain, just returning TRUE.
10101 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10102 fprintf (acfg->fp, "movl $1, %%eax\n");
10103 fprintf (acfg->fp, "ret\n");
10105 // Inform linker about our dll entry function.
10106 emit_section_change (acfg, ".drectve", 0);
10107 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10108 return;
10112 #else
10114 static inline void
10115 emit_library_info (MonoAotCompile *acfg)
10117 return;
10119 #endif
10121 static void
10122 emit_globals (MonoAotCompile *acfg)
10124 int i, table_size;
10125 guint32 hash;
10126 GPtrArray *table;
10127 char symbol [1024];
10128 GlobalsTableEntry *entry, *new_entry;
10130 if (!acfg->aot_opts.static_link)
10131 return;
10133 if (acfg->aot_opts.llvm_only) {
10134 g_assert (acfg->globals->len == 0);
10135 return;
10139 * When static linking, we emit a table containing our globals.
10143 * Construct a chained hash table for mapping global names to their index in
10144 * the globals table.
10146 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10147 table = g_ptr_array_sized_new (table_size);
10148 for (i = 0; i < table_size; ++i)
10149 g_ptr_array_add (table, NULL);
10150 for (i = 0; i < acfg->globals->len; ++i) {
10151 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10153 hash = mono_metadata_str_hash (name) % table_size;
10155 /* FIXME: Allocate from the mempool */
10156 new_entry = g_new0 (GlobalsTableEntry, 1);
10157 new_entry->value = i;
10159 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10160 if (entry == NULL) {
10161 new_entry->index = hash;
10162 g_ptr_array_index (table, hash) = new_entry;
10163 } else {
10164 while (entry->next)
10165 entry = entry->next;
10167 entry->next = new_entry;
10168 new_entry->index = table->len;
10169 g_ptr_array_add (table, new_entry);
10173 /* Emit the table */
10174 sprintf (symbol, ".Lglobals_hash");
10175 emit_section_change (acfg, RODATA_SECT, 0);
10176 emit_alignment (acfg, 8);
10177 emit_label (acfg, symbol);
10179 /* FIXME: Optimize memory usage */
10180 g_assert (table_size < 65000);
10181 emit_int16 (acfg, table_size);
10182 for (i = 0; i < table->len; ++i) {
10183 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10185 if (entry == NULL) {
10186 emit_int16 (acfg, 0);
10187 emit_int16 (acfg, 0);
10188 } else {
10189 emit_int16 (acfg, entry->value + 1);
10190 if (entry->next)
10191 emit_int16 (acfg, entry->next->index);
10192 else
10193 emit_int16 (acfg, 0);
10197 /* Emit the names */
10198 for (i = 0; i < acfg->globals->len; ++i) {
10199 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10201 sprintf (symbol, "name_%d", i);
10202 emit_section_change (acfg, RODATA_SECT, 1);
10203 #ifdef TARGET_MACH
10204 emit_alignment (acfg, 4);
10205 #endif
10206 emit_label (acfg, symbol);
10207 emit_string (acfg, name);
10210 /* Emit the globals table */
10211 sprintf (symbol, "globals");
10212 emit_section_change (acfg, ".data", 0);
10213 /* This is not a global, since it is accessed by the init function */
10214 emit_alignment (acfg, 8);
10215 emit_info_symbol (acfg, symbol);
10217 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10218 emit_pointer (acfg, symbol);
10220 for (i = 0; i < acfg->globals->len; ++i) {
10221 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10223 sprintf (symbol, "name_%d", i);
10224 emit_pointer (acfg, symbol);
10226 g_assert (strlen (name) < sizeof (symbol));
10227 sprintf (symbol, "%s", name);
10228 emit_pointer (acfg, symbol);
10230 /* Null terminate the table */
10231 emit_int32 (acfg, 0);
10232 emit_int32 (acfg, 0);
10235 static void
10236 emit_mem_end (MonoAotCompile *acfg)
10238 char symbol [128];
10240 if (acfg->aot_opts.llvm_only)
10241 return;
10243 sprintf (symbol, "mem_end");
10244 emit_section_change (acfg, ".text", 1);
10245 emit_alignment_code (acfg, 8);
10246 emit_label (acfg, symbol);
10249 static void
10250 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10252 int i;
10254 info->version = MONO_AOT_FILE_VERSION;
10255 info->plt_got_offset_base = acfg->plt_got_offset_base;
10256 info->got_size = acfg->got_offset * sizeof (gpointer);
10257 info->plt_size = acfg->plt_offset;
10258 info->nmethods = acfg->nmethods;
10259 info->flags = acfg->flags;
10260 info->opts = acfg->opts;
10261 info->simd_opts = acfg->simd_opts;
10262 info->gc_name_index = acfg->gc_name_offset;
10263 info->datafile_size = acfg->datafile_offset;
10264 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10265 info->table_offsets [i] = acfg->table_offsets [i];
10266 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10267 info->num_trampolines [i] = acfg->num_trampolines [i];
10268 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10269 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10270 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10271 info->trampoline_size [i] = acfg->trampoline_size [i];
10272 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10274 info->double_align = MONO_ABI_ALIGNOF (double);
10275 info->long_align = MONO_ABI_ALIGNOF (gint64);
10276 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10277 info->tramp_page_size = acfg->tramp_page_size;
10278 info->nshared_got_entries = acfg->nshared_got_entries;
10279 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10280 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10282 memcpy(&info->aotid, acfg->image->aotid, 16);
10285 static void
10286 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10288 char symbol [MAX_SYMBOL_SIZE];
10289 int i, sindex;
10290 const char **symbols;
10292 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10293 sindex = 0;
10294 symbols [sindex ++] = acfg->got_symbol;
10295 if (acfg->llvm) {
10296 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10297 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
10298 } else {
10299 symbols [sindex ++] = NULL;
10300 symbols [sindex ++] = NULL;
10302 /* llvm_get_method */
10303 symbols [sindex ++] = NULL;
10304 /* llvm_get_unbox_tramp */
10305 symbols [sindex ++] = NULL;
10306 if (!acfg->aot_opts.llvm_only) {
10307 symbols [sindex ++] = "jit_code_start";
10308 symbols [sindex ++] = "jit_code_end";
10309 symbols [sindex ++] = "method_addresses";
10310 } else {
10311 symbols [sindex ++] = NULL;
10312 symbols [sindex ++] = NULL;
10313 symbols [sindex ++] = NULL;
10316 if (acfg->data_outfile) {
10317 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10318 symbols [sindex ++] = NULL;
10319 } else {
10320 symbols [sindex ++] = "blob";
10321 symbols [sindex ++] = "class_name_table";
10322 symbols [sindex ++] = "class_info_offsets";
10323 symbols [sindex ++] = "method_info_offsets";
10324 symbols [sindex ++] = "ex_info_offsets";
10325 symbols [sindex ++] = "extra_method_info_offsets";
10326 symbols [sindex ++] = "extra_method_table";
10327 symbols [sindex ++] = "got_info_offsets";
10328 if (acfg->llvm)
10329 symbols [sindex ++] = "llvm_got_info_offsets";
10330 else
10331 symbols [sindex ++] = NULL;
10332 symbols [sindex ++] = "image_table";
10333 symbols [sindex ++] = "weak_field_indexes";
10336 symbols [sindex ++] = "mem_end";
10337 symbols [sindex ++] = "assembly_guid";
10338 symbols [sindex ++] = "runtime_version";
10339 if (acfg->num_trampoline_got_entries) {
10340 symbols [sindex ++] = "specific_trampolines";
10341 symbols [sindex ++] = "static_rgctx_trampolines";
10342 symbols [sindex ++] = "imt_trampolines";
10343 symbols [sindex ++] = "gsharedvt_arg_trampolines";
10344 } else {
10345 symbols [sindex ++] = NULL;
10346 symbols [sindex ++] = NULL;
10347 symbols [sindex ++] = NULL;
10348 symbols [sindex ++] = NULL;
10350 if (acfg->aot_opts.static_link) {
10351 symbols [sindex ++] = "globals";
10352 } else {
10353 symbols [sindex ++] = NULL;
10355 symbols [sindex ++] = "assembly_name";
10356 symbols [sindex ++] = "plt";
10357 symbols [sindex ++] = "plt_end";
10358 symbols [sindex ++] = "unwind_info";
10359 if (!acfg->aot_opts.llvm_only) {
10360 symbols [sindex ++] = "unbox_trampolines";
10361 symbols [sindex ++] = "unbox_trampolines_end";
10362 symbols [sindex ++] = "unbox_trampoline_addresses";
10363 } else {
10364 symbols [sindex ++] = NULL;
10365 symbols [sindex ++] = NULL;
10366 symbols [sindex ++] = NULL;
10369 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10371 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10372 emit_section_change (acfg, ".data", 0);
10373 emit_alignment (acfg, 8);
10374 emit_label (acfg, symbol);
10375 if (!acfg->aot_opts.static_link)
10376 emit_global (acfg, symbol, FALSE);
10378 /* The data emitted here must match MonoAotFileInfo. */
10380 emit_int32 (acfg, info->version);
10381 emit_int32 (acfg, info->dummy);
10384 * We emit pointers to our data structures instead of emitting global symbols which
10385 * point to them, to reduce the number of globals, and because using globals leads to
10386 * various problems (i.e. arm/thumb).
10388 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10389 emit_pointer (acfg, symbols [i]);
10391 emit_int32 (acfg, info->plt_got_offset_base);
10392 emit_int32 (acfg, info->got_size);
10393 emit_int32 (acfg, info->plt_size);
10394 emit_int32 (acfg, info->nmethods);
10395 emit_int32 (acfg, info->flags);
10396 emit_int32 (acfg, info->opts);
10397 emit_int32 (acfg, info->simd_opts);
10398 emit_int32 (acfg, info->gc_name_index);
10399 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10400 emit_int32 (acfg, info->double_align);
10401 emit_int32 (acfg, info->long_align);
10402 emit_int32 (acfg, info->generic_tramp_num);
10403 emit_int32 (acfg, info->tramp_page_size);
10404 emit_int32 (acfg, info->nshared_got_entries);
10405 emit_int32 (acfg, info->datafile_size);
10407 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10408 emit_int32 (acfg, info->table_offsets [i]);
10409 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10410 emit_int32 (acfg, info->num_trampolines [i]);
10411 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10412 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10413 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10414 emit_int32 (acfg, info->trampoline_size [i]);
10415 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10416 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10418 emit_bytes (acfg, info->aotid, 16);
10420 if (acfg->aot_opts.static_link) {
10421 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10422 emit_alignment (acfg, sizeof (gpointer));
10423 emit_label (acfg, acfg->static_linking_symbol);
10424 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10429 * Emit a structure containing all the information not stored elsewhere.
10431 static void
10432 emit_file_info (MonoAotCompile *acfg)
10434 char *build_info;
10435 MonoAotFileInfo *info;
10437 if (acfg->aot_opts.bind_to_runtime_version) {
10438 build_info = mono_get_runtime_build_info ();
10439 emit_string_symbol (acfg, "runtime_version", build_info);
10440 g_free (build_info);
10441 } else {
10442 emit_string_symbol (acfg, "runtime_version", "");
10445 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10447 /* Emit a string holding the assembly name */
10448 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10450 info = g_new0 (MonoAotFileInfo, 1);
10451 init_aot_file_info (acfg, info);
10453 if (acfg->aot_opts.static_link) {
10454 char symbol [MAX_SYMBOL_SIZE];
10455 char *p;
10458 * Emit a global symbol which can be passed by an embedding app to
10459 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10460 * structure.
10462 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10464 /* Get rid of characters which cannot occur in symbols */
10465 p = symbol;
10466 for (p = symbol; *p; ++p) {
10467 if (!(isalnum (*p) || *p == '_'))
10468 *p = '_';
10470 acfg->static_linking_symbol = g_strdup (symbol);
10473 if (acfg->llvm)
10474 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10475 else
10476 emit_aot_file_info (acfg, info);
10479 static void
10480 emit_blob (MonoAotCompile *acfg)
10482 acfg->blob_closed = TRUE;
10484 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10487 static void
10488 emit_objc_selectors (MonoAotCompile *acfg)
10490 int i;
10491 char symbol [128];
10493 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10494 return;
10497 * From
10498 * cat > foo.m << EOF
10499 * void *ret ()
10501 * return @selector(print:);
10503 * EOF
10506 mono_img_writer_emit_unset_mode (acfg->w);
10507 g_assert (acfg->fp);
10508 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10509 fprintf (acfg->fp, ".align 3\n");
10510 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10511 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10512 emit_label (acfg, symbol);
10513 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10514 emit_pointer (acfg, symbol);
10517 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10518 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10519 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10520 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10523 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10524 fprintf (acfg->fp, ".align 3\n");
10525 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10526 fprintf (acfg->fp, ".long 0\n");
10527 fprintf (acfg->fp, ".long 16\n");
10530 static void
10531 emit_dwarf_info (MonoAotCompile *acfg)
10533 #ifdef EMIT_DWARF_INFO
10534 int i;
10535 char symbol2 [128];
10537 /* DIEs for methods */
10538 for (i = 0; i < acfg->nmethods; ++i) {
10539 MonoCompile *cfg = acfg->cfgs [i];
10541 if (ignore_cfg (cfg))
10542 continue;
10544 // FIXME: LLVM doesn't define .Lme_...
10545 if (cfg->compile_llvm)
10546 continue;
10548 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10550 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 ()));
10552 #endif
10555 #ifdef EMIT_WIN32_CODEVIEW_INFO
10556 typedef struct _CodeViewSubSectionData
10558 gchar *start_section;
10559 gchar *end_section;
10560 gchar *start_section_record;
10561 gchar *end_section_record;
10562 int section_type;
10563 int section_record_type;
10564 int section_id;
10565 } CodeViewSubsectionData;
10567 typedef struct _CodeViewCompilerVersion
10569 gint major;
10570 gint minor;
10571 gint revision;
10572 gint patch;
10573 } CodeViewCompilerVersion;
10575 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
10576 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
10577 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
10578 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
10579 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
10580 #define CODEVIEW_CPU_TYPE 0x0
10581 #define CODEVIEW_MAGIC_HEADER 0x4
10583 static void
10584 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
10586 g_free (section_data->start_section);
10587 g_free (section_data->end_section);
10588 g_free (section_data->start_section_record);
10589 g_free (section_data->end_section_record);
10591 memset (section_data, 0, sizeof (CodeViewSubsectionData));
10594 static void
10595 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
10597 gint values[4] = { 0 };
10598 gint *value = values;
10600 while (*version && (value < values + G_N_ELEMENTS (values))) {
10601 if (isdigit (*version)) {
10602 *value *= 10;
10603 *value += *version - '0';
10605 else if (*version == '.') {
10606 value++;
10609 version++;
10612 data->major = values[0];
10613 data->minor = values[1];
10614 data->revision = values[2];
10615 data->patch = values[3];
10618 static void
10619 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
10621 // Starting a new subsection, clear old data.
10622 codeview_clear_subsection_data (section_data);
10624 // Keep subsection data.
10625 section_data->section_id = section_id;
10626 section_data->section_type = section_type;
10627 section_data->section_record_type = section_record_type;
10629 // Allocate all labels used in subsection.
10630 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
10631 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
10632 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
10633 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
10635 // Subsection type, function symbol.
10636 emit_int32 (acfg, section_data->section_type);
10638 // Subsection size.
10639 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
10640 emit_label (acfg, section_data->start_section);
10642 // Subsection record size.
10643 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
10644 emit_label (acfg, section_data->start_section_record);
10646 // Subsection record type.
10647 emit_int16 (acfg, section_record_type);
10650 static void
10651 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10653 g_assert (section_data->start_section);
10654 g_assert (section_data->end_section);
10655 g_assert (section_data->start_section_record);
10656 g_assert (section_data->end_section_record);
10658 emit_label (acfg, section_data->end_section_record);
10660 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
10661 // Emit record length.
10662 emit_int16 (acfg, 2);
10664 // Emit specific record type end.
10665 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
10668 emit_label (acfg, section_data->end_section);
10670 // Next subsection needs to be 4 byte aligned.
10671 emit_alignment (acfg, 4);
10673 *section_id = section_data->section_id + 1;
10674 codeview_clear_subsection_data (section_data);
10677 inline static void
10678 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
10680 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
10683 inline static void
10684 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10686 emit_codeview_end_subsection (acfg, section_data, section_id);
10689 static void
10690 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
10692 CodeViewSubsectionData section_data = { 0 };
10693 CodeViewCompilerVersion compiler_version = { 0 };
10695 // Start new compiler record subsection.
10696 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
10698 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
10699 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
10701 // Get compiler version information.
10702 codeview_parse_compiler_version (VERSION, &compiler_version);
10704 // Compiler frontend version, 4 digits.
10705 emit_int16 (acfg, compiler_version.major);
10706 emit_int16 (acfg, compiler_version.minor);
10707 emit_int16 (acfg, compiler_version.revision);
10708 emit_int16 (acfg, compiler_version.patch);
10710 // Compiler backend version, 4 digits (currently same as frontend).
10711 emit_int16 (acfg, compiler_version.major);
10712 emit_int16 (acfg, compiler_version.minor);
10713 emit_int16 (acfg, compiler_version.revision);
10714 emit_int16 (acfg, compiler_version.patch);
10716 // Compiler string.
10717 emit_string (acfg, "Mono AOT compiler");
10719 // Done with section.
10720 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
10723 static void
10724 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
10726 CodeViewSubsectionData section_data = { 0 };
10727 gchar *full_method_name = NULL;
10729 // Start new function record subsection.
10730 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
10732 // Emit 3 int 0 byte padding, currently not used.
10733 emit_zero_bytes (acfg, sizeof (int) * 3);
10735 // Emit size of function.
10736 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
10738 // Emit 3 int 0 byte padding, currently not used.
10739 emit_zero_bytes (acfg, sizeof (int) * 3);
10741 // Emit reallocation info.
10742 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
10743 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
10745 // Emit flag, currently not used.
10746 emit_zero_bytes (acfg, 1);
10748 // Emit function name, exclude signature since it should be described by own metadata.
10749 full_method_name = mono_method_full_name (method, FALSE);
10750 emit_string (acfg, full_method_name ? full_method_name : "");
10751 g_free (full_method_name);
10753 // Done with section.
10754 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
10757 static void
10758 emit_codeview_info (MonoAotCompile *acfg)
10760 int i;
10761 int section_id = 0;
10762 gchar symbol_buffer[MAX_SYMBOL_SIZE];
10764 // Emit codeview debug info section
10765 emit_section_change (acfg, ".debug$S", 0);
10767 // Emit magic header.
10768 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
10770 emit_codeview_compiler_info (acfg, &section_id);
10772 for (i = 0; i < acfg->nmethods; ++i) {
10773 MonoCompile *cfg = acfg->cfgs[i];
10775 if (!cfg)
10776 continue;
10778 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
10779 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
10780 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
10783 #else
10784 static void
10785 emit_codeview_info (MonoAotCompile *acfg)
10788 #endif /* EMIT_WIN32_CODEVIEW_INFO */
10790 #ifdef EMIT_WIN32_UNWIND_INFO
10791 static UnwindInfoSectionCacheItem *
10792 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
10794 UnwindInfoSectionCacheItem *item = NULL;
10796 if (!acfg->unwind_info_section_cache)
10797 acfg->unwind_info_section_cache = g_list_alloc ();
10799 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
10801 // Search for unwind info in cache.
10802 GList *list = acfg->unwind_info_section_cache;
10803 int list_size = 0;
10804 while (list && list->data) {
10805 item = (UnwindInfoSectionCacheItem*)list->data;
10806 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
10807 // Cache hit, return cached item.
10808 return item;
10810 list = list->next;
10811 list_size++;
10814 // Add to cache.
10815 if (acfg->unwind_info_section_cache) {
10816 item = g_new0 (UnwindInfoSectionCacheItem, 1);
10817 if (item) {
10818 // Format .xdata section label for function, used to get unwind info address RVA.
10819 // Since the unwind info is similar for most functions, the symbol will be reused.
10820 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
10822 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
10823 //over ownership of unwind info.
10824 item->unwind_info = unwind_info;
10826 // Needs to be emitted once.
10827 item->xdata_section_emitted = FALSE;
10829 // Prepend to beginning of list to speed up inserts.
10830 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
10834 return item;
10837 static void
10838 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
10840 GList *list = acfg->unwind_info_section_cache;
10842 while (list) {
10843 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
10844 if (item) {
10845 g_free (item->xdata_section_label);
10846 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
10848 g_free (item);
10849 list->data = NULL;
10852 list = list->next;
10855 g_list_free (acfg->unwind_info_section_cache);
10856 acfg->unwind_info_section_cache = NULL;
10859 static void
10860 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
10862 // Emit the unwind info struct.
10863 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
10865 // Emit all unwind codes encoded in unwind info struct.
10866 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
10867 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
10869 while (current_unwind_node < last_unwind_node) {
10870 guint8 node_count = 0;
10871 switch (current_unwind_node->UnwindOp) {
10872 case UWOP_PUSH_NONVOL:
10873 case UWOP_ALLOC_SMALL:
10874 case UWOP_SET_FPREG:
10875 case UWOP_PUSH_MACHFRAME:
10876 node_count = 1;
10877 break;
10878 case UWOP_SAVE_NONVOL:
10879 case UWOP_SAVE_XMM128:
10880 node_count = 2;
10881 break;
10882 case UWOP_SAVE_NONVOL_FAR:
10883 case UWOP_SAVE_XMM128_FAR:
10884 node_count = 3;
10885 break;
10886 case UWOP_ALLOC_LARGE:
10887 if (current_unwind_node->OpInfo == 0)
10888 node_count = 2;
10889 else
10890 node_count = 3;
10891 break;
10892 default:
10893 g_assert (!"Unknown unwind opcode.");
10896 while (node_count > 0) {
10897 g_assert (current_unwind_node < last_unwind_node);
10899 //Emit current node.
10900 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
10902 node_count--;
10903 current_unwind_node++;
10908 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
10909 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
10910 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
10911 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
10912 static void
10913 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
10915 char *pdata_section_label = NULL;
10917 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
10918 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
10919 temp_prefix_len = 0;
10922 // Format .pdata section label for function.
10923 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
10925 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
10926 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
10928 // Emit .pdata section.
10929 emit_section_change (acfg, ".pdata", 0);
10930 emit_alignment (acfg, sizeof (DWORD));
10931 emit_label (acfg, pdata_section_label);
10933 // Emit function start address RVA.
10934 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
10936 // Emit function end address RVA.
10937 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
10939 // Emit unwind info address RVA.
10940 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
10942 if (!cache_item->xdata_section_emitted) {
10943 // Emit .xdata section.
10944 emit_section_change (acfg, ".xdata", 0);
10945 emit_alignment (acfg, sizeof (DWORD));
10946 emit_label (acfg, cache_item->xdata_section_label);
10948 // Emit unwind info into .xdata section.
10949 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
10950 cache_item->xdata_section_emitted = TRUE;
10953 g_free (pdata_section_label);
10955 #endif
10957 static gboolean
10958 collect_methods (MonoAotCompile *acfg)
10960 int mindex, i;
10961 MonoImage *image = acfg->image;
10963 /* Collect methods */
10964 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10965 ERROR_DECL (error);
10966 MonoMethod *method;
10967 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10969 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
10971 if (!method) {
10972 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
10973 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10974 mono_error_cleanup (error);
10975 return FALSE;
10978 /* Load all methods eagerly to skip the slower lazy loading code */
10979 mono_class_setup_methods (method->klass);
10981 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10982 /* Compile the wrapper instead */
10983 /* We do this here instead of add_wrappers () because it is easy to do it here */
10984 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10985 method = wrapper;
10988 /* FIXME: Some mscorlib methods don't have debug info */
10990 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10991 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10992 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10993 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10994 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10995 if (!mono_debug_lookup_method (method)) {
10996 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10997 exit (1);
11003 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11004 /* Compile the ref shared version instead */
11005 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11006 if (!method) {
11007 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11008 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11009 mono_error_cleanup (error);
11010 return FALSE;
11014 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11015 add_method_with_index (acfg, method, i, FALSE);
11016 acfg->method_index ++;
11019 /* gsharedvt methods */
11020 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11021 ERROR_DECL (error);
11022 MonoMethod *method;
11023 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11025 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11026 continue;
11028 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11029 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11031 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11032 MonoMethod *gshared;
11034 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11035 mono_error_assert_ok (error);
11037 add_extra_method (acfg, gshared);
11041 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11042 add_generic_instances (acfg);
11044 if (mono_aot_mode_is_full (&acfg->aot_opts))
11045 add_wrappers (acfg);
11046 return TRUE;
11049 static void
11050 compile_methods (MonoAotCompile *acfg)
11052 int i, methods_len;
11054 if (acfg->aot_opts.nthreads > 0) {
11055 GPtrArray *frag;
11056 int len, j;
11057 GPtrArray *threads;
11058 MonoThreadHandle *thread_handle;
11059 gpointer *user_data;
11060 MonoMethod **methods;
11062 methods_len = acfg->methods->len;
11064 len = acfg->methods->len / acfg->aot_opts.nthreads;
11065 g_assert (len > 0);
11067 * Partition the list of methods into fragments, and hand it to threads to
11068 * process.
11070 threads = g_ptr_array_new ();
11071 /* Make a copy since acfg->methods is modified by compile_method () */
11072 methods = g_new0 (MonoMethod*, methods_len);
11073 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11074 for (i = 0; i < methods_len; ++i)
11075 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11076 i = 0;
11077 while (i < methods_len) {
11078 ERROR_DECL (error);
11079 MonoInternalThread *thread;
11081 frag = g_ptr_array_new ();
11082 for (j = 0; j < len; ++j) {
11083 if (i < methods_len) {
11084 g_ptr_array_add (frag, methods [i]);
11085 i ++;
11089 user_data = g_new0 (gpointer, 3);
11090 user_data [0] = acfg;
11091 user_data [1] = frag;
11093 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11094 mono_error_assert_ok (error);
11096 thread_handle = mono_threads_open_thread_handle (thread->handle);
11097 g_ptr_array_add (threads, thread_handle);
11099 g_free (methods);
11101 for (i = 0; i < threads->len; ++i) {
11102 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11103 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
11105 } else {
11106 methods_len = 0;
11109 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11110 for (i = methods_len; i < acfg->methods->len; ++i) {
11111 /* This can add new methods to acfg->methods */
11112 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11116 static int
11117 compile_asm (MonoAotCompile *acfg)
11119 char *command, *objfile;
11120 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11121 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11122 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11124 #ifdef TARGET_WIN32_MSVC
11125 #define AS_OPTIONS "-c -x assembler"
11126 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11127 #define AS_OPTIONS "--64"
11128 #elif defined(TARGET_POWERPC64)
11129 #define AS_OPTIONS "-a64 -mppc64"
11130 #elif defined(sparc) && SIZEOF_VOID_P == 8
11131 #define AS_OPTIONS "-xarch=v9"
11132 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11133 #define AS_OPTIONS "-arch i386"
11134 #else
11135 #define AS_OPTIONS ""
11136 #endif
11138 #if defined(TARGET_OSX)
11139 #define AS_NAME "clang"
11140 #elif defined(TARGET_WIN32_MSVC)
11141 #define AS_NAME "clang.exe"
11142 #else
11143 #define AS_NAME "as"
11144 #endif
11146 #ifdef TARGET_WIN32_MSVC
11147 #define AS_OBJECT_FILE_SUFFIX "obj"
11148 #else
11149 #define AS_OBJECT_FILE_SUFFIX "o"
11150 #endif
11152 #if defined(sparc)
11153 #define LD_NAME "ld"
11154 #define LD_OPTIONS "-shared -G"
11155 #elif defined(__ppc__) && defined(TARGET_MACH)
11156 #define LD_NAME "gcc"
11157 #define LD_OPTIONS "-dynamiclib"
11158 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11159 #define LD_NAME "clang"
11160 #define LD_OPTIONS "--shared"
11161 #elif defined(TARGET_WIN32_MSVC)
11162 #define LD_NAME "link.exe"
11163 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11164 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11165 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11166 #define LD_NAME "gcc"
11167 #define LD_OPTIONS "-shared"
11168 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11169 #define LD_NAME "clang"
11170 #define LD_OPTIONS "-m32 -dynamiclib"
11171 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11172 #define LD_NAME "gcc"
11173 #define LD_OPTIONS "--shared"
11174 #elif defined(TARGET_POWERPC64)
11175 #define LD_OPTIONS "-m elf64ppc"
11176 #endif
11178 #ifndef LD_OPTIONS
11179 #define LD_OPTIONS ""
11180 #endif
11182 if (acfg->aot_opts.asm_only) {
11183 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11184 if (acfg->aot_opts.static_link)
11185 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11186 if (acfg->llvm)
11187 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11188 return 0;
11191 if (acfg->aot_opts.static_link) {
11192 if (acfg->aot_opts.outfile)
11193 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11194 else
11195 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11196 } else {
11197 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11200 #ifdef TARGET_OSX
11201 g_string_append (acfg->as_args, "-c -x assembler");
11202 #endif
11204 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11205 acfg->as_args ? acfg->as_args->str : "",
11206 wrap_path (objfile), wrap_path (acfg->tmpfname));
11207 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11208 if (execute_system (command) != 0) {
11209 g_free (command);
11210 g_free (objfile);
11211 return 1;
11214 if (acfg->llvm && !acfg->llvm_owriter) {
11215 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11216 acfg->as_args ? acfg->as_args->str : "",
11217 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11218 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11219 if (execute_system (command) != 0) {
11220 g_free (command);
11221 g_free (objfile);
11222 return 1;
11226 g_free (command);
11228 if (acfg->aot_opts.static_link) {
11229 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11230 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11231 g_free (objfile);
11232 return 0;
11235 if (acfg->aot_opts.outfile)
11236 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11237 else
11238 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11240 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11242 if (acfg->llvm) {
11243 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11244 } else {
11245 llvm_ofile = g_strdup ("");
11248 /* replace the ; flags separators with spaces */
11249 g_strdelimit (ld_flags, ";", ' ');
11251 if (acfg->aot_opts.llvm_only)
11252 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11254 #ifdef TARGET_WIN32_MSVC
11255 g_assert (tmp_outfile_name != NULL);
11256 g_assert (objfile != NULL);
11257 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME,
11258 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, tmp_outfile_name, objfile);
11259 #elif defined(LD_NAME)
11260 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11261 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11262 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11263 #else
11264 // Default (linux)
11265 if (acfg->aot_opts.tool_prefix) {
11266 /* Cross compiling */
11267 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
11268 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11269 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11270 } else {
11271 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
11272 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11273 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11275 if (acfg->aot_opts.llvm_only) {
11276 command = g_strdup_printf ("clang++ %s", args);
11277 } else {
11278 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
11280 g_free (args);
11282 #endif
11283 aot_printf (acfg, "Executing the native linker: %s\n", command);
11284 if (execute_system (command) != 0) {
11285 g_free (tmp_outfile_name);
11286 g_free (outfile_name);
11287 g_free (command);
11288 g_free (objfile);
11289 g_free (ld_flags);
11290 return 1;
11293 g_free (command);
11295 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
11296 printf ("Stripping the binary: %s\n", com);
11297 execute_system (com);
11298 g_free (com);*/
11300 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
11302 * gas generates 'mapping symbols' each time code and data is mixed, which
11303 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
11305 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
11306 aot_printf (acfg, "Stripping the binary: %s\n", command);
11307 if (execute_system (command) != 0) {
11308 g_free (tmp_outfile_name);
11309 g_free (outfile_name);
11310 g_free (command);
11311 g_free (objfile);
11312 return 1;
11314 #endif
11316 if (0 != rename (tmp_outfile_name, outfile_name)) {
11317 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
11318 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
11319 unlink (outfile_name);
11320 rename (tmp_outfile_name, outfile_name);
11324 #if defined(TARGET_MACH)
11325 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
11326 aot_printf (acfg, "Executing dsymutil: %s\n", command);
11327 if (execute_system (command) != 0) {
11328 return 1;
11330 #endif
11332 if (!acfg->aot_opts.save_temps)
11333 unlink (objfile);
11335 g_free (tmp_outfile_name);
11336 g_free (outfile_name);
11337 g_free (objfile);
11339 if (acfg->aot_opts.save_temps)
11340 aot_printf (acfg, "Retained input file.\n");
11341 else
11342 unlink (acfg->tmpfname);
11344 return 0;
11347 static guint8
11348 profread_byte (FILE *infile)
11350 guint8 i;
11351 int res;
11353 res = fread (&i, 1, 1, infile);
11354 g_assert (res == 1);
11355 return i;
11358 static int
11359 profread_int (FILE *infile)
11361 int i, res;
11363 res = fread (&i, 4, 1, infile);
11364 g_assert (res == 1);
11365 return i;
11368 static char*
11369 profread_string (FILE *infile)
11371 int len, res;
11372 char *pbuf;
11374 len = profread_int (infile);
11375 pbuf = (char*)g_malloc (len + 1);
11376 res = fread (pbuf, 1, len, infile);
11377 g_assert (res == len);
11378 pbuf [len] = '\0';
11379 return pbuf;
11382 static void
11383 load_profile_file (MonoAotCompile *acfg, char *filename)
11385 FILE *infile;
11386 char buf [1024];
11387 int res, len, version;
11388 char magic [32];
11390 infile = fopen (filename, "r");
11391 if (!infile) {
11392 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
11393 exit (1);
11396 printf ("Using profile data file '%s'\n", filename);
11398 sprintf (magic, AOT_PROFILER_MAGIC);
11399 len = strlen (magic);
11400 res = fread (buf, 1, len, infile);
11401 magic [len] = '\0';
11402 buf [len] = '\0';
11403 if ((res != len) || strcmp (buf, magic) != 0) {
11404 printf ("Profile file has wrong header: '%s'.\n", buf);
11405 fclose (infile);
11406 exit (1);
11408 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
11409 version = profread_int (infile);
11410 if (version != expected_version) {
11411 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
11412 fclose (infile);
11413 exit (1);
11416 ProfileData *data = g_new0 (ProfileData, 1);
11417 data->images = g_hash_table_new (NULL, NULL);
11418 data->classes = g_hash_table_new (NULL, NULL);
11419 data->ginsts = g_hash_table_new (NULL, NULL);
11420 data->methods = g_hash_table_new (NULL, NULL);
11422 while (TRUE) {
11423 int type = profread_byte (infile);
11424 int id = profread_int (infile);
11426 if (type == AOTPROF_RECORD_NONE)
11427 break;
11429 switch (type) {
11430 case AOTPROF_RECORD_IMAGE: {
11431 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
11432 idata->name = profread_string (infile);
11433 char *mvid = profread_string (infile);
11434 g_free (mvid);
11435 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
11436 break;
11438 case AOTPROF_RECORD_GINST: {
11439 int i;
11440 int len = profread_int (infile);
11442 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
11443 gdata->argc = len;
11444 gdata->argv = g_new0 (ClassProfileData*, len);
11446 for (i = 0; i < len; ++i) {
11447 int class_id = profread_int (infile);
11449 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11450 g_assert (gdata->argv [i]);
11452 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
11453 break;
11455 case AOTPROF_RECORD_TYPE: {
11456 int type = profread_byte (infile);
11458 switch (type) {
11459 case MONO_TYPE_CLASS: {
11460 int image_id = profread_int (infile);
11461 int ginst_id = profread_int (infile);
11462 char *class_name = profread_string (infile);
11464 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
11465 g_assert (image);
11467 char *p = strrchr (class_name, '.');
11468 g_assert (p);
11469 *p = '\0';
11471 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
11472 cdata->image = image;
11473 cdata->ns = g_strdup (class_name);
11474 cdata->name = g_strdup (p + 1);
11476 if (ginst_id != -1) {
11477 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11478 g_assert (cdata->inst);
11480 g_free (class_name);
11482 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
11483 break;
11485 #if 0
11486 case MONO_TYPE_SZARRAY: {
11487 int elem_id = profread_int (infile);
11488 // FIXME:
11489 break;
11491 #endif
11492 default:
11493 g_assert_not_reached ();
11494 break;
11496 break;
11498 case AOTPROF_RECORD_METHOD: {
11499 int class_id = profread_int (infile);
11500 int ginst_id = profread_int (infile);
11501 int param_count = profread_int (infile);
11502 char *method_name = profread_string (infile);
11503 char *sig = profread_string (infile);
11505 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11506 g_assert (klass);
11508 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
11509 mdata->id = id;
11510 mdata->klass = klass;
11511 mdata->name = method_name;
11512 mdata->signature = sig;
11513 mdata->param_count = param_count;
11515 if (ginst_id != -1) {
11516 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11517 g_assert (mdata->inst);
11519 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
11520 break;
11522 default:
11523 printf ("%d\n", type);
11524 g_assert_not_reached ();
11525 break;
11529 fclose (infile);
11530 acfg->profile_data = g_list_append (acfg->profile_data, data);
11533 static void
11534 resolve_class (ClassProfileData *cdata);
11536 static void
11537 resolve_ginst (GInstProfileData *inst_data)
11539 int i;
11541 if (inst_data->inst)
11542 return;
11544 for (i = 0; i < inst_data->argc; ++i) {
11545 resolve_class (inst_data->argv [i]);
11546 if (!inst_data->argv [i]->klass)
11547 return;
11549 MonoType **args = g_new0 (MonoType*, inst_data->argc);
11550 for (i = 0; i < inst_data->argc; ++i)
11551 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
11553 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
11556 static void
11557 resolve_class (ClassProfileData *cdata)
11559 ERROR_DECL (error);
11560 MonoClass *klass;
11562 if (!cdata->image->image)
11563 return;
11565 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
11566 if (!klass) {
11567 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
11568 return;
11570 if (cdata->inst) {
11571 resolve_ginst (cdata->inst);
11572 if (!cdata->inst->inst)
11573 return;
11574 MonoGenericContext ctx;
11576 memset (&ctx, 0, sizeof (ctx));
11577 ctx.class_inst = cdata->inst->inst;
11578 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
11579 } else {
11580 cdata->klass = klass;
11585 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
11587 static void
11588 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
11590 GHashTableIter iter;
11591 gpointer key, value;
11592 int i;
11594 if (!data)
11595 return;
11597 /* Images */
11598 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
11599 g_hash_table_iter_init (&iter, data->images);
11600 while (g_hash_table_iter_next (&iter, &key, &value)) {
11601 ImageProfileData *idata = (ImageProfileData*)value;
11603 for (i = 0; i < assemblies->len; ++i) {
11604 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
11606 if (!strcmp (ass->aname.name, idata->name)) {
11607 idata->image = ass->image;
11608 break;
11612 g_ptr_array_free (assemblies, TRUE);
11614 /* Classes */
11615 g_hash_table_iter_init (&iter, data->classes);
11616 while (g_hash_table_iter_next (&iter, &key, &value)) {
11617 ClassProfileData *cdata = (ClassProfileData*)value;
11619 if (!cdata->image->image) {
11620 if (acfg->aot_opts.verbose)
11621 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
11622 continue;
11625 resolve_class (cdata);
11627 if (cdata->klass)
11628 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
11632 /* Methods */
11633 g_hash_table_iter_init (&iter, data->methods);
11634 while (g_hash_table_iter_next (&iter, &key, &value)) {
11635 MethodProfileData *mdata = (MethodProfileData*)value;
11636 MonoClass *klass;
11637 MonoMethod *m;
11638 gpointer miter;
11640 resolve_class (mdata->klass);
11641 klass = mdata->klass->klass;
11642 if (!klass) {
11643 if (acfg->aot_opts.verbose)
11644 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
11645 continue;
11647 miter = NULL;
11648 while ((m = mono_class_get_methods (klass, &miter))) {
11649 ERROR_DECL (error);
11651 if (strcmp (m->name, mdata->name))
11652 continue;
11653 MonoMethodSignature *sig = mono_method_signature (m);
11654 if (!sig)
11655 continue;
11656 if (sig->param_count != mdata->param_count)
11657 continue;
11658 if (mdata->inst) {
11659 resolve_ginst (mdata->inst);
11660 if (!mdata->inst->inst)
11661 continue;
11662 MonoGenericContext ctx;
11664 memset (&ctx, 0, sizeof (ctx));
11665 ctx.method_inst = mdata->inst->inst;
11667 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
11668 if (!m)
11669 continue;
11670 sig = mono_method_signature_checked (m, error);
11671 if (!is_ok (error)) {
11672 mono_error_cleanup (error);
11673 continue;
11676 char *sig_str = mono_signature_full_name (sig);
11677 gboolean match = !strcmp (sig_str, mdata->signature);
11678 g_free (sig_str);
11679 if (!match)
11681 continue;
11682 //printf ("%s\n", mono_method_full_name (m, 1));
11683 mdata->method = m;
11684 break;
11686 if (!mdata->method) {
11687 if (acfg->aot_opts.verbose)
11688 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
11693 static gboolean
11694 inst_references_image (MonoGenericInst *inst, MonoImage *image)
11696 int i;
11698 for (i = 0; i < inst->type_argc; ++i) {
11699 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
11700 if (m_class_get_image (k) == image)
11701 return TRUE;
11702 if (mono_class_is_ginst (k)) {
11703 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
11704 if (inst_references_image (kinst, image))
11705 return TRUE;
11708 return FALSE;
11711 static gboolean
11712 is_local_inst (MonoGenericInst *inst, MonoImage *image)
11714 int i;
11716 for (i = 0; i < inst->type_argc; ++i) {
11717 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
11718 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
11719 return FALSE;
11721 return TRUE;
11724 static void
11725 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
11727 GHashTableIter iter;
11728 gpointer key, value;
11729 int count = 0;
11731 if (!data)
11732 return;
11734 if (acfg->aot_opts.profile_only) {
11735 /* Add methods referenced by the profile */
11736 g_hash_table_iter_init (&iter, data->methods);
11737 while (g_hash_table_iter_next (&iter, &key, &value)) {
11738 MethodProfileData *mdata = (MethodProfileData*)value;
11739 MonoMethod *m = mdata->method;
11741 if (!m)
11742 continue;
11743 if (m->is_inflated)
11744 continue;
11745 add_extra_method (acfg, m);
11746 g_hash_table_insert (acfg->profile_methods, m, m);
11747 count ++;
11752 * Add method instances 'related' to this assembly to the AOT image.
11754 g_hash_table_iter_init (&iter, data->methods);
11755 while (g_hash_table_iter_next (&iter, &key, &value)) {
11756 MethodProfileData *mdata = (MethodProfileData*)value;
11757 MonoMethod *m = mdata->method;
11758 MonoGenericContext *ctx;
11760 if (!m)
11761 continue;
11762 if (!m->is_inflated)
11763 continue;
11765 ctx = mono_method_get_context (m);
11766 /* For simplicity, add instances which reference the assembly we are compiling */
11767 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
11768 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
11769 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11770 //printf ("%s\n", mono_method_full_name (m, TRUE));
11771 add_extra_method (acfg, m);
11772 count ++;
11773 } else if (m_class_get_image (m->klass) == acfg->image &&
11774 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11775 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11776 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11777 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11778 //printf ("%s\n", mono_method_full_name (m, TRUE));
11779 add_extra_method (acfg, m);
11780 count ++;
11783 * FIXME: We might skip some instances, for example:
11784 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11785 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11789 printf ("Added %d methods from profile.\n", count);
11792 static void
11793 init_got_info (GotInfo *info)
11795 int i;
11797 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11798 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11799 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11800 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11801 info->got_patches = g_ptr_array_new ();
11804 static MonoAotCompile*
11805 acfg_create (MonoAssembly *ass, guint32 opts)
11807 MonoImage *image = ass->image;
11808 MonoAotCompile *acfg;
11810 acfg = g_new0 (MonoAotCompile, 1);
11811 acfg->methods = g_ptr_array_new ();
11812 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11813 acfg->method_depth = g_hash_table_new (NULL, NULL);
11814 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11815 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11816 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11817 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11818 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11819 acfg->image_hash = g_hash_table_new (NULL, NULL);
11820 acfg->image_table = g_ptr_array_new ();
11821 acfg->globals = g_ptr_array_new ();
11822 acfg->image = image;
11823 acfg->opts = opts;
11824 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11825 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11826 acfg->mempool = mono_mempool_new ();
11827 acfg->extra_methods = g_ptr_array_new ();
11828 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11829 acfg->unwind_ops = g_ptr_array_new ();
11830 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11831 acfg->method_order = g_ptr_array_new ();
11832 acfg->export_names = g_hash_table_new (NULL, NULL);
11833 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11834 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11835 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11836 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11837 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11838 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11839 mono_os_mutex_init_recursive (&acfg->mutex);
11841 init_got_info (&acfg->got_info);
11842 init_got_info (&acfg->llvm_got_info);
11844 return acfg;
11847 static void
11848 got_info_free (GotInfo *info)
11850 int i;
11852 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11853 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11854 g_free (info->patch_to_got_offset_by_type);
11855 g_hash_table_destroy (info->patch_to_got_offset);
11856 g_ptr_array_free (info->got_patches, TRUE);
11859 static void
11860 acfg_free (MonoAotCompile *acfg)
11862 int i;
11864 mono_img_writer_destroy (acfg->w);
11865 for (i = 0; i < acfg->nmethods; ++i)
11866 if (acfg->cfgs [i])
11867 mono_destroy_compile (acfg->cfgs [i]);
11869 g_free (acfg->cfgs);
11871 g_free (acfg->static_linking_symbol);
11872 g_free (acfg->got_symbol);
11873 g_free (acfg->plt_symbol);
11874 g_ptr_array_free (acfg->methods, TRUE);
11875 g_ptr_array_free (acfg->image_table, TRUE);
11876 g_ptr_array_free (acfg->globals, TRUE);
11877 g_ptr_array_free (acfg->unwind_ops, TRUE);
11878 g_hash_table_destroy (acfg->method_indexes);
11879 g_hash_table_destroy (acfg->method_depth);
11880 g_hash_table_destroy (acfg->plt_offset_to_entry);
11881 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11882 if (acfg->patch_to_plt_entry [i])
11883 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11885 g_free (acfg->patch_to_plt_entry);
11886 g_hash_table_destroy (acfg->method_to_cfg);
11887 g_hash_table_destroy (acfg->token_info_hash);
11888 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11889 g_hash_table_destroy (acfg->image_hash);
11890 g_hash_table_destroy (acfg->unwind_info_offsets);
11891 g_hash_table_destroy (acfg->method_label_hash);
11892 if (acfg->typespec_classes)
11893 g_hash_table_destroy (acfg->typespec_classes);
11894 g_hash_table_destroy (acfg->export_names);
11895 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11896 g_hash_table_destroy (acfg->klass_blob_hash);
11897 g_hash_table_destroy (acfg->method_blob_hash);
11898 got_info_free (&acfg->got_info);
11899 got_info_free (&acfg->llvm_got_info);
11900 arch_free_unwind_info_section_cache (acfg);
11901 mono_mempool_destroy (acfg->mempool);
11902 g_free (acfg);
11905 #define WRAPPER(e,n) n,
11906 static const char* const
11907 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11908 #include "mono/metadata/wrapper-types.h"
11909 NULL
11912 static G_GNUC_UNUSED const char*
11913 get_wrapper_type_name (int type)
11915 return wrapper_type_names [type];
11918 //#define DUMP_PLT
11919 //#define DUMP_GOT
11921 static void aot_dump (MonoAotCompile *acfg)
11923 FILE *dumpfile;
11924 char * dumpname;
11926 JsonWriter writer;
11927 mono_json_writer_init (&writer);
11929 mono_json_writer_object_begin(&writer);
11931 // Methods
11932 mono_json_writer_indent (&writer);
11933 mono_json_writer_object_key(&writer, "methods");
11934 mono_json_writer_array_begin (&writer);
11936 int i;
11937 for (i = 0; i < acfg->nmethods; ++i) {
11938 MonoCompile *cfg;
11939 MonoMethod *method;
11940 MonoClass *klass;
11942 cfg = acfg->cfgs [i];
11943 if (ignore_cfg (cfg))
11944 continue;
11946 method = cfg->orig_method;
11948 mono_json_writer_indent (&writer);
11949 mono_json_writer_object_begin(&writer);
11951 mono_json_writer_indent (&writer);
11952 mono_json_writer_object_key(&writer, "name");
11953 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11955 mono_json_writer_indent (&writer);
11956 mono_json_writer_object_key(&writer, "signature");
11957 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11959 mono_json_writer_indent (&writer);
11960 mono_json_writer_object_key(&writer, "code_size");
11961 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11963 klass = method->klass;
11965 mono_json_writer_indent (&writer);
11966 mono_json_writer_object_key(&writer, "class");
11967 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
11969 mono_json_writer_indent (&writer);
11970 mono_json_writer_object_key(&writer, "namespace");
11971 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
11973 mono_json_writer_indent (&writer);
11974 mono_json_writer_object_key(&writer, "wrapper_type");
11975 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11977 mono_json_writer_indent_pop (&writer);
11978 mono_json_writer_indent (&writer);
11979 mono_json_writer_object_end (&writer);
11980 mono_json_writer_printf (&writer, ",\n");
11983 mono_json_writer_indent_pop (&writer);
11984 mono_json_writer_indent (&writer);
11985 mono_json_writer_array_end (&writer);
11986 mono_json_writer_printf (&writer, ",\n");
11988 // PLT entries
11989 #ifdef DUMP_PLT
11990 mono_json_writer_indent_push (&writer);
11991 mono_json_writer_indent (&writer);
11992 mono_json_writer_object_key(&writer, "plt");
11993 mono_json_writer_array_begin (&writer);
11995 for (i = 0; i < acfg->plt_offset; ++i) {
11996 MonoPltEntry *plt_entry = NULL;
11997 MonoJumpInfo *ji;
11999 if (i == 0)
12001 * The first plt entry is unused.
12003 continue;
12005 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12006 ji = plt_entry->ji;
12008 mono_json_writer_indent (&writer);
12009 mono_json_writer_printf (&writer, "{ ");
12010 mono_json_writer_object_key(&writer, "symbol");
12011 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12014 mono_json_writer_indent_pop (&writer);
12015 mono_json_writer_indent (&writer);
12016 mono_json_writer_array_end (&writer);
12017 mono_json_writer_printf (&writer, ",\n");
12018 #endif
12020 // GOT entries
12021 #ifdef DUMP_GOT
12022 mono_json_writer_indent_push (&writer);
12023 mono_json_writer_indent (&writer);
12024 mono_json_writer_object_key(&writer, "got");
12025 mono_json_writer_array_begin (&writer);
12027 mono_json_writer_indent_push (&writer);
12028 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12029 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12031 mono_json_writer_indent (&writer);
12032 mono_json_writer_printf (&writer, "{ ");
12033 mono_json_writer_object_key(&writer, "patch_name");
12034 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12037 mono_json_writer_indent_pop (&writer);
12038 mono_json_writer_indent (&writer);
12039 mono_json_writer_array_end (&writer);
12040 mono_json_writer_printf (&writer, ",\n");
12041 #endif
12043 mono_json_writer_indent_pop (&writer);
12044 mono_json_writer_indent (&writer);
12045 mono_json_writer_object_end (&writer);
12047 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12048 dumpfile = fopen (dumpname, "w+");
12049 g_free (dumpname);
12051 fprintf (dumpfile, "%s", writer.text->str);
12052 fclose (dumpfile);
12054 mono_json_writer_destroy (&writer);
12057 static const char *preinited_jit_icalls[] = {
12058 "mono_aot_init_llvm_method",
12059 "mono_aot_init_gshared_method_this",
12060 "mono_aot_init_gshared_method_mrgctx",
12061 "mono_aot_init_gshared_method_vtable",
12062 "mono_llvm_throw_corlib_exception",
12063 "mono_init_vtable_slot",
12064 "mono_helper_ldstr_mscorlib"
12067 static void
12068 add_preinit_got_slots (MonoAotCompile *acfg)
12070 MonoJumpInfo *ji;
12071 int i;
12074 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12075 * during method initialization etc.
12078 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12079 ji->type = MONO_PATCH_INFO_IMAGE;
12080 ji->data.image = acfg->image;
12081 get_got_offset (acfg, FALSE, ji);
12082 get_got_offset (acfg, TRUE, ji);
12084 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12085 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12086 get_got_offset (acfg, FALSE, ji);
12087 get_got_offset (acfg, TRUE, ji);
12089 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12090 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12091 get_got_offset (acfg, FALSE, ji);
12092 get_got_offset (acfg, TRUE, ji);
12094 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12095 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12096 get_got_offset (acfg, FALSE, ji);
12097 get_got_offset (acfg, TRUE, ji);
12099 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12100 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12101 get_got_offset (acfg, FALSE, ji);
12102 get_got_offset (acfg, TRUE, ji);
12104 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12105 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12106 get_got_offset (acfg, FALSE, ji);
12107 get_got_offset (acfg, TRUE, ji);
12109 for (i = 0; i < TLS_KEY_NUM; i++) {
12110 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12111 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12112 ji->data.index = i;
12113 get_got_offset (acfg, FALSE, ji);
12114 get_got_offset (acfg, TRUE, ji);
12116 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12117 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12118 ji->data.index = i;
12119 get_got_offset (acfg, FALSE, ji);
12120 get_got_offset (acfg, TRUE, ji);
12123 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12124 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
12125 get_got_offset (acfg, FALSE, ji);
12126 get_got_offset (acfg, TRUE, ji);
12128 /* Called by native-to-managed wrappers on possibly unattached threads */
12129 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12130 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12131 ji->data.name = "mono_threads_attach_coop";
12132 get_got_offset (acfg, FALSE, ji);
12133 get_got_offset (acfg, TRUE, ji);
12135 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
12136 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12137 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
12138 ji->data.name = preinited_jit_icalls [i];
12139 get_got_offset (acfg, FALSE, ji);
12140 get_got_offset (acfg, TRUE, ji);
12143 acfg->nshared_got_entries = acfg->got_offset;
12146 static void
12147 mono_dedup_log_stats (MonoAotCompile *acfg)
12149 GHashTableIter iter;
12150 g_assert (acfg->dedup_stats);
12152 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12153 // deduped modules
12154 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12155 MonoCompile *dcfg = NULL;
12156 MonoMethod *method = NULL;
12158 size_t wrappers_size_saved = 0;
12159 size_t inflated_size_saved = 0;
12160 size_t copied_singles = 0;
12162 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12163 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12164 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12166 if (count == 0)
12167 continue;
12169 if (acfg->dedup_emit_mode) {
12170 // Size *saved* is the size due to things not emitted.
12171 if (count < 2) {
12172 // Just moved, didn't save space / dedup
12173 copied_singles += dcfg->code_len;
12174 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12175 wrappers_size_saved += dcfg->code_len * (count - 1);
12176 } else {
12177 inflated_size_saved += dcfg->code_len * (count - 1);
12180 if (acfg->aot_opts.dedup) {
12181 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12182 wrappers_size_saved += dcfg->code_len * count;
12183 } else {
12184 inflated_size_saved += dcfg->code_len * count;
12189 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%zu bytes\n", wrappers_size_saved);
12190 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%zu bytes\n", inflated_size_saved);
12191 if (acfg->dedup_emit_mode)
12192 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%zu bytes\n", copied_singles);
12194 g_hash_table_destroy (acfg->dedup_stats);
12195 acfg->dedup_stats = NULL;
12198 // Flush the cache to tell future calls what to skip
12199 static void
12200 mono_flush_method_cache (MonoAotCompile *acfg)
12202 GHashTable *method_cache = acfg->dedup_cache;
12203 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12204 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12205 g_free (filename);
12206 return;
12209 acfg->dedup_cache = NULL;
12211 FILE *cache = fopen (filename, "w");
12213 if (!cache)
12214 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12216 GHashTableIter iter;
12217 gchar *name = NULL;
12218 g_hash_table_iter_init (&iter, method_cache);
12219 gboolean cont = TRUE;
12220 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12221 int res = fprintf (cache, "%s\n", name);
12222 cont = res >= 0;
12224 // FIXME: don't assert if error when flushing
12225 g_assert (cont);
12227 fclose (cache);
12228 g_free (filename);
12230 // The keys are all in the imageset, nothing to free
12231 // Values are just pointers to memory owned elsewhere, or sentinels
12232 g_hash_table_destroy (method_cache);
12235 // Read in what has been emitted by previous invocations,
12236 // what can be skipped
12237 static void
12238 mono_read_method_cache (MonoAotCompile *acfg)
12240 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12241 // Only do once, when dedup_cache is null
12242 if (acfg->dedup_cache)
12243 goto early_exit;
12245 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
12246 g_assert (acfg->dedup_stats);
12248 // only in skip mode
12249 if (!acfg->aot_opts.dedup)
12250 goto early_exit;
12252 g_assert (acfg->dedup_cache);
12254 FILE *cache = fopen (filename, "r");
12255 if (!cache)
12256 goto early_exit;
12258 // Since we do pointer comparisons, and it can't be allocated at
12259 // the address 0x1 due to alignment, we use this as a sentinel
12260 gpointer other_acfg_sentinel = GINT_TO_POINTER (0x1);
12262 if (fseek (cache, 0L, SEEK_END))
12263 goto cleanup;
12265 size_t fileLength = ftell (cache);
12266 g_assert (fileLength > 0);
12268 if (fseek (cache, 0L, SEEK_SET))
12269 goto cleanup;
12271 // Avoid thousands of new malloc entries
12272 // FIXME: allocate into imageset, so we don't need to free.
12273 // put the other mangled names there too.
12274 char *bulk = g_malloc0 (fileLength * sizeof (char));
12275 size_t offset = 0;
12277 while (fgets (&bulk [offset], fileLength - offset, cache)) {
12278 // strip newline
12279 char *line = &bulk [offset];
12280 size_t len = strlen (line);
12281 if (len == 0)
12282 break;
12284 if (len >= 0 && line [len] == '\n')
12285 line [len] = '\0';
12286 offset += strlen (line) + 1;
12287 g_assert (fileLength >= offset);
12289 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
12292 cleanup:
12293 fclose (cache);
12295 early_exit:
12296 g_free (filename);
12297 return;
12300 typedef struct {
12301 GHashTable *cache;
12302 GHashTable *stats;
12303 gboolean emit_inflated_methods;
12304 MonoAssembly *inflated_assembly;
12305 } MonoAotState;
12307 static MonoAotState *
12308 alloc_aot_state (void)
12310 MonoAotState *state = g_malloc (sizeof (MonoAotState));
12311 // FIXME: Should this own the memory?
12312 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
12313 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
12314 // Start in "collect mode"
12315 state->emit_inflated_methods = FALSE;
12316 state->inflated_assembly = NULL;
12317 return state;
12320 static void
12321 free_aot_state (MonoAotState *astate)
12323 g_hash_table_destroy (astate->cache);
12324 g_free (astate);
12327 static void
12328 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
12330 GHashTableIter iter;
12331 gchar *name = NULL;
12332 MonoMethod *method = NULL;
12334 acfg->dedup_emit_mode = TRUE;
12336 g_hash_table_iter_init (&iter, astate->cache);
12337 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
12338 add_method_full (acfg, method, TRUE, 0);
12340 return;
12343 static void
12344 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
12346 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
12347 return;
12349 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
12350 // Thread the state through when making the inflate pass
12351 *astate = *global_aot_state;
12354 if (!*astate) {
12355 *astate = alloc_aot_state ();
12356 *global_aot_state = *astate;
12359 acfg->dedup_cache = (*astate)->cache;
12360 acfg->dedup_stats = (*astate)->stats;
12362 // fills out acfg->dedup_cache
12363 if (acfg->aot_opts.dedup)
12364 mono_read_method_cache (acfg);
12366 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
12367 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
12368 gchar *asm_file = NULL;
12370 // Get the last part of the path, the filename
12371 for (int i=0; asm_path [i] != NULL; i++)
12372 asm_file = asm_path [i];
12374 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
12375 // Save
12376 *is_dedup_dummy = TRUE;
12377 (*astate)->inflated_assembly = ass;
12379 g_strfreev (asm_path);
12380 } else if ((*astate)->inflated_assembly) {
12381 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
12385 int
12386 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12388 // create assembly, loop and add extra_methods
12389 // in add_generic_instances , rip out what's in that for loop
12390 // and apply that to this aot_state inside of mono_compile_assembly
12391 MonoAotState *astate;
12392 astate = *(MonoAotState **)aot_state;
12393 g_assert (astate);
12395 // FIXME: allow suffixes?
12396 if (!astate->inflated_assembly) {
12397 char *inflate = strstr (aot_options, "dedup-inflate");
12398 if (!inflate)
12399 return 0;
12400 else
12401 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
12404 // Switch modes
12405 astate->emit_inflated_methods = TRUE;
12407 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
12409 *aot_state = NULL;
12410 free_aot_state (astate);
12412 return res;
12415 static const char* interp_in_static_sigs[] = {
12416 "bool ptr int32 ptr&",
12417 "bool ptr ptr&",
12418 "int32 int32 ptr&",
12419 "int32 int32 ptr ptr&",
12420 "int32 ptr int32 ptr",
12421 "int32 ptr int32 ptr&",
12422 "int32 ptr ptr&",
12423 "object object ptr ptr ptr",
12424 "object",
12425 "ptr int32 ptr&",
12426 "ptr ptr int32 ptr ptr ptr&",
12427 "ptr ptr int32 ptr ptr&",
12428 "ptr ptr int32 ptr&",
12429 "ptr ptr ptr int32 ptr&",
12430 "ptr ptr ptr ptr& ptr&",
12431 "ptr ptr ptr ptr ptr&",
12432 "ptr ptr ptr ptr&",
12433 "ptr ptr ptr&",
12434 "ptr ptr uint32 ptr&",
12435 "ptr uint32 ptr&",
12436 "void object ptr ptr ptr",
12437 "void ptr ptr int32 ptr ptr& ptr ptr&",
12438 "void ptr ptr int32 ptr ptr&",
12439 "void ptr ptr ptr&",
12440 "void ptr ptr&",
12441 "void ptr",
12442 "void int32 ptr&",
12443 "void uint32 ptr&",
12444 "void"
12448 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
12450 MonoImage *image = ass->image;
12451 int i, res;
12452 gint64 all_sizes;
12453 MonoAotCompile *acfg;
12454 char *outfile_name, *tmp_outfile_name, *p;
12455 char llvm_stats_msg [256];
12456 TV_DECLARE (atv);
12457 TV_DECLARE (btv);
12459 acfg = acfg_create (ass, opts);
12461 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
12462 acfg->aot_opts.write_symbols = TRUE;
12463 acfg->aot_opts.ntrampolines = 4096;
12464 acfg->aot_opts.nrgctx_trampolines = 4096;
12465 acfg->aot_opts.nimt_trampolines = 512;
12466 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
12467 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
12468 acfg->aot_opts.llvm_path = g_strdup ("");
12469 acfg->aot_opts.temp_path = g_strdup ("");
12470 #ifdef MONOTOUCH
12471 acfg->aot_opts.use_trampolines_page = TRUE;
12472 #endif
12474 mono_aot_parse_options (aot_options, &acfg->aot_opts);
12476 // start dedup
12477 MonoAotState *astate = NULL;
12478 gboolean is_dedup_dummy = FALSE;
12479 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
12481 // Process later
12482 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
12483 return 0;
12485 // end dedup
12487 if (acfg->aot_opts.logfile) {
12488 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
12491 if (acfg->aot_opts.data_outfile) {
12492 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
12493 if (!acfg->data_outfile) {
12494 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
12495 return 1;
12497 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
12500 //acfg->aot_opts.print_skipped_methods = TRUE;
12502 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
12503 if (acfg->opts & MONO_OPT_GSHAREDVT) {
12504 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
12505 return 1;
12507 if (acfg->aot_opts.llvm_only) {
12508 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
12509 return 1;
12511 #else
12512 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12513 acfg->opts |= MONO_OPT_GSHAREDVT;
12514 #endif
12516 #if !defined(ENABLE_LLVM)
12517 if (acfg->aot_opts.llvm_only) {
12518 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
12519 return 1;
12521 #endif
12523 if (acfg->opts & MONO_OPT_GSHAREDVT)
12524 mono_set_generic_sharing_vt_supported (TRUE);
12526 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
12528 generate_aotid ((guint8*) &acfg->image->aotid);
12530 char *aotid = mono_guid_to_string (acfg->image->aotid);
12531 aot_printf (acfg, "AOTID %s\n", aotid);
12532 g_free (aotid);
12534 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
12535 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12536 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
12537 return 1;
12539 #endif
12541 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
12542 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
12543 return 1;
12546 if (acfg->aot_opts.static_link)
12547 acfg->aot_opts.asm_writer = TRUE;
12549 if (acfg->aot_opts.soft_debug) {
12550 MonoDebugOptions *opt = mini_get_debug_options ();
12552 opt->mdb_optimizations = TRUE;
12553 opt->gen_sdb_seq_points = TRUE;
12555 if (!mono_debug_enabled ()) {
12556 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
12557 return 1;
12559 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
12562 if (mono_use_llvm || acfg->aot_opts.llvm) {
12563 acfg->llvm = TRUE;
12564 acfg->aot_opts.asm_writer = TRUE;
12565 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
12567 if (acfg->aot_opts.soft_debug) {
12568 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
12569 return 1;
12572 mini_llvm_init ();
12574 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
12575 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
12576 return 1;
12580 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12581 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
12582 acfg->is_full_aot = TRUE;
12585 if (mono_threads_are_safepoints_enabled ())
12586 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
12588 // The methods in dedup-emit amodules must be available on runtime startup
12589 // Note: Only one such amodule can have this attribute
12590 if (astate && astate->emit_inflated_methods)
12591 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
12594 if (acfg->aot_opts.instances_logfile_path) {
12595 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
12596 if (!acfg->instances_logfile) {
12597 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
12598 return 1;
12602 if (acfg->aot_opts.profile_files) {
12603 GList *l;
12605 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
12606 load_profile_file (acfg, (char*)l->data);
12610 if (!(acfg->aot_opts.interp && !mono_aot_mode_is_full (&acfg->aot_opts))) {
12611 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
12612 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
12615 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
12616 #ifdef MONO_ARCH_GSHARED_SUPPORTED
12617 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
12618 #endif
12619 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
12620 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
12621 if (acfg->opts & MONO_OPT_GSHAREDVT)
12622 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
12623 #endif
12625 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
12627 arch_init (acfg);
12629 if (mono_use_llvm || acfg->aot_opts.llvm) {
12631 * Emit all LLVM code into a separate assembly/object file and link with it
12632 * normally.
12634 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
12635 acfg->llvm_owriter = TRUE;
12636 } else if (acfg->aot_opts.llvm_outfile) {
12637 int len = strlen (acfg->aot_opts.llvm_outfile);
12639 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
12640 acfg->llvm_owriter = TRUE;
12644 if (acfg->llvm && acfg->thumb_mixed)
12645 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
12646 if (acfg->aot_opts.llvm_only)
12647 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
12649 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
12650 /* Get rid of characters which cannot occur in symbols */
12651 for (p = acfg->assembly_name_sym; *p; ++p) {
12652 if (!(isalnum (*p) || *p == '_'))
12653 *p = '_';
12656 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
12657 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
12658 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
12659 if (acfg->llvm) {
12660 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
12661 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
12664 acfg->method_index = 1;
12666 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12667 mono_set_partial_sharing_supported (TRUE);
12669 if (!(acfg->aot_opts.interp && !mono_aot_mode_is_full (&acfg->aot_opts))) {
12670 res = collect_methods (acfg);
12671 if (!res)
12672 return 1;
12675 // If we're emitting all of the inflated methods into a dummy
12676 // Assembly, then after extra_methods is set up, we're done
12677 // in this function.
12678 if (astate && astate->emit_inflated_methods)
12679 mono_add_deferred_extra_methods (acfg, astate);
12682 GList *l;
12684 for (l = acfg->profile_data; l; l = l->next)
12685 resolve_profile_data (acfg, (ProfileData*)l->data);
12686 for (l = acfg->profile_data; l; l = l->next)
12687 add_profile_instances (acfg, (ProfileData*)l->data);
12690 acfg->cfgs_size = acfg->methods->len + 32;
12691 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
12693 /* PLT offset 0 is reserved for the PLT trampoline */
12694 acfg->plt_offset = 1;
12695 add_preinit_got_slots (acfg);
12697 #ifdef ENABLE_LLVM
12698 if (acfg->llvm) {
12699 llvm_acfg = acfg;
12700 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
12702 #endif
12704 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
12705 for (int i = 0; i < sizeof (interp_in_static_sigs) / sizeof (const char *); i++) {
12706 MonoMethodSignature *sig = mono_create_icall_signature (interp_in_static_sigs [i]);
12707 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
12708 sig->pinvoke = FALSE;
12709 MonoMethod *wrapper = mini_get_interp_in_wrapper (sig);
12710 add_method (acfg, wrapper);
12714 TV_GETTIME (atv);
12716 compile_methods (acfg);
12718 TV_GETTIME (btv);
12720 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
12722 TV_GETTIME (atv);
12724 #ifdef ENABLE_LLVM
12725 if (acfg->llvm) {
12726 if (acfg->aot_opts.asm_only) {
12727 if (acfg->aot_opts.outfile) {
12728 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12729 acfg->tmpbasename = g_strdup (acfg->tmpfname);
12730 } else {
12731 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
12732 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12734 g_assert (acfg->aot_opts.llvm_outfile);
12735 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
12736 if (acfg->llvm_owriter)
12737 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
12738 else
12739 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
12740 } else {
12741 gchar *temp_path;
12742 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
12743 temp_path = g_strdup (acfg->aot_opts.temp_path);
12744 } else {
12745 temp_path = mkdtemp(g_strdup ("mono_aot_XXXXXX"));
12746 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
12749 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
12750 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12751 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
12752 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
12754 g_free (temp_path);
12757 #endif
12759 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
12760 if (acfg->aot_opts.outfile)
12761 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12762 else
12763 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
12764 acfg->fp = fopen (acfg->tmpfname, "w+");
12765 } else {
12766 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
12767 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
12768 acfg->fp = fdopen (i, "w+");
12769 } else {
12770 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
12771 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12772 acfg->fp = fopen (acfg->tmpfname, "w+");
12775 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
12776 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
12777 return 1;
12779 if (acfg->fp)
12780 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
12782 tmp_outfile_name = NULL;
12783 outfile_name = NULL;
12785 /* Compute symbols for methods */
12786 for (i = 0; i < acfg->nmethods; ++i) {
12787 if (acfg->cfgs [i]) {
12788 MonoCompile *cfg = acfg->cfgs [i];
12789 int method_index = get_method_index (acfg, cfg->orig_method);
12791 if (COMPILE_LLVM (cfg))
12792 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
12793 else if (acfg->global_symbols || acfg->llvm)
12794 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
12795 else
12796 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
12797 cfg->asm_debug_symbol = cfg->asm_symbol;
12801 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
12803 * CLANG supports GAS .file/.loc directives, so emit line number information this way
12805 acfg->gas_line_numbers = TRUE;
12808 #ifdef EMIT_DWARF_INFO
12809 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
12810 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
12811 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
12812 return 1;
12814 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
12816 #endif /* EMIT_DWARF_INFO */
12818 if (acfg->w)
12819 mono_img_writer_emit_start (acfg->w);
12821 if (acfg->dwarf)
12822 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
12824 emit_code (acfg);
12825 if (acfg->aot_opts.dedup)
12826 mono_flush_method_cache (acfg);
12827 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
12828 mono_dedup_log_stats (acfg);
12830 emit_info (acfg);
12832 emit_extra_methods (acfg);
12834 if (acfg->aot_opts.dedup_include && !is_dedup_dummy) {
12835 fclose (acfg->fp);
12836 return 0;
12839 emit_trampolines (acfg);
12841 emit_class_name_table (acfg);
12843 emit_got_info (acfg, FALSE);
12844 if (acfg->llvm)
12845 emit_got_info (acfg, TRUE);
12847 emit_exception_info (acfg);
12849 emit_unwind_info (acfg);
12851 emit_class_info (acfg);
12853 emit_plt (acfg);
12855 emit_image_table (acfg);
12857 emit_weak_field_indexes (acfg);
12859 emit_got (acfg);
12863 * The managed allocators are GC specific, so can't use an AOT image created by one GC
12864 * in another.
12866 const char *gc_name = mono_gc_get_gc_name ();
12867 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
12870 emit_blob (acfg);
12872 emit_objc_selectors (acfg);
12874 emit_globals (acfg);
12876 emit_file_info (acfg);
12878 emit_library_info (acfg);
12880 if (acfg->dwarf) {
12881 emit_dwarf_info (acfg);
12882 mono_dwarf_writer_close (acfg->dwarf);
12883 } else {
12884 if (!acfg->aot_opts.nodebug)
12885 emit_codeview_info (acfg);
12888 emit_mem_end (acfg);
12890 if (acfg->need_pt_gnu_stack) {
12891 /* This is required so the .so doesn't have an executable stack */
12892 /* The bin writer already emits this */
12893 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
12896 if (acfg->aot_opts.data_outfile)
12897 fclose (acfg->data_outfile);
12899 #ifdef ENABLE_LLVM
12900 if (acfg->llvm) {
12901 gboolean res;
12903 res = emit_llvm_file (acfg);
12904 if (!res)
12905 return 1;
12907 #endif
12909 TV_GETTIME (btv);
12911 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
12913 if (acfg->llvm)
12914 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
12915 else
12916 strcpy (llvm_stats_msg, "");
12918 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;
12920 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",
12921 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
12922 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
12923 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
12924 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
12925 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
12926 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,
12927 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
12928 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
12929 (int)(acfg->got_offset * sizeof (gpointer)));
12930 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
12931 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
12932 llvm_stats_msg,
12933 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
12934 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
12935 if (acfg->stats.genericcount)
12936 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
12937 if (acfg->stats.abscount)
12938 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
12939 if (acfg->stats.lmfcount)
12940 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
12941 if (acfg->stats.ocount)
12942 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
12944 TV_GETTIME (atv);
12945 if (acfg->w) {
12946 res = mono_img_writer_emit_writeout (acfg->w);
12947 if (res != 0) {
12948 acfg_free (acfg);
12949 return res;
12951 res = compile_asm (acfg);
12952 if (res != 0) {
12953 acfg_free (acfg);
12954 return res;
12957 TV_GETTIME (btv);
12958 acfg->stats.link_time = TV_ELAPSED (atv, btv);
12960 if (acfg->aot_opts.stats) {
12961 int i;
12963 aot_printf (acfg, "GOT slot distribution:\n");
12964 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12965 if (acfg->stats.got_slot_types [i])
12966 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]);
12967 aot_printf (acfg, "\nMethod stats:\n");
12968 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
12969 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
12970 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
12971 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
12974 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);
12976 if (acfg->aot_opts.dump_json)
12977 aot_dump (acfg);
12979 acfg_free (acfg);
12981 return 0;
12984 #else
12986 /* AOT disabled */
12988 void*
12989 mono_aot_readonly_field_override (MonoClassField *field)
12991 return NULL;
12995 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
12997 return 0;
13000 gboolean
13001 mono_aot_is_shared_got_offset (int offset)
13003 return FALSE;
13007 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13009 g_assert_not_reached ();
13010 return 0;
13013 #endif