[wasm] Switch to the LLVM wasm backend. (#14734)
[mono-project.git] / mono / mini / aot-compiler.c
blob42ae68960df9a4127c7f8e310478d720bc4f23c3
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 static MonoMethod*
73 try_get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
75 MonoMethod *result;
76 ERROR_DECL (error);
77 result = mono_class_get_method_from_name_checked (klass, method_name, param_count, flags, error);
78 mono_error_assert_ok (error);
79 return result;
82 static MonoMethod*
83 get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
85 MonoMethod *result = try_get_method_nofail (klass, method_name, param_count, flags);
86 g_assertf (result, "Expected to find method %s in klass %s", method_name, m_class_get_name (klass));
87 return result;
90 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
92 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
93 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
94 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
95 #define TARGET_X86_64_WIN32_MSVC
96 #endif
98 #if defined(TARGET_X86_64_WIN32_MSVC)
99 #define TARGET_WIN32_MSVC
100 #endif
102 // Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
103 // works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
104 // compiling for AMD64 (Windows x64 platforms).
105 #if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
106 #define EMIT_WIN32_UNWIND_INFO
107 #endif
109 #if defined(__linux__)
110 #define RODATA_SECT ".rodata"
111 #elif defined(TARGET_MACH)
112 #define RODATA_SECT ".section __TEXT, __const"
113 #elif defined(TARGET_WIN32_MSVC)
114 #define RODATA_SECT ".rdata"
115 #else
116 #define RODATA_SECT ".text"
117 #endif
119 #define TV_DECLARE(name) gint64 name
120 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
121 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
123 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
125 typedef struct {
126 char *name;
127 MonoImage *image;
128 } ImageProfileData;
130 typedef struct ClassProfileData ClassProfileData;
132 typedef struct {
133 int argc;
134 ClassProfileData **argv;
135 MonoGenericInst *inst;
136 } GInstProfileData;
138 struct ClassProfileData {
139 ImageProfileData *image;
140 char *ns, *name;
141 GInstProfileData *inst;
142 MonoClass *klass;
145 typedef struct {
146 ClassProfileData *klass;
147 int id;
148 char *name;
149 int param_count;
150 char *signature;
151 GInstProfileData *inst;
152 MonoMethod *method;
153 } MethodProfileData;
155 typedef struct {
156 GHashTable *images, *classes, *ginsts, *methods;
157 } ProfileData;
159 /* predefined values for static readonly fields without needed to run the .cctor */
160 typedef struct _ReadOnlyValue ReadOnlyValue;
161 struct _ReadOnlyValue {
162 ReadOnlyValue *next;
163 char *name;
164 int type; /* to be used later for typechecking to prevent user errors */
165 union {
166 guint8 i1;
167 guint16 i2;
168 guint32 i4;
169 guint64 i8;
170 gpointer ptr;
171 } value;
173 static ReadOnlyValue *readonly_values;
175 typedef struct MonoAotOptions {
176 char *outfile;
177 char *llvm_outfile;
178 char *data_outfile;
179 GList *profile_files;
180 gboolean save_temps;
181 gboolean write_symbols;
182 gboolean metadata_only;
183 gboolean bind_to_runtime_version;
184 MonoAotMode mode;
185 gboolean interp;
186 gboolean no_dlsym;
187 gboolean static_link;
188 gboolean asm_only;
189 gboolean asm_writer;
190 gboolean nodebug;
191 gboolean dwarf_debug;
192 gboolean soft_debug;
193 gboolean log_generics;
194 gboolean log_instances;
195 gboolean gen_msym_dir;
196 char *gen_msym_dir_path;
197 gboolean direct_pinvoke;
198 gboolean direct_icalls;
199 gboolean no_direct_calls;
200 gboolean use_trampolines_page;
201 gboolean no_instances;
202 // We are collecting inflated methods and emitting non-inflated
203 gboolean dedup;
204 // The name of the assembly for which the AOT module is going to have all deduped methods moved to.
205 // When set, we are emitting inflated methods only
206 char *dedup_include;
207 gboolean gnu_asm;
208 gboolean try_llvm;
209 gboolean llvm;
210 gboolean llvm_only;
211 gboolean llvm_disable_self_init;
212 int nthreads;
213 int ntrampolines;
214 int nrgctx_trampolines;
215 int nimt_trampolines;
216 int ngsharedvt_arg_trampolines;
217 int nftnptr_arg_trampolines;
218 int nrgctx_fetch_trampolines;
219 int nunbox_arbitrary_trampolines;
220 gboolean print_skipped_methods;
221 gboolean stats;
222 gboolean verbose;
223 gboolean deterministic;
224 char *tool_prefix;
225 char *ld_flags;
226 char *mtriple;
227 char *llvm_path;
228 char *temp_path;
229 char *instances_logfile_path;
230 char *logfile;
231 char *llvm_opts;
232 char *llvm_llc;
233 gboolean dump_json;
234 gboolean profile_only;
235 gboolean no_opt;
236 char *clangxx;
237 char *depfile;
238 } MonoAotOptions;
240 typedef enum {
241 METHOD_CAT_NORMAL,
242 METHOD_CAT_GSHAREDVT,
243 METHOD_CAT_INST,
244 METHOD_CAT_WRAPPER,
245 METHOD_CAT_NUM
246 } MethodCategory;
248 typedef struct MonoAotStats {
249 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
250 gint64 code_size, method_info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size, blob_size;
251 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
252 int got_slots, offsets_size;
253 int method_categories [METHOD_CAT_NUM];
254 int got_slot_types [MONO_PATCH_INFO_NUM];
255 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
256 int jit_time, gen_time, link_time;
257 int method_ref_count, method_ref_size;
258 int class_ref_count, class_ref_size;
259 int ginst_count, ginst_size;
260 } MonoAotStats;
262 typedef struct GotInfo {
263 GHashTable *patch_to_got_offset;
264 GHashTable **patch_to_got_offset_by_type;
265 GPtrArray *got_patches;
266 } GotInfo;
268 #ifdef EMIT_WIN32_UNWIND_INFO
269 typedef struct _UnwindInfoSectionCacheItem {
270 char *xdata_section_label;
271 PUNWIND_INFO unwind_info;
272 gboolean xdata_section_emitted;
273 } UnwindInfoSectionCacheItem;
274 #endif
276 typedef struct MonoAotCompile {
277 MonoImage *image;
278 GPtrArray *methods;
279 GHashTable *method_indexes;
280 GHashTable *method_depth;
281 MonoCompile **cfgs;
282 int cfgs_size;
283 GHashTable **patch_to_plt_entry;
284 GHashTable *plt_offset_to_entry;
285 //GHashTable *patch_to_got_offset;
286 //GHashTable **patch_to_got_offset_by_type;
287 //GPtrArray *got_patches;
288 GotInfo got_info, llvm_got_info;
289 GHashTable *image_hash;
290 GHashTable *method_to_cfg;
291 GHashTable *token_info_hash;
292 GHashTable *method_to_pinvoke_import;
293 GHashTable *method_to_external_icall_symbol_name;
294 GPtrArray *extra_methods;
295 GPtrArray *image_table;
296 GPtrArray *globals;
297 GPtrArray *method_order;
298 GHashTable *dedup_stats;
299 GHashTable *dedup_cache;
300 gboolean dedup_cache_changed;
301 GHashTable *export_names;
302 /* Maps MonoClass* -> blob offset */
303 GHashTable *klass_blob_hash;
304 /* Maps MonoMethod* -> blob offset */
305 GHashTable *method_blob_hash;
306 /* Maps MonoGenericInst* -> blob offset */
307 GHashTable *ginst_blob_hash;
308 GHashTable *gsharedvt_in_signatures;
309 GHashTable *gsharedvt_out_signatures;
310 guint32 *plt_got_info_offsets;
311 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
312 /* Number of GOT entries reserved for trampolines */
313 guint32 num_trampoline_got_entries;
314 guint32 tramp_page_size;
316 guint32 table_offsets [MONO_AOT_TABLE_NUM];
317 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
318 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
319 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
320 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
322 MonoAotOptions aot_opts;
323 guint32 nmethods;
324 guint32 nextra_methods;
325 guint32 opts;
326 guint32 simd_opts;
327 MonoMemPool *mempool;
328 MonoAotStats stats;
329 int method_index;
330 char *static_linking_symbol;
331 mono_mutex_t mutex;
332 gboolean gas_line_numbers;
333 /* Whenever to emit an object file directly from llc */
334 gboolean llvm_owriter;
335 gboolean llvm_owriter_supported;
336 MonoImageWriter *w;
337 MonoDwarfWriter *dwarf;
338 FILE *fp;
339 char *tmpbasename;
340 char *tmpfname;
341 char *temp_dir_to_delete;
342 char *llvm_sfile;
343 char *llvm_ofile;
344 GSList *cie_program;
345 GHashTable *unwind_info_offsets;
346 GPtrArray *unwind_ops;
347 guint32 unwind_info_offset;
348 char *global_prefix;
349 char *got_symbol;
350 char *llvm_got_symbol;
351 char *plt_symbol;
352 char *llvm_eh_frame_symbol;
353 GHashTable *method_label_hash;
354 const char *temp_prefix;
355 const char *user_symbol_prefix;
356 const char *llvm_label_prefix;
357 const char *inst_directive;
358 int align_pad_value;
359 guint32 label_generator;
360 gboolean llvm;
361 gboolean has_jitted_code;
362 gboolean is_full_aot;
363 gboolean dedup_collect_only;
364 MonoAotFileFlags flags;
365 MonoDynamicStream blob;
366 gboolean blob_closed;
367 GHashTable *typespec_classes;
368 GString *llc_args;
369 GString *as_args;
370 char *assembly_name_sym;
371 GHashTable *plt_entry_debug_sym_cache;
372 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
373 GHashTable *ginst_hash;
374 GHashTable *dwarf_ln_filenames;
375 gboolean global_symbols;
376 int objc_selector_index, objc_selector_index_2;
377 GPtrArray *objc_selectors;
378 GHashTable *objc_selector_to_index;
379 GList *profile_data;
380 GHashTable *profile_methods;
381 #ifdef EMIT_WIN32_UNWIND_INFO
382 GList *unwind_info_section_cache;
383 #endif
384 FILE *logfile;
385 FILE *instances_logfile;
386 FILE *data_outfile;
387 int datafile_offset;
388 int gc_name_offset;
389 // In this mode, we are emitting dedupable methods that we encounter
390 gboolean dedup_emit_mode;
391 } MonoAotCompile;
393 typedef struct {
394 int plt_offset;
395 char *symbol, *llvm_symbol, *debug_sym;
396 MonoJumpInfo *ji;
397 gboolean jit_used, llvm_used;
398 } MonoPltEntry;
400 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
401 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
403 /* This points to the current acfg in LLVM mode */
404 static MonoAotCompile *llvm_acfg;
406 /* Cache of decoded method external icall symbol names. */
407 /* Owned by acfg, but kept in this static as well since it is */
408 /* accessed by code paths not having access to acfg. */
409 static GHashTable *method_to_external_icall_symbol_name;
411 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
412 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
413 #define MSGSTRFIELD1(line) str##line
414 static const struct msgstr_t {
415 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
416 #include "patch-info.h"
417 #undef PATCH_INFO
418 } opstr = {
419 #define PATCH_INFO(a,b) b,
420 #include "patch-info.h"
421 #undef PATCH_INFO
423 static const gint16 opidx [] = {
424 #define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
425 #include "patch-info.h"
426 #undef PATCH_INFO
429 static G_GNUC_UNUSED const char*
430 get_patch_name (int info)
432 return (const char*)&opstr + opidx [info];
435 static int
436 emit_aot_image (MonoAotCompile *acfg);
438 static void
439 mono_flush_method_cache (MonoAotCompile *acfg);
441 static void
442 mono_read_method_cache (MonoAotCompile *acfg);
444 static guint32
445 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
447 static char*
448 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
450 static void
451 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
453 static void
454 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
456 static inline gboolean
457 ignore_cfg (MonoCompile *cfg)
459 return !cfg || cfg->skip;
462 static void
463 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
465 FILE *output;
466 va_list args;
468 if (acfg->logfile)
469 output = acfg->logfile;
470 else
471 output = stdout;
473 va_start (args, format);
474 vfprintf (output, format, args);
475 va_end (args);
478 static void
479 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
481 FILE *output;
482 va_list args;
484 if (acfg->logfile)
485 output = acfg->logfile;
486 else
487 output = stderr;
489 va_start (args, format);
490 vfprintf (output, format, args);
491 va_end (args);
494 static void
495 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
497 FILE *output;
498 va_list args;
500 if (mono_error_ok (error))
501 return;
503 if (acfg->logfile)
504 output = acfg->logfile;
505 else
506 output = stderr;
508 va_start (args, format);
509 vfprintf (output, format, args);
510 va_end (args);
511 mono_error_cleanup (error);
513 if (acfg->is_full_aot && fatal) {
514 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
515 exit (1);
519 /* Wrappers around the image writer functions */
521 #define MAX_SYMBOL_SIZE 256
523 static inline const char *
524 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
526 gsize needed_size = length;
528 g_assert (NULL != symbol);
529 g_assert (NULL != mangled_symbol);
530 g_assert (0 != length);
532 #if defined(TARGET_WIN32) && defined(TARGET_X86)
533 if (symbol && '_' != symbol [0]) {
534 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
535 } else {
536 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
538 #else
539 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
540 #endif
542 g_assert (0 <= needed_size && needed_size < length);
543 return mangled_symbol;
546 static inline char *
547 mangle_symbol_alloc (const char * symbol)
549 g_assert (NULL != symbol);
551 #if defined(TARGET_WIN32) && defined(TARGET_X86)
552 if (symbol && '_' != symbol [0]) {
553 return g_strdup_printf ("_%s", symbol);
555 else {
556 return g_strdup_printf ("%s", symbol);
558 #else
559 return g_strdup_printf ("%s", symbol);
560 #endif
563 static inline void
564 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
566 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
569 #if defined(TARGET_WIN32) && defined(TARGET_X86)
571 static inline void
572 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
574 const char * mangled_symbol_name = name;
575 char * mangled_symbol_name_alloc = NULL;
577 if (TRUE == func) {
578 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
579 mangled_symbol_name = mangled_symbol_name_alloc;
582 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
583 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
585 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
587 if (NULL != mangled_symbol_name_alloc) {
588 g_free (mangled_symbol_name_alloc);
592 #else
594 static inline void
595 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
597 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
600 #endif
602 static inline void
603 emit_label (MonoAotCompile *acfg, const char *name)
605 mono_img_writer_emit_label (acfg->w, name);
608 static inline void
609 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
611 mono_img_writer_emit_bytes (acfg->w, buf, size);
614 static inline void
615 emit_string (MonoAotCompile *acfg, const char *value)
617 mono_img_writer_emit_string (acfg->w, value);
620 static inline void
621 emit_line (MonoAotCompile *acfg)
623 mono_img_writer_emit_line (acfg->w);
626 static inline void
627 emit_alignment (MonoAotCompile *acfg, int size)
629 mono_img_writer_emit_alignment (acfg->w, size);
632 static inline void
633 emit_alignment_code (MonoAotCompile *acfg, int size)
635 if (acfg->align_pad_value)
636 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
637 else
638 mono_img_writer_emit_alignment (acfg->w, size);
641 static inline void
642 emit_padding (MonoAotCompile *acfg, int size)
644 int i;
645 guint8 buf [16];
647 if (acfg->align_pad_value) {
648 for (i = 0; i < 16; ++i)
649 buf [i] = acfg->align_pad_value;
650 } else {
651 memset (buf, 0, sizeof (buf));
654 for (i = 0; i < size; i += 16) {
655 if (size - i < 16)
656 emit_bytes (acfg, buf, size - i);
657 else
658 emit_bytes (acfg, buf, 16);
662 static inline void
663 emit_pointer (MonoAotCompile *acfg, const char *target)
665 mono_img_writer_emit_pointer (acfg->w, target);
668 static inline void
669 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
671 if (prefix [0] != '\0') {
672 char *s = g_strdup_printf ("%s%s", prefix, target);
673 mono_img_writer_emit_pointer (acfg->w, s);
674 g_free (s);
675 } else {
676 mono_img_writer_emit_pointer (acfg->w, target);
680 static inline void
681 emit_int16 (MonoAotCompile *acfg, int value)
683 mono_img_writer_emit_int16 (acfg->w, value);
686 static inline void
687 emit_int32 (MonoAotCompile *acfg, int value)
689 mono_img_writer_emit_int32 (acfg->w, value);
692 static inline void
693 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
695 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
698 static inline void
699 emit_zero_bytes (MonoAotCompile *acfg, int num)
701 mono_img_writer_emit_zero_bytes (acfg->w, num);
704 static inline void
705 emit_byte (MonoAotCompile *acfg, guint8 val)
707 mono_img_writer_emit_byte (acfg->w, val);
710 #if defined(TARGET_WIN32) && defined(TARGET_X86)
712 static G_GNUC_UNUSED void
713 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
715 const char * mangled_symbol_name = name;
716 char * mangled_symbol_name_alloc = NULL;
718 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
719 mangled_symbol_name = mangled_symbol_name_alloc;
721 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
722 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
724 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
726 if (NULL != mangled_symbol_name_alloc) {
727 g_free (mangled_symbol_name_alloc);
731 #else
733 static G_GNUC_UNUSED void
734 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
736 mono_img_writer_emit_global (acfg->w, name, func);
739 #endif
741 static inline gboolean
742 link_shared_library (MonoAotCompile *acfg)
744 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
747 static inline gboolean
748 add_to_global_symbol_table (MonoAotCompile *acfg)
750 #ifdef TARGET_WIN32_MSVC
751 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
752 #else
753 return acfg->aot_opts.no_dlsym;
754 #endif
757 static void
758 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
760 if (add_to_global_symbol_table (acfg))
761 g_ptr_array_add (acfg->globals, g_strdup (name));
763 if (acfg->aot_opts.no_dlsym) {
764 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
765 } else {
766 emit_global_inner (acfg, name, func);
770 static void
771 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
773 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
776 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
777 static void
778 emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
780 char symbol [MAX_SYMBOL_SIZE];
782 if (acfg->llvm) {
783 emit_label (acfg, name);
784 /* LLVM generated code references this */
785 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
786 emit_label (acfg, symbol);
788 #ifndef TARGET_WIN32_MSVC
789 emit_global_inner (acfg, symbol, FALSE);
790 #else
791 emit_global_inner (acfg, symbol, func);
792 #endif
793 } else {
794 emit_label (acfg, name);
798 static void
799 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
801 if (acfg->llvm) {
802 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
803 return;
806 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
807 #ifdef TARGET_MACH
808 /* On apple, all symbols need to be aligned to avoid warnings from ld */
809 emit_alignment (acfg, 4);
810 #endif
811 mono_img_writer_emit_label (acfg->w, name);
812 mono_img_writer_emit_string (acfg->w, value);
815 static G_GNUC_UNUSED void
816 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
818 do {
819 guint8 b = value & 0x7f;
820 value >>= 7;
821 if (value != 0) /* more bytes to come */
822 b |= 0x80;
823 emit_byte (acfg, b);
824 } while (value);
827 static G_GNUC_UNUSED void
828 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
830 gboolean more = 1;
831 gboolean negative = (value < 0);
832 guint32 size = 64;
833 guint8 byte;
835 while (more) {
836 byte = value & 0x7f;
837 value >>= 7;
838 /* the following is unnecessary if the
839 * implementation of >>= uses an arithmetic rather
840 * than logical shift for a signed left operand
842 if (negative)
843 /* sign extend */
844 value |= - ((gint64)1 <<(size - 7));
845 /* sign bit of byte is second high order bit (0x40) */
846 if ((value == 0 && !(byte & 0x40)) ||
847 (value == -1 && (byte & 0x40)))
848 more = 0;
849 else
850 byte |= 0x80;
851 emit_byte (acfg, byte);
855 static G_GNUC_UNUSED void
856 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
858 guint8 *p = buf;
860 do {
861 guint8 b = value & 0x7f;
862 value >>= 7;
863 if (value != 0) /* more bytes to come */
864 b |= 0x80;
865 *p ++ = b;
866 } while (value);
868 *endbuf = p;
871 static G_GNUC_UNUSED void
872 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
874 gboolean more = 1;
875 gboolean negative = (value < 0);
876 guint32 size = 32;
877 guint8 byte;
878 guint8 *p = buf;
880 while (more) {
881 byte = value & 0x7f;
882 value >>= 7;
883 /* the following is unnecessary if the
884 * implementation of >>= uses an arithmetic rather
885 * than logical shift for a signed left operand
887 if (negative)
888 /* sign extend */
889 value |= - (1 <<(size - 7));
890 /* sign bit of byte is second high order bit (0x40) */
891 if ((value == 0 && !(byte & 0x40)) ||
892 (value == -1 && (byte & 0x40)))
893 more = 0;
894 else
895 byte |= 0x80;
896 *p ++= byte;
899 *endbuf = p;
902 static void
903 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
905 // FIXME: Big-endian
906 buf [0] = (val >> 0) & 0xff;
907 buf [1] = (val >> 8) & 0xff;
908 buf [2] = (val >> 16) & 0xff;
909 buf [3] = (val >> 24) & 0xff;
911 *endbuf = buf + 4;
914 static void
915 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
917 buf [0] = (val >> 0) & 0xff;
918 buf [1] = (val >> 8) & 0xff;
920 *endbuf = buf + 2;
923 static void
924 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
926 int len = strlen (s);
928 memcpy (buf, s, len + 1);
929 *endbuf = buf + len + 1;
932 static void
933 emit_unset_mode (MonoAotCompile *acfg)
935 mono_img_writer_emit_unset_mode (acfg->w);
938 static G_GNUC_UNUSED void
939 emit_set_thumb_mode (MonoAotCompile *acfg)
941 emit_unset_mode (acfg);
942 fprintf (acfg->fp, ".code 16\n");
945 static G_GNUC_UNUSED void
946 emit_set_arm_mode (MonoAotCompile *acfg)
948 emit_unset_mode (acfg);
949 fprintf (acfg->fp, ".code 32\n");
952 static inline void
953 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
955 #ifdef TARGET_ARM64
956 int i;
958 g_assert (size % 4 == 0);
959 emit_unset_mode (acfg);
960 for (i = 0; i < size; i += 4)
961 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
962 #else
963 emit_bytes (acfg, buf, size);
964 #endif
967 /* ARCHITECTURE SPECIFIC CODE */
969 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
970 #define EMIT_DWARF_INFO 1
971 #endif
973 #ifdef TARGET_WIN32_MSVC
974 #undef EMIT_DWARF_INFO
975 #define EMIT_WIN32_CODEVIEW_INFO
976 #endif
978 #ifdef EMIT_WIN32_UNWIND_INFO
979 static UnwindInfoSectionCacheItem *
980 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
982 static void
983 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
985 static void
986 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
988 static void
989 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
990 #endif
992 static void
993 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
995 #ifdef EMIT_WIN32_UNWIND_INFO
996 free_unwind_info_section_cache_win32 (acfg);
997 #endif
1000 static void
1001 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
1003 #ifdef EMIT_WIN32_UNWIND_INFO
1004 gboolean own_unwind_ops = FALSE;
1005 if (!unwind_ops) {
1006 unwind_ops = mono_unwind_get_cie_program ();
1007 own_unwind_ops = TRUE;
1010 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
1012 if (own_unwind_ops)
1013 mono_free_unwind_info (unwind_ops);
1014 #endif
1017 #if defined(TARGET_ARM)
1018 #define AOT_FUNC_ALIGNMENT 4
1019 #else
1020 #define AOT_FUNC_ALIGNMENT 16
1021 #endif
1023 #if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
1024 #define PPC_LD_OP "ld"
1025 #define PPC_LDX_OP "ldx"
1026 #else
1027 #define PPC_LD_OP "lwz"
1028 #define PPC_LDX_OP "lwzx"
1029 #endif
1031 #ifdef TARGET_X86_64_WIN32_MSVC
1032 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
1033 #elif TARGET_AMD64
1034 #define AOT_TARGET_STR "AMD64"
1035 #endif
1037 #ifdef TARGET_ARM
1038 #ifdef TARGET_MACH
1039 #define AOT_TARGET_STR "ARM (MACH)"
1040 #else
1041 #define AOT_TARGET_STR "ARM (!MACH)"
1042 #endif
1043 #endif
1045 #ifdef TARGET_ARM64
1046 #ifdef TARGET_MACH
1047 #define AOT_TARGET_STR "ARM64 (MACH)"
1048 #else
1049 #define AOT_TARGET_STR "ARM64 (!MACH)"
1050 #endif
1051 #endif
1053 #ifdef TARGET_POWERPC64
1054 #ifdef MONO_ARCH_ILP32
1055 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1056 #else
1057 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1058 #endif
1059 #else
1060 #ifdef TARGET_POWERPC
1061 #ifdef MONO_ARCH_ILP32
1062 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1063 #else
1064 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1065 #endif
1066 #endif
1067 #endif
1069 #ifdef TARGET_RISCV32
1070 #define AOT_TARGET_STR "RISCV32"
1071 #endif
1073 #ifdef TARGET_RISCV64
1074 #define AOT_TARGET_STR "RISCV64"
1075 #endif
1077 #ifdef TARGET_X86
1078 #ifdef TARGET_WIN32
1079 #define AOT_TARGET_STR "X86 (WIN32)"
1080 #else
1081 #define AOT_TARGET_STR "X86"
1082 #endif
1083 #endif
1085 #ifndef AOT_TARGET_STR
1086 #define AOT_TARGET_STR ""
1087 #endif
1089 static void
1090 arch_init (MonoAotCompile *acfg)
1092 acfg->llc_args = g_string_new ("");
1093 acfg->as_args = g_string_new ("");
1094 acfg->llvm_owriter_supported = TRUE;
1097 * The prefix LLVM likes to put in front of symbol names on darwin.
1098 * The mach-os specs require this for globals, but LLVM puts them in front of all
1099 * symbols. We need to handle this, since we need to refer to LLVM generated
1100 * symbols.
1102 acfg->llvm_label_prefix = "";
1103 acfg->user_symbol_prefix = "";
1105 #if TARGET_X86 || TARGET_AMD64
1106 const gboolean has_custom_args = !!acfg->aot_opts.llvm_llc;
1107 #endif
1109 #if defined(TARGET_X86)
1110 g_string_append_printf (acfg->llc_args, " -march=x86 %s", has_custom_args ? "" : "-mcpu=generic");
1111 #endif
1113 #if defined(TARGET_AMD64)
1114 g_string_append_printf (acfg->llc_args, " -march=x86-64 %s", has_custom_args ? "" : "-mcpu=generic");
1115 /* NOP */
1116 acfg->align_pad_value = 0x90;
1117 #endif
1119 #ifdef TARGET_ARM
1120 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1121 g_string_append (acfg->llc_args, "-mattr=+v6");
1122 } else {
1123 if (!(acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb")))
1124 g_string_append (acfg->llc_args, " -march=arm");
1126 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "ios"))
1127 g_string_append (acfg->llc_args, " -mattr=+v7");
1129 #if defined(ARM_FPU_VFP_HARD)
1130 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1131 g_string_append (acfg->as_args, " -mfpu=vfp3");
1132 #elif defined(ARM_FPU_VFP)
1133 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1134 g_string_append (acfg->as_args, " -mfpu=vfp3");
1135 #else
1136 #ifdef LLVM_API_VERSION > 100
1137 g_string_append (acfg->llc_args, " -mattr=+soft-float");
1138 #else
1139 g_string_append (acfg->llc_args, " -soft-float");
1140 #endif
1141 #endif
1143 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1144 acfg->thumb_mixed = TRUE;
1146 if (acfg->aot_opts.mtriple)
1147 mono_arch_set_target (acfg->aot_opts.mtriple);
1148 #endif
1150 #ifdef TARGET_ARM64
1151 g_string_append (acfg->llc_args, " -march=aarch64");
1152 acfg->inst_directive = ".inst";
1153 if (acfg->aot_opts.mtriple)
1154 mono_arch_set_target (acfg->aot_opts.mtriple);
1155 #endif
1157 #ifdef TARGET_MACH
1158 acfg->user_symbol_prefix = "_";
1159 acfg->llvm_label_prefix = "_";
1160 acfg->inst_directive = ".word";
1161 acfg->need_no_dead_strip = TRUE;
1162 acfg->aot_opts.gnu_asm = TRUE;
1163 #endif
1165 #if defined(__linux__) && !defined(TARGET_ARM)
1166 acfg->need_pt_gnu_stack = TRUE;
1167 #endif
1169 #ifdef TARGET_RISCV
1170 if (acfg->aot_opts.mtriple)
1171 mono_arch_set_target (acfg->aot_opts.mtriple);
1173 #ifdef TARGET_RISCV64
1175 g_string_append (acfg->as_args, " -march=rv64i ");
1176 #ifdef RISCV_FPABI_DOUBLE
1177 g_string_append (acfg->as_args, " -mabi=lp64d");
1178 #else
1179 g_string_append (acfg->as_args, " -mabi=lp64");
1180 #endif
1182 #else
1184 g_string_append (acfg->as_args, " -march=rv32i ");
1185 #ifdef RISCV_FPABI_DOUBLE
1186 g_string_append (acfg->as_args, " -mabi=ilp32d ");
1187 #else
1188 g_string_append (acfg->as_args, " -mabi=ilp32 ");
1189 #endif
1191 #endif
1193 #endif
1195 #ifdef MONOTOUCH
1196 acfg->global_symbols = TRUE;
1197 #endif
1199 #ifdef TARGET_ANDROID
1200 acfg->llvm_owriter_supported = FALSE;
1201 #endif
1204 #ifdef TARGET_ARM64
1207 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1208 static void
1209 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1211 int offset;
1213 g_assert (acfg->fp);
1214 emit_unset_mode (acfg);
1215 /* r16==ip0 */
1216 offset = (int)(got_slot * sizeof (target_mgreg_t));
1217 #ifdef TARGET_MACH
1218 /* clang's integrated assembler */
1219 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1220 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1221 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1222 #else
1223 /* Linux GAS */
1224 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1225 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1226 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1227 #endif
1230 static void
1231 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1233 int reg;
1235 g_assert (acfg->fp);
1236 emit_unset_mode (acfg);
1238 /* ldr rt, target */
1239 reg = arm_get_ldr_lit_reg (code);
1241 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1242 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1243 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1245 *code_size = 12;
1248 static void
1249 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1251 g_assert (acfg->fp);
1252 emit_unset_mode (acfg);
1253 if (ji && ji->relocation == MONO_R_ARM64_B) {
1254 fprintf (acfg->fp, "b %s\n", target);
1255 } else {
1256 if (ji)
1257 g_assert (ji->relocation == MONO_R_ARM64_BL);
1258 fprintf (acfg->fp, "bl %s\n", target);
1260 *call_size = 4;
1263 static void
1264 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1266 int reg;
1268 /* ldr rt, target */
1269 reg = arm_get_ldr_lit_reg (code);
1270 arm64_emit_load_got_slot (acfg, reg, got_slot);
1271 *code_size = 12;
1274 static void
1275 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1277 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
1278 fprintf (acfg->fp, "br x16\n");
1279 /* Used by mono_aot_get_plt_info_offset () */
1280 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1283 static void
1284 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1286 guint8 buf [256];
1287 guint8 *code;
1288 int imm;
1290 /* The common code */
1291 code = buf;
1292 imm = pagesize;
1293 /* The trampoline address is in IP0 */
1294 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1295 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1296 /* Compute the data slot address */
1297 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1298 /* Trampoline argument */
1299 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1300 /* Address */
1301 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1302 arm_brx (code, ARMREG_IP0);
1304 /* Emit it */
1305 emit_code_bytes (acfg, buf, code - buf);
1307 *size = code - buf;
1310 static void
1311 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1313 guint8 buf [256];
1314 guint8 *code;
1315 int i, count;
1317 count = (pagesize - common_tramp_size) / specific_tramp_size;
1318 for (i = 0; i < count; ++i) {
1319 code = buf;
1320 arm_adrx (code, ARMREG_IP0, code);
1321 /* Branch to the generic code */
1322 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1323 /* This has to be 2 pointers long */
1324 arm_nop (code);
1325 arm_nop (code);
1326 g_assert (code - buf == specific_tramp_size);
1327 emit_code_bytes (acfg, buf, code - buf);
1331 static void
1332 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1334 guint8 buf [128];
1335 guint8 *code;
1336 guint8 *labels [16];
1337 int common_tramp_size;
1338 int specific_tramp_size = 2 * 8;
1339 int imm, pagesize;
1340 char symbol [128];
1342 if (!acfg->aot_opts.use_trampolines_page)
1343 return;
1345 #ifdef TARGET_MACH
1346 /* Have to match the target pagesize */
1347 pagesize = 16384;
1348 #else
1349 pagesize = mono_pagesize ();
1350 #endif
1351 acfg->tramp_page_size = pagesize;
1353 /* The specific trampolines */
1354 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1355 emit_alignment (acfg, pagesize);
1356 emit_global (acfg, symbol, TRUE);
1357 emit_label (acfg, symbol);
1359 /* The common code */
1360 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1361 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1363 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1365 /* The rgctx trampolines */
1366 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1367 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1368 emit_alignment (acfg, pagesize);
1369 emit_global (acfg, symbol, TRUE);
1370 emit_label (acfg, symbol);
1372 /* The common code */
1373 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1374 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1376 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1378 /* The gsharedvt arg trampolines */
1379 /* These are the same as the specific trampolines */
1380 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1381 emit_alignment (acfg, pagesize);
1382 emit_global (acfg, symbol, TRUE);
1383 emit_label (acfg, symbol);
1385 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1386 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1388 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1390 /* Unbox arbitrary trampolines */
1391 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1392 emit_alignment (acfg, pagesize);
1393 emit_global (acfg, symbol, TRUE);
1394 emit_label (acfg, symbol);
1396 code = buf;
1397 imm = pagesize;
1399 /* Unbox this arg */
1400 arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1402 /* The trampoline address is in IP0 */
1403 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1404 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1405 /* Compute the data slot address */
1406 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1407 /* Address */
1408 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1409 arm_brx (code, ARMREG_IP0);
1411 /* Emit it */
1412 emit_code_bytes (acfg, buf, code - buf);
1414 common_tramp_size = code - buf;
1415 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
1417 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1419 /* The IMT trampolines */
1420 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1421 emit_alignment (acfg, pagesize);
1422 emit_global (acfg, symbol, TRUE);
1423 emit_label (acfg, symbol);
1425 code = buf;
1426 imm = pagesize;
1427 /* The trampoline address is in IP0 */
1428 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1429 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1430 /* Compute the data slot address */
1431 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1432 /* Trampoline argument */
1433 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1435 /* Same as arch_emit_imt_trampoline () */
1436 labels [0] = code;
1437 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1438 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1439 labels [1] = code;
1440 arm_bcc (code, ARMCOND_EQ, 0);
1442 /* End-of-loop check */
1443 labels [2] = code;
1444 arm_cbzx (code, ARMREG_IP0, 0);
1446 /* Loop footer */
1447 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1448 arm_b (code, labels [0]);
1450 /* Match */
1451 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1452 /* Load vtable slot addr */
1453 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1454 /* Load vtable slot */
1455 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1456 arm_brx (code, ARMREG_IP0);
1458 /* No match */
1459 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1460 /* Load fail addr */
1461 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1462 arm_brx (code, ARMREG_IP0);
1464 emit_code_bytes (acfg, buf, code - buf);
1466 common_tramp_size = code - buf;
1467 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1469 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1472 static void
1473 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1475 /* Load argument from second GOT slot */
1476 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1477 /* Load generic trampoline address from first GOT slot */
1478 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1479 fprintf (acfg->fp, "br x16\n");
1480 *tramp_size = 7 * 4;
1483 static void
1484 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1486 emit_unset_mode (acfg);
1487 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
1488 fprintf (acfg->fp, "b %s\n", call_target);
1491 static void
1492 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1494 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1496 /* Load argument from first GOT slot */
1497 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1498 /* Load generic trampoline address from second GOT slot */
1499 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1500 fprintf (acfg->fp, "br x16\n");
1501 *tramp_size = 7 * 4;
1504 static void
1505 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1507 guint8 buf [128];
1508 guint8 *code, *labels [16];
1510 /* Load parameter from GOT slot into ip1 */
1511 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1513 code = buf;
1514 labels [0] = code;
1515 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1516 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1517 labels [1] = code;
1518 arm_bcc (code, ARMCOND_EQ, 0);
1520 /* End-of-loop check */
1521 labels [2] = code;
1522 arm_cbzx (code, ARMREG_IP0, 0);
1524 /* Loop footer */
1525 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1526 arm_b (code, labels [0]);
1528 /* Match */
1529 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1530 /* Load vtable slot addr */
1531 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1532 /* Load vtable slot */
1533 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1534 arm_brx (code, ARMREG_IP0);
1536 /* No match */
1537 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1538 /* Load fail addr */
1539 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1540 arm_brx (code, ARMREG_IP0);
1542 emit_code_bytes (acfg, buf, code - buf);
1544 *tramp_size = code - buf + (3 * 4);
1547 static void
1548 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1550 /* Similar to the specific trampolines, but the address is in the second slot */
1551 /* Load argument from first GOT slot */
1552 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1553 /* Load generic trampoline address from second GOT slot */
1554 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1555 fprintf (acfg->fp, "br x16\n");
1556 *tramp_size = 7 * 4;
1560 #endif
1562 #ifdef MONO_ARCH_AOT_SUPPORTED
1564 * arch_emit_direct_call:
1566 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1567 * calling code.
1569 static void
1570 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1572 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1573 /* Need to make sure this is exactly 5 bytes long */
1574 emit_unset_mode (acfg);
1575 fprintf (acfg->fp, "call %s\n", target);
1576 *call_size = 5;
1577 #elif defined(TARGET_ARM)
1578 emit_unset_mode (acfg);
1579 if (thumb)
1580 fprintf (acfg->fp, "blx %s\n", target);
1581 else
1582 fprintf (acfg->fp, "bl %s\n", target);
1583 *call_size = 4;
1584 #elif defined(TARGET_ARM64)
1585 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1586 #elif defined(TARGET_POWERPC)
1587 emit_unset_mode (acfg);
1588 fprintf (acfg->fp, "bl %s\n", target);
1589 *call_size = 4;
1590 #else
1591 g_assert_not_reached ();
1592 #endif
1595 static void
1596 arch_emit_label_address (MonoAotCompile *acfg, const char *target, gboolean external_call, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1598 #if defined(TARGET_ARM) && defined(TARGET_ANDROID)
1599 /* binutils ld does not support branch islands on arm32 */
1600 if (!thumb) {
1601 emit_unset_mode (acfg);
1602 fprintf (acfg->fp, "ldr pc,=%s\n", target);
1603 fprintf (acfg->fp, ".ltorg\n");
1604 *call_size = 8;
1605 } else
1606 #endif
1607 arch_emit_direct_call (acfg, target, external_call, thumb, ji, call_size);
1609 #endif
1612 * PPC32 design:
1613 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1614 * the GOT pointer.
1615 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1616 * in in the 2. slot of every GOT, and require every method to place the GOT
1617 * address in r30, even when it doesn't access the GOT otherwise. This way,
1618 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1622 * PPC64 design:
1623 * PPC64 uses function descriptors which greatly complicate all code, since
1624 * these are used very inconsistently in the runtime. Some functions like
1625 * mono_compile_method () return ftn descriptors, while others like the
1626 * trampoline creation functions do not.
1627 * We assume that all GOT slots contain function descriptors, and create
1628 * descriptors in aot-runtime.c when needed.
1629 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1630 * from function descriptors, we could do the same, but it would require
1631 * rewriting all the ppc/aot code to handle function descriptors properly.
1632 * So instead, we use the same approach as on PPC32.
1633 * This is a horrible mess, but fixing it would probably lead to an even bigger
1634 * one.
1638 * X86 design:
1639 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1642 #ifdef MONO_ARCH_AOT_SUPPORTED
1644 * arch_emit_got_offset:
1646 * The memory pointed to by CODE should hold native code for computing the GOT
1647 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1648 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1650 static void
1651 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1653 #if defined(TARGET_POWERPC64)
1654 emit_unset_mode (acfg);
1656 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1657 * unsupported relocations. So we store the got address into the .Lgot_addr
1658 * symbol which is in the text segment, compute its address, and load it.
1660 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1661 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1662 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1663 fprintf (acfg->fp, "add 30, 30, 0\n");
1664 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1665 acfg->label_generator ++;
1666 *code_size = 16;
1667 #elif defined(TARGET_POWERPC)
1668 emit_unset_mode (acfg);
1669 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1670 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1671 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1672 acfg->label_generator ++;
1673 *code_size = 8;
1674 #else
1675 guint32 offset = mono_arch_get_patch_offset (code);
1676 emit_bytes (acfg, code, offset);
1677 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1679 *code_size = offset + 4;
1680 #endif
1684 * arch_emit_got_access:
1686 * The memory pointed to by CODE should hold native code for loading a GOT
1687 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1688 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1690 static void
1691 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1693 #ifdef TARGET_AMD64
1694 /* mov reg, got+offset(%rip) */
1695 if (acfg->llvm) {
1696 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1697 int dreg;
1698 int rex_r;
1700 /* Decode reg, see amd64_mov_reg_membase () */
1701 rex_r = code [0] & AMD64_REX_R;
1702 g_assert (code [0] == 0x49 + rex_r);
1703 g_assert (code [1] == 0x8b);
1704 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1706 emit_unset_mode (acfg);
1707 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
1708 *code_size = 7;
1709 } else {
1710 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1711 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
1712 *code_size = mono_arch_get_patch_offset (code) + 4;
1714 #elif defined(TARGET_X86)
1715 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1716 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
1717 *code_size = mono_arch_get_patch_offset (code) + 4;
1718 #elif defined(TARGET_ARM)
1719 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1720 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
1721 *code_size = mono_arch_get_patch_offset (code) + 4;
1722 #elif defined(TARGET_ARM64)
1723 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1724 arm64_emit_got_access (acfg, code, got_slot, code_size);
1725 #elif defined(TARGET_POWERPC)
1727 guint8 buf [32];
1729 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1730 code = buf;
1731 ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
1732 g_assert (code - buf == 8);
1733 emit_bytes (acfg, buf, code - buf);
1734 *code_size = code - buf;
1736 #else
1737 g_assert_not_reached ();
1738 #endif
1741 #endif
1743 #ifdef MONO_ARCH_AOT_SUPPORTED
1745 * arch_emit_objc_selector_ref:
1747 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1749 static void
1750 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1752 #if defined(TARGET_ARM)
1753 char symbol1 [MAX_SYMBOL_SIZE];
1754 char symbol2 [MAX_SYMBOL_SIZE];
1755 int lindex = acfg->objc_selector_index_2 ++;
1757 /* Emit ldr.imm/b */
1758 emit_bytes (acfg, code, 8);
1760 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1761 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1763 emit_label (acfg, symbol1);
1764 mono_img_writer_emit_unset_mode (acfg->w);
1765 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1767 *code_size = 12;
1768 #elif defined(TARGET_ARM64)
1769 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1770 #else
1771 g_assert_not_reached ();
1772 #endif
1774 #endif
1777 * arch_emit_plt_entry:
1779 * Emit code for the PLT entry.
1780 * The plt entry should look like this:
1781 * <indirect jump to GOT_SYMBOL + OFFSET>
1782 * <INFO_OFFSET embedded into the instruction stream>
1784 static void
1785 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1787 #if defined(TARGET_X86)
1788 /* jmp *<offset>(%ebx) */
1789 emit_byte (acfg, 0xff);
1790 emit_byte (acfg, 0xa3);
1791 emit_int32 (acfg, offset);
1792 /* Used by mono_aot_get_plt_info_offset */
1793 emit_int32 (acfg, info_offset);
1794 #elif defined(TARGET_AMD64)
1795 emit_unset_mode (acfg);
1796 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1797 /* Used by mono_aot_get_plt_info_offset */
1798 emit_int32 (acfg, info_offset);
1799 acfg->stats.plt_size += 10;
1800 #elif defined(TARGET_ARM)
1801 guint8 buf [256];
1802 guint8 *code;
1804 code = buf;
1805 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1806 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1807 emit_bytes (acfg, buf, code - buf);
1808 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1809 /* Used by mono_aot_get_plt_info_offset */
1810 emit_int32 (acfg, info_offset);
1811 #elif defined(TARGET_ARM64)
1812 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1813 #elif defined(TARGET_POWERPC)
1814 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1815 emit_unset_mode (acfg);
1816 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1817 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1818 fprintf (acfg->fp, "add 11, 11, 30\n");
1819 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1820 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1821 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
1822 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1823 #endif
1824 fprintf (acfg->fp, "mtctr 11\n");
1825 fprintf (acfg->fp, "bctr\n");
1826 emit_int32 (acfg, info_offset);
1827 #else
1828 g_assert_not_reached ();
1829 #endif
1833 * arch_emit_llvm_plt_entry:
1835 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1836 * This is only needed on arm to handle thumb interop.
1838 static void
1839 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1841 #if defined(TARGET_ARM)
1842 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1843 /* The caller already transitioned to thumb */
1844 /* The code below should be 12 bytes long */
1845 /* clang has trouble encoding these instructions, so emit the binary */
1846 #if 0
1847 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1848 /* thumb can't encode ld pc, [pc, ip] */
1849 fprintf (acfg->fp, "add ip, pc, ip\n");
1850 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1851 fprintf (acfg->fp, "bx ip\n");
1852 #endif
1853 emit_set_thumb_mode (acfg);
1854 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1855 fprintf (acfg->fp, ".2byte 0x44fc\n");
1856 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1857 fprintf (acfg->fp, ".2byte 0x4760\n");
1858 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1859 emit_int32 (acfg, info_offset);
1860 emit_unset_mode (acfg);
1861 emit_set_arm_mode (acfg);
1862 #else
1863 g_assert_not_reached ();
1864 #endif
1867 /* Save unwind_info in the module and emit the offset to the information at symbol */
1868 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1870 guint32 uw_offset, encoded_len;
1871 guint8 *encoded;
1873 emit_section_change (acfg, RODATA_SECT, 0);
1874 emit_global (acfg, symbol, FALSE);
1875 emit_label (acfg, symbol);
1877 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1878 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1879 g_free (encoded);
1880 emit_int32 (acfg, uw_offset);
1884 * arch_emit_specific_trampoline_pages:
1886 * Emits a page full of trampolines: each trampoline uses its own address to
1887 * lookup both the generic trampoline code and the data argument.
1888 * This page can be remapped in process multiple times so we can get an
1889 * unlimited number of trampolines.
1890 * Specifically this implementation uses the following trick: two memory pages
1891 * are allocated, with the first containing the data and the second containing the trampolines.
1892 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1893 * implementation does all the lifting.
1894 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1895 * on the arm 32 bit system.
1897 static void
1898 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1900 #if defined(TARGET_ARM)
1901 guint8 buf [128];
1902 guint8 *code;
1903 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1904 int i;
1905 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1906 GSList *unwind_ops = NULL;
1907 #define COMMON_TRAMP_SIZE 16
1908 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1909 int imm8, rot_amount;
1910 char symbol [128];
1912 if (!acfg->aot_opts.use_trampolines_page)
1913 return;
1915 acfg->tramp_page_size = pagesize;
1917 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1918 emit_alignment (acfg, pagesize);
1919 emit_global (acfg, symbol, TRUE);
1920 emit_label (acfg, symbol);
1922 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1923 code = buf;
1924 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1925 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1926 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1927 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1928 ARM_NOP (code);
1929 g_assert (code - buf == COMMON_TRAMP_SIZE);
1931 /* Emit it */
1932 emit_bytes (acfg, buf, code - buf);
1934 for (i = 0; i < count; ++i) {
1935 code = buf;
1936 ARM_PUSH (code, 0x5fff);
1937 ARM_BL (code, 0);
1938 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1939 g_assert (code - buf == 8);
1940 emit_bytes (acfg, buf, code - buf);
1943 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1944 * the instruction pointer address, so the generic trampoline at the start of the page
1945 * subtracts 4096 to get to the data page and loads the values
1946 * We again fit the generic trampiline in 16 bytes.
1948 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1949 emit_global (acfg, symbol, TRUE);
1950 emit_label (acfg, symbol);
1951 code = buf;
1952 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1953 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1954 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1955 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1956 ARM_NOP (code);
1957 g_assert (code - buf == COMMON_TRAMP_SIZE);
1959 /* Emit it */
1960 emit_bytes (acfg, buf, code - buf);
1962 for (i = 0; i < count; ++i) {
1963 code = buf;
1964 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1965 ARM_B (code, 0);
1966 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1967 g_assert (code - buf == 8);
1968 emit_bytes (acfg, buf, code - buf);
1972 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1974 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1975 emit_global (acfg, symbol, TRUE);
1976 emit_label (acfg, symbol);
1977 code = buf;
1978 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1979 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1980 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1981 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1982 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1983 g_assert (code - buf == COMMON_TRAMP_SIZE);
1984 /* Emit it */
1985 emit_bytes (acfg, buf, code - buf);
1987 for (i = 0; i < count; ++i) {
1988 code = buf;
1989 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1990 ARM_B (code, 0);
1991 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1992 g_assert (code - buf == 8);
1993 emit_bytes (acfg, buf, code - buf);
1996 /* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
1997 * the instruction pointer address, so the generic trampoline at the start of the page
1998 * subtracts 4096 to get to the data page and loads the target addr.
1999 * We again fit the generic trampoline in 16 bytes.
2001 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
2002 emit_global (acfg, symbol, TRUE);
2003 emit_label (acfg, symbol);
2004 code = buf;
2006 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2007 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2008 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2009 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
2010 ARM_NOP (code);
2011 g_assert (code - buf == COMMON_TRAMP_SIZE);
2013 /* Emit it */
2014 emit_bytes (acfg, buf, code - buf);
2016 for (i = 0; i < count; ++i) {
2017 code = buf;
2018 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2019 ARM_B (code, 0);
2020 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
2021 g_assert (code - buf == 8);
2022 emit_bytes (acfg, buf, code - buf);
2025 /* now the imt trampolines: each specific trampolines puts in the ip register
2026 * the instruction pointer address, so the generic trampoline at the start of the page
2027 * subtracts 4096 to get to the data page and loads the values
2029 #define IMT_TRAMP_SIZE 72
2030 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
2031 emit_global (acfg, symbol, TRUE);
2032 emit_label (acfg, symbol);
2033 code = buf;
2034 /* Need at least two free registers, plus a slot for storing the pc */
2035 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2037 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2038 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2039 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
2041 /* The IMT method is in v5, r0 has the imt array address */
2043 loop_start = code;
2044 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2045 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2046 imt_found_check = code;
2047 ARM_B_COND (code, ARMCOND_EQ, 0);
2049 /* End-of-loop check */
2050 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2051 loop_end_check = code;
2052 ARM_B_COND (code, ARMCOND_EQ, 0);
2054 /* Loop footer */
2055 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2056 loop_branch_back = code;
2057 ARM_B (code, 0);
2058 arm_patch (loop_branch_back, loop_start);
2060 /* Match */
2061 arm_patch (imt_found_check, code);
2062 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2063 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2064 /* Save it to the third stack slot */
2065 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2066 /* Restore the registers and branch */
2067 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2069 /* No match */
2070 arm_patch (loop_end_check, code);
2071 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2072 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2073 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2074 ARM_NOP (code);
2076 /* Emit it */
2077 g_assert (code - buf == IMT_TRAMP_SIZE);
2078 emit_bytes (acfg, buf, code - buf);
2080 for (i = 0; i < count; ++i) {
2081 code = buf;
2082 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2083 ARM_B (code, 0);
2084 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
2085 g_assert (code - buf == 8);
2086 emit_bytes (acfg, buf, code - buf);
2089 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
2090 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
2091 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
2092 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
2093 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
2095 /* Unwind info for specifc trampolines */
2096 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
2097 /* We unwind to the original caller, from the stack, since lr is clobbered */
2098 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
2099 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
2100 save_unwind_info (acfg, symbol, unwind_ops);
2101 mono_free_unwind_info (unwind_ops);
2103 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
2104 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2105 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (target_mgreg_t));
2106 save_unwind_info (acfg, symbol, unwind_ops);
2107 mono_free_unwind_info (unwind_ops);
2109 /* Unwind info for rgctx trampolines */
2110 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
2111 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2112 save_unwind_info (acfg, symbol, unwind_ops);
2114 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
2115 save_unwind_info (acfg, symbol, unwind_ops);
2116 mono_free_unwind_info (unwind_ops);
2118 /* Unwind info for gsharedvt trampolines */
2119 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2120 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2121 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
2122 save_unwind_info (acfg, symbol, unwind_ops);
2123 mono_free_unwind_info (unwind_ops);
2125 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2126 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2127 save_unwind_info (acfg, symbol, unwind_ops);
2128 mono_free_unwind_info (unwind_ops);
2130 /* Unwind info for unbox arbitrary trampolines */
2131 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
2132 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2133 save_unwind_info (acfg, symbol, unwind_ops);
2135 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
2136 save_unwind_info (acfg, symbol, unwind_ops);
2137 mono_free_unwind_info (unwind_ops);
2139 /* Unwind info for imt trampolines */
2140 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2141 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2142 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
2143 save_unwind_info (acfg, symbol, unwind_ops);
2144 mono_free_unwind_info (unwind_ops);
2146 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2147 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2148 save_unwind_info (acfg, symbol, unwind_ops);
2149 mono_free_unwind_info (unwind_ops);
2150 #elif defined(TARGET_ARM64)
2151 arm64_emit_specific_trampoline_pages (acfg);
2152 #endif
2156 * arch_emit_specific_trampoline:
2158 * Emit code for a specific trampoline. OFFSET is the offset of the first of
2159 * two GOT slots which contain the generic trampoline address and the trampoline
2160 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
2162 static void
2163 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2166 * The trampolines created here are variations of the specific
2167 * trampolines created in mono_arch_create_specific_trampoline (). The
2168 * differences are:
2169 * - the generic trampoline address is taken from a got slot.
2170 * - the offset of the got slot where the trampoline argument is stored
2171 * is embedded in the instruction stream, and the generic trampoline
2172 * can load the argument by loading the offset, adding it to the
2173 * address of the trampoline to get the address of the got slot, and
2174 * loading the argument from there.
2175 * - all the trampolines should be of the same length.
2177 #if defined(TARGET_AMD64)
2178 /* This should be exactly 8 bytes long */
2179 *tramp_size = 8;
2180 /* call *<offset>(%rip) */
2181 if (acfg->llvm) {
2182 emit_unset_mode (acfg);
2183 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2184 emit_zero_bytes (acfg, 2);
2185 } else {
2186 emit_byte (acfg, '\x41');
2187 emit_byte (acfg, '\xff');
2188 emit_byte (acfg, '\x15');
2189 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2190 emit_zero_bytes (acfg, 1);
2192 #elif defined(TARGET_ARM)
2193 guint8 buf [128];
2194 guint8 *code;
2196 /* This should be exactly 20 bytes long */
2197 *tramp_size = 20;
2198 code = buf;
2199 ARM_PUSH (code, 0x5fff);
2200 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2201 /* Load the value from the GOT */
2202 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2203 /* Branch to it */
2204 ARM_BLX_REG (code, ARMREG_R1);
2206 g_assert (code - buf == 16);
2208 /* Emit it */
2209 emit_bytes (acfg, buf, code - buf);
2211 * Only one offset is needed, since the second one would be equal to the
2212 * first one.
2214 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
2215 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
2216 #elif defined(TARGET_ARM64)
2217 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2218 #elif defined(TARGET_POWERPC)
2219 guint8 buf [128];
2220 guint8 *code;
2222 *tramp_size = 4;
2223 code = buf;
2226 * PPC has no ip relative addressing, so we need to compute the address
2227 * of the mscorlib got. That is slow and complex, so instead, we store it
2228 * in the second got slot of every aot image. The caller already computed
2229 * the address of its got and placed it into r30.
2231 emit_unset_mode (acfg);
2232 /* Load mscorlib got address */
2233 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2234 /* Load generic trampoline address */
2235 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2236 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2237 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2238 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2239 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2240 #endif
2241 fprintf (acfg->fp, "mtctr 11\n");
2242 /* Load trampoline argument */
2243 /* On ppc, we pass it normally to the generic trampoline */
2244 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2245 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2246 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2247 /* Branch to generic trampoline */
2248 fprintf (acfg->fp, "bctr\n");
2250 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2251 *tramp_size = 10 * 4;
2252 #else
2253 *tramp_size = 9 * 4;
2254 #endif
2255 #elif defined(TARGET_X86)
2256 guint8 buf [128];
2257 guint8 *code;
2259 /* Similar to the PPC code above */
2261 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2263 code = buf;
2264 /* Load mscorlib got address */
2265 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2266 /* Push trampoline argument */
2267 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2268 /* Load generic trampoline address */
2269 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2270 /* Branch to generic trampoline */
2271 x86_jump_reg (code, X86_ECX);
2273 emit_bytes (acfg, buf, code - buf);
2275 *tramp_size = 17;
2276 g_assert (code - buf == *tramp_size);
2277 #else
2278 g_assert_not_reached ();
2279 #endif
2283 * arch_emit_unbox_trampoline:
2285 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2286 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2288 * See mono_aot_get_unbox_trampoline.
2290 static void
2291 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2293 #if defined(TARGET_AMD64)
2294 guint8 buf [32];
2295 guint8 *code;
2296 int this_reg;
2298 this_reg = mono_arch_get_this_arg_reg (NULL);
2299 code = buf;
2300 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2302 emit_bytes (acfg, buf, code - buf);
2303 /* jump <method> */
2304 if (acfg->llvm) {
2305 emit_unset_mode (acfg);
2306 fprintf (acfg->fp, "jmp %s\n", call_target);
2307 } else {
2308 emit_byte (acfg, '\xe9');
2309 emit_symbol_diff (acfg, call_target, ".", -4);
2311 #elif defined(TARGET_X86)
2312 guint8 buf [32];
2313 guint8 *code;
2314 int this_pos = 4;
2316 code = buf;
2318 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
2320 emit_bytes (acfg, buf, code - buf);
2322 /* jump <method> */
2323 emit_byte (acfg, '\xe9');
2324 emit_symbol_diff (acfg, call_target, ".", -4);
2325 #elif defined(TARGET_ARM)
2326 guint8 buf [128];
2327 guint8 *code;
2329 if (acfg->thumb_mixed && cfg->compile_llvm) {
2330 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
2331 fprintf (acfg->fp, "b %s\n", call_target);
2332 fprintf (acfg->fp, ".arm\n");
2333 fprintf (acfg->fp, ".align 2\n");
2334 return;
2337 code = buf;
2339 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2341 emit_bytes (acfg, buf, code - buf);
2342 /* jump to method */
2343 if (acfg->thumb_mixed && cfg->compile_llvm)
2344 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2345 else
2346 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2347 #elif defined(TARGET_ARM64)
2348 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2349 #elif defined(TARGET_POWERPC)
2350 int this_pos = 3;
2352 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
2353 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2354 #else
2355 g_assert_not_reached ();
2356 #endif
2360 * arch_emit_static_rgctx_trampoline:
2362 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2363 * two GOT slots which contain the rgctx argument, and the method to jump to.
2364 * TRAMP_SIZE is set to the size of the emitted trampoline.
2365 * These kinds of trampolines cannot be enumerated statically, since there could
2366 * be one trampoline per method instantiation, so we emit the same code for all
2367 * trampolines, and parameterize them using two GOT slots.
2369 static void
2370 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2372 #if defined(TARGET_AMD64)
2373 /* This should be exactly 13 bytes long */
2374 *tramp_size = 13;
2376 if (acfg->llvm) {
2377 emit_unset_mode (acfg);
2378 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2379 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
2380 } else {
2381 /* mov <OFFSET>(%rip), %r10 */
2382 emit_byte (acfg, '\x4d');
2383 emit_byte (acfg, '\x8b');
2384 emit_byte (acfg, '\x15');
2385 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2387 /* jmp *<offset>(%rip) */
2388 emit_byte (acfg, '\xff');
2389 emit_byte (acfg, '\x25');
2390 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
2392 #elif defined(TARGET_ARM)
2393 guint8 buf [128];
2394 guint8 *code;
2396 /* This should be exactly 24 bytes long */
2397 *tramp_size = 24;
2398 code = buf;
2399 /* Load rgctx value */
2400 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2401 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2402 /* Load branch addr + branch */
2403 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2404 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2406 g_assert (code - buf == 16);
2408 /* Emit it */
2409 emit_bytes (acfg, buf, code - buf);
2410 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
2411 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
2412 #elif defined(TARGET_ARM64)
2413 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2414 #elif defined(TARGET_POWERPC)
2415 guint8 buf [128];
2416 guint8 *code;
2418 *tramp_size = 4;
2419 code = buf;
2422 * PPC has no ip relative addressing, so we need to compute the address
2423 * of the mscorlib got. That is slow and complex, so instead, we store it
2424 * in the second got slot of every aot image. The caller already computed
2425 * the address of its got and placed it into r30.
2427 emit_unset_mode (acfg);
2428 /* Load mscorlib got address */
2429 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2430 /* Load rgctx */
2431 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2432 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2433 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2434 /* Load target address */
2435 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2436 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2437 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2438 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2439 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2440 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2441 #endif
2442 fprintf (acfg->fp, "mtctr 11\n");
2443 /* Branch to the target address */
2444 fprintf (acfg->fp, "bctr\n");
2446 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2447 *tramp_size = 11 * 4;
2448 #else
2449 *tramp_size = 9 * 4;
2450 #endif
2452 #elif defined(TARGET_X86)
2453 guint8 buf [128];
2454 guint8 *code;
2456 /* Similar to the PPC code above */
2458 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2460 code = buf;
2461 /* Load mscorlib got address */
2462 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2463 /* Load arg */
2464 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2465 /* Branch to the target address */
2466 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2468 emit_bytes (acfg, buf, code - buf);
2470 *tramp_size = 15;
2471 g_assert (code - buf == *tramp_size);
2472 #else
2473 g_assert_not_reached ();
2474 #endif
2478 * arch_emit_imt_trampoline:
2480 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2481 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2482 * key is the IMT key, and ptr holds the address of a memory location holding
2483 * the address to branch to if the IMT arg matches the key. The array is
2484 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2485 * fail_tramp.
2486 * TRAMP_SIZE is set to the size of the emitted trampoline.
2488 static void
2489 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2491 #if defined(TARGET_AMD64)
2492 guint8 *buf, *code;
2493 guint8 *labels [16];
2494 guint8 mov_buf[3];
2495 guint8 *mov_buf_ptr = mov_buf;
2497 const int kSizeOfMove = 7;
2499 code = buf = (guint8 *)g_malloc (256);
2501 /* FIXME: Optimize this, i.e. use binary search etc. */
2502 /* Maybe move the body into a separate function (slower, but much smaller) */
2504 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2506 if (acfg->llvm) {
2507 emit_unset_mode (acfg);
2508 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2511 labels [0] = code;
2512 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2513 labels [1] = code;
2514 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2516 /* Check key */
2517 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
2518 labels [2] = code;
2519 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2521 /* Loop footer */
2522 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
2523 amd64_jump_code (code, labels [0]);
2525 /* Match */
2526 mono_amd64_patch (labels [2], code);
2527 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
2528 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2530 /* No match */
2531 mono_amd64_patch (labels [1], code);
2532 /* Load fail tramp */
2533 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
2534 /* Check if there is a fail tramp */
2535 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2536 labels [3] = code;
2537 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2538 /* Jump to fail tramp */
2539 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2541 /* Fail */
2542 mono_amd64_patch (labels [3], code);
2543 x86_breakpoint (code);
2545 if (!acfg->llvm) {
2546 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2547 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2548 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2549 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2550 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2551 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2553 emit_bytes (acfg, buf, code - buf);
2555 *tramp_size = code - buf + kSizeOfMove;
2557 g_free (buf);
2559 #elif defined(TARGET_X86)
2560 guint8 *buf, *code;
2561 guint8 *labels [16];
2563 code = buf = g_malloc (256);
2565 /* Allocate a temporary stack slot */
2566 x86_push_reg (code, X86_EAX);
2567 /* Save EAX */
2568 x86_push_reg (code, X86_EAX);
2570 /* Load mscorlib got address */
2571 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2572 /* Load arg */
2573 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
2575 labels [0] = code;
2576 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2577 labels [1] = code;
2578 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2580 /* Check key */
2581 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2582 labels [2] = code;
2583 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2585 /* Loop footer */
2586 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
2587 x86_jump_code (code, labels [0]);
2589 /* Match */
2590 mono_x86_patch (labels [2], code);
2591 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2592 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2593 /* Save the target address to the temporary stack location */
2594 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2595 /* Restore EAX */
2596 x86_pop_reg (code, X86_EAX);
2597 /* Jump to the target address */
2598 x86_ret (code);
2600 /* No match */
2601 mono_x86_patch (labels [1], code);
2602 /* Load fail tramp */
2603 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2604 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2605 labels [3] = code;
2606 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2607 /* Jump to fail tramp */
2608 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2609 x86_pop_reg (code, X86_EAX);
2610 x86_ret (code);
2612 /* Fail */
2613 mono_x86_patch (labels [3], code);
2614 x86_breakpoint (code);
2616 emit_bytes (acfg, buf, code - buf);
2618 *tramp_size = code - buf;
2620 g_free (buf);
2622 #elif defined(TARGET_ARM)
2623 guint8 buf [128];
2624 guint8 *code, *code2, *labels [16];
2626 code = buf;
2628 /* The IMT method is in v5 */
2630 /* Need at least two free registers, plus a slot for storing the pc */
2631 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2632 labels [0] = code;
2633 /* Load the parameter from the GOT */
2634 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2635 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2637 labels [1] = code;
2638 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2639 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2640 labels [2] = code;
2641 ARM_B_COND (code, ARMCOND_EQ, 0);
2643 /* End-of-loop check */
2644 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2645 labels [3] = code;
2646 ARM_B_COND (code, ARMCOND_EQ, 0);
2648 /* Loop footer */
2649 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2650 labels [4] = code;
2651 ARM_B (code, 0);
2652 arm_patch (labels [4], labels [1]);
2654 /* Match */
2655 arm_patch (labels [2], code);
2656 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2657 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2658 /* Save it to the third stack slot */
2659 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2660 /* Restore the registers and branch */
2661 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2663 /* No match */
2664 arm_patch (labels [3], code);
2665 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2666 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2667 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2669 /* Fixup offset */
2670 code2 = labels [0];
2671 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2673 emit_bytes (acfg, buf, code - buf);
2674 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
2676 *tramp_size = code - buf + 4;
2677 #elif defined(TARGET_ARM64)
2678 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2679 #elif defined(TARGET_POWERPC)
2680 guint8 buf [128];
2681 guint8 *code, *labels [16];
2683 code = buf;
2685 /* Load the mscorlib got address */
2686 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
2687 /* Load the parameter from the GOT */
2688 ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
2689 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2691 /* Load and check key */
2692 labels [1] = code;
2693 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2694 ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2695 labels [2] = code;
2696 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2698 /* End-of-loop check */
2699 ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
2700 labels [3] = code;
2701 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2703 /* Loop footer */
2704 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
2705 labels [4] = code;
2706 ppc_b (code, 0);
2707 mono_ppc_patch (labels [4], labels [1]);
2709 /* Match */
2710 mono_ppc_patch (labels [2], code);
2711 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
2712 /* r12 now contains the value of the vtable slot */
2713 /* this is not a function descriptor on ppc64 */
2714 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2715 ppc_mtctr (code, ppc_r12);
2716 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2718 /* Fail */
2719 mono_ppc_patch (labels [3], code);
2720 /* FIXME: */
2721 ppc_break (code);
2723 *tramp_size = code - buf;
2725 emit_bytes (acfg, buf, code - buf);
2726 #else
2727 g_assert_not_reached ();
2728 #endif
2732 #if defined (TARGET_AMD64)
2734 static void
2735 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2738 g_assert (acfg->fp);
2739 emit_unset_mode (acfg);
2741 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
2744 #endif
2748 * arch_emit_gsharedvt_arg_trampoline:
2750 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2751 * two GOT slots which contain the argument, and the code to jump to.
2752 * TRAMP_SIZE is set to the size of the emitted trampoline.
2753 * These kinds of trampolines cannot be enumerated statically, since there could
2754 * be one trampoline per method instantiation, so we emit the same code for all
2755 * trampolines, and parameterize them using two GOT slots.
2757 static void
2758 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2760 #if defined(TARGET_X86)
2761 guint8 buf [128];
2762 guint8 *code;
2764 /* Similar to the PPC code above */
2766 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2768 code = buf;
2769 /* Load mscorlib got address */
2770 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2771 /* Load arg */
2772 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2773 /* Branch to the target address */
2774 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2776 emit_bytes (acfg, buf, code - buf);
2778 *tramp_size = 15;
2779 g_assert (code - buf == *tramp_size);
2780 #elif defined(TARGET_ARM)
2781 guint8 buf [128];
2782 guint8 *code;
2784 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2785 /* Similar to arch_emit_specific_trampoline () */
2786 *tramp_size = 24;
2787 code = buf;
2788 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2789 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2790 /* Load the arg value from the GOT */
2791 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2792 /* Load the addr from the GOT */
2793 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2794 /* Branch to it */
2795 ARM_BX (code, ARMREG_R1);
2797 g_assert (code - buf == 20);
2799 /* Emit it */
2800 emit_bytes (acfg, buf, code - buf);
2801 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
2802 #elif defined(TARGET_ARM64)
2803 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2804 #elif defined (TARGET_AMD64)
2806 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2807 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2808 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2809 fprintf (acfg->fp, "jmp *%%r11\n");
2811 *tramp_size = 0x11;
2812 #else
2813 g_assert_not_reached ();
2814 #endif
2817 static void
2818 arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2820 #if defined(TARGET_ARM)
2821 guint8 buf [128];
2822 guint8 *code;
2824 *tramp_size = 32;
2825 code = buf;
2827 /* Load target address and push it on stack */
2828 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
2829 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2830 ARM_PUSH (code, 1 << ARMREG_IP);
2831 /* Load argument in ARMREG_IP */
2832 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2833 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2834 /* Branch */
2835 ARM_POP (code, 1 << ARMREG_PC);
2837 g_assert (code - buf == 24);
2839 /* Emit it */
2840 emit_bytes (acfg, buf, code - buf);
2841 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
2842 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
2843 #else
2844 g_assert_not_reached ();
2845 #endif
2848 static void
2849 arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2851 #if defined(TARGET_ARM64)
2852 emit_unset_mode (acfg);
2853 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
2854 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
2855 fprintf (acfg->fp, "br x17\n");
2856 *tramp_size = 5 * 4;
2857 #elif defined (TARGET_AMD64)
2858 guint8 buf [32];
2859 guint8 *code;
2860 int this_reg;
2862 this_reg = mono_arch_get_this_arg_reg (NULL);
2863 code = buf;
2864 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2865 emit_bytes (acfg, buf, code - buf);
2867 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2868 fprintf (acfg->fp, "jmp *%%rax\n");
2870 *tramp_size = 13;
2871 #elif defined (TARGET_ARM)
2872 guint8 buf [32];
2873 guint8 *code, *label;
2875 code = buf;
2876 /* Unbox */
2877 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2879 label = code;
2880 /* Calculate GOT slot */
2881 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
2882 /* Load target addr into PC*/
2883 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2885 g_assert (code - buf == 12);
2887 /* Emit it */
2888 emit_bytes (acfg, buf, code - buf);
2889 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
2890 *tramp_size = 4 * 4;
2891 #else
2892 g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
2893 #endif
2896 /* END OF ARCH SPECIFIC CODE */
2898 static guint32
2899 mono_get_field_token (MonoClassField *field)
2901 MonoClass *klass = field->parent;
2902 int i;
2904 int fcount = mono_class_get_field_count (klass);
2905 MonoClassField *klass_fields = m_class_get_fields (klass);
2906 for (i = 0; i < fcount; ++i) {
2907 if (field == &klass_fields [i])
2908 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2911 g_assert_not_reached ();
2912 return 0;
2915 static inline void
2916 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2918 guint8 *p = buf;
2920 //printf ("ENCODE: %d 0x%x.\n", value, value);
2923 * Same encoding as the one used in the metadata, extended to handle values
2924 * greater than 0x1fffffff.
2926 if ((value >= 0) && (value <= 127))
2927 *p++ = value;
2928 else if ((value >= 0) && (value <= 16383)) {
2929 p [0] = 0x80 | (value >> 8);
2930 p [1] = value & 0xff;
2931 p += 2;
2932 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2933 p [0] = (value >> 24) | 0xc0;
2934 p [1] = (value >> 16) & 0xff;
2935 p [2] = (value >> 8) & 0xff;
2936 p [3] = value & 0xff;
2937 p += 4;
2939 else {
2940 p [0] = 0xff;
2941 p [1] = (value >> 24) & 0xff;
2942 p [2] = (value >> 16) & 0xff;
2943 p [3] = (value >> 8) & 0xff;
2944 p [4] = value & 0xff;
2945 p += 5;
2947 if (endbuf)
2948 *endbuf = p;
2951 static void
2952 stream_init (MonoDynamicStream *sh)
2954 sh->index = 0;
2955 sh->alloc_size = 4096;
2956 sh->data = (char *)g_malloc (4096);
2958 /* So offsets are > 0 */
2959 sh->data [0] = 0;
2960 sh->index ++;
2963 static void
2964 make_room_in_stream (MonoDynamicStream *stream, int size)
2966 if (size <= stream->alloc_size)
2967 return;
2969 while (stream->alloc_size <= size) {
2970 if (stream->alloc_size < 4096)
2971 stream->alloc_size = 4096;
2972 else
2973 stream->alloc_size *= 2;
2976 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2979 static guint32
2980 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2982 guint32 idx;
2984 make_room_in_stream (stream, stream->index + len);
2985 memcpy (stream->data + stream->index, data, len);
2986 idx = stream->index;
2987 stream->index += len;
2988 return idx;
2992 * add_to_blob:
2994 * Add data to the binary blob inside the aot image. Returns the offset inside the
2995 * blob where the data was stored.
2997 static guint32
2998 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
3000 g_assert (!acfg->blob_closed);
3002 if (acfg->blob.alloc_size == 0)
3003 stream_init (&acfg->blob);
3005 acfg->stats.blob_size += data_len;
3007 return add_stream_data (&acfg->blob, (char*)data, data_len);
3010 static guint32
3011 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
3013 char buf [4] = {0};
3014 guint32 count;
3016 if (acfg->blob.alloc_size == 0)
3017 stream_init (&acfg->blob);
3019 count = acfg->blob.index % align;
3021 /* we assume the stream data will be aligned */
3022 if (count)
3023 add_stream_data (&acfg->blob, buf, 4 - count);
3025 return add_stream_data (&acfg->blob, (char*)data, data_len);
3028 /* Emit a table of data into the aot image */
3029 static void
3030 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
3032 if (acfg->data_outfile) {
3033 acfg->table_offsets [(int)table] = acfg->datafile_offset;
3034 fwrite (data,1, size, acfg->data_outfile);
3035 acfg->datafile_offset += size;
3036 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
3037 int align = 8 - size % 8;
3038 acfg->datafile_offset += align;
3039 guint8 align_buf [16];
3040 memset (&align_buf, 0, sizeof (align_buf));
3041 fwrite (align_buf, align, 1, acfg->data_outfile);
3042 } else if (acfg->llvm) {
3043 mono_llvm_emit_aot_data (symbol, data, size);
3044 } else {
3045 emit_section_change (acfg, RODATA_SECT, 0);
3046 emit_alignment (acfg, 8);
3047 emit_label (acfg, symbol);
3048 emit_bytes (acfg, data, size);
3053 * emit_offset_table:
3055 * Emit a table of increasing offsets in a compact form using differential encoding.
3056 * There is an index entry for each GROUP_SIZE number of entries. The greater the
3057 * group size, the more compact the table becomes, but the slower it becomes to compute
3058 * a given entry. Returns the size of the table.
3060 static guint32
3061 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
3063 gint32 current_offset;
3064 int i, buf_size, ngroups, index_entry_size;
3065 guint8 *p, *buf;
3066 guint8 *data_p, *data_buf;
3067 guint32 *index_offsets;
3069 ngroups = (noffsets + (group_size - 1)) / group_size;
3071 index_offsets = g_new0 (guint32, ngroups);
3073 buf_size = noffsets * 4;
3074 p = buf = (guint8 *)g_malloc0 (buf_size);
3076 current_offset = 0;
3077 for (i = 0; i < noffsets; ++i) {
3078 //printf ("D: %d -> %d\n", i, offsets [i]);
3079 if ((i % group_size) == 0) {
3080 index_offsets [i / group_size] = p - buf;
3081 /* Emit the full value for these entries */
3082 encode_value (offsets [i], p, &p);
3083 } else {
3084 /* The offsets are allowed to be non-increasing */
3085 //g_assert (offsets [i] >= current_offset);
3086 encode_value (offsets [i] - current_offset, p, &p);
3088 current_offset = offsets [i];
3090 data_buf = buf;
3091 data_p = p;
3093 if (ngroups && index_offsets [ngroups - 1] < 65000)
3094 index_entry_size = 2;
3095 else
3096 index_entry_size = 4;
3098 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
3099 p = buf = (guint8 *)g_malloc0 (buf_size);
3101 /* Emit the header */
3102 encode_int (noffsets, p, &p);
3103 encode_int (group_size, p, &p);
3104 encode_int (ngroups, p, &p);
3105 encode_int (index_entry_size, p, &p);
3107 /* Emit the index */
3108 for (i = 0; i < ngroups; ++i) {
3109 if (index_entry_size == 2)
3110 encode_int16 (index_offsets [i], p, &p);
3111 else
3112 encode_int (index_offsets [i], p, &p);
3114 /* Emit the data */
3115 memcpy (p, data_buf, data_p - data_buf);
3116 p += data_p - data_buf;
3118 g_assert (p - buf <= buf_size);
3120 emit_aot_data (acfg, table, symbol, buf, p - buf);
3122 g_free (buf);
3123 g_free (data_buf);
3125 return (int)(p - buf);
3128 static guint32
3129 get_image_index (MonoAotCompile *cfg, MonoImage *image)
3131 guint32 index;
3133 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
3134 if (index)
3135 return index - 1;
3136 else {
3137 index = g_hash_table_size (cfg->image_hash);
3138 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
3139 g_ptr_array_add (cfg->image_table, image);
3140 return index;
3144 static guint32
3145 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
3147 int i;
3148 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
3150 /* FIXME: Search referenced images as well */
3151 if (!acfg->typespec_classes) {
3152 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
3153 for (i = 0; i < len; i++) {
3154 ERROR_DECL (error);
3155 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
3156 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
3157 if (!is_ok (error)) {
3158 mono_error_cleanup (error);
3159 continue;
3161 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
3164 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
3167 static void
3168 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
3170 static void
3171 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
3173 static void
3174 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
3176 static void
3177 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
3179 static guint32
3180 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst);
3182 static void
3183 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3185 guint8 *p = buf;
3188 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
3189 * information.
3192 if (mono_class_is_ginst (klass)) {
3193 guint32 token;
3194 g_assert (m_class_get_type_token (klass));
3196 /* Find a typespec for a class if possible */
3197 token = find_typespec_for_class (acfg, klass);
3198 if (token) {
3199 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
3200 encode_value (token, p, &p);
3201 } else {
3202 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
3203 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3204 static int count = 0;
3205 guint8 *p1 = p;
3207 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
3208 encode_klass_ref (acfg, gclass, p, &p);
3209 guint32 offset = get_shared_ginst_ref (acfg, inst);
3210 encode_value (offset, p, &p);
3212 count += p - p1;
3214 } else if (m_class_get_type_token (klass)) {
3215 int iindex = get_image_index (acfg, m_class_get_image (klass));
3217 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
3218 if (iindex == 0) {
3219 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
3220 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3221 } else {
3222 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
3223 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3224 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
3226 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3227 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
3228 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
3230 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
3232 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
3233 if (par->gshared_constraint) {
3234 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
3235 encode_type (acfg, par->gshared_constraint, p, &p);
3236 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
3237 } else {
3238 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
3239 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
3241 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3243 if (!container->is_anonymous) {
3244 encode_value (container->is_method, p, &p);
3245 if (container->is_method)
3246 encode_method_ref (acfg, container->owner.method, p, &p);
3247 else
3248 encode_klass_ref (acfg, container->owner.klass, p, &p);
3251 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3252 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3253 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3254 } else {
3255 /* Array class */
3256 g_assert (m_class_get_rank (klass) > 0);
3257 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3258 encode_value (m_class_get_rank (klass), p, &p);
3259 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3262 acfg->stats.class_ref_count++;
3263 acfg->stats.class_ref_size += p - buf;
3265 *endbuf = p;
3268 static guint32
3269 get_shared_klass_ref (MonoAotCompile *acfg, MonoClass *klass)
3271 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3272 guint8 *buf2, *p;
3274 if (!offset) {
3275 buf2 = (guint8 *)g_malloc (1024);
3276 p = buf2;
3278 encode_klass_ref_inner (acfg, klass, p, &p);
3279 g_assert (p - buf2 < 1024);
3281 offset = add_to_blob (acfg, buf2, p - buf2);
3282 g_free (buf2);
3284 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3285 } else {
3286 offset --;
3289 return offset;
3293 * encode_klass_ref:
3295 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3296 * standard metadata encoding.
3298 static void
3299 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3301 gboolean shared = FALSE;
3304 * The encoding of generic instances is large so emit them only once.
3306 if (mono_class_is_ginst (klass)) {
3307 guint32 token;
3308 g_assert (m_class_get_type_token (klass));
3310 /* Find a typespec for a class if possible */
3311 token = find_typespec_for_class (acfg, klass);
3312 if (!token)
3313 shared = TRUE;
3314 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3315 shared = TRUE;
3318 if (shared) {
3319 guint8 *p;
3320 guint32 offset = get_shared_klass_ref (acfg, klass);
3322 p = buf;
3323 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3324 encode_value (offset, p, &p);
3325 *endbuf = p;
3326 return;
3329 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3332 static void
3333 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3335 guint32 token = mono_get_field_token (field);
3336 guint8 *p = buf;
3338 encode_klass_ref (cfg, field->parent, p, &p);
3339 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3340 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3341 *endbuf = p;
3344 static void
3345 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3347 guint8 *p = buf;
3348 int i;
3350 encode_value (inst->type_argc, p, &p);
3351 for (i = 0; i < inst->type_argc; ++i)
3352 encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
3354 acfg->stats.ginst_count++;
3355 acfg->stats.ginst_size += p - buf;
3357 *endbuf = p;
3360 static guint32
3361 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst)
3363 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->ginst_blob_hash, ginst));
3364 if (!offset) {
3365 guint8 *buf2, *p2;
3367 buf2 = (guint8 *)g_malloc (1024);
3368 p2 = buf2;
3370 encode_ginst (acfg, ginst, p2, &p2);
3371 g_assert (p2 - buf2 < 1024);
3373 offset = add_to_blob (acfg, buf2, p2 - buf2);
3374 g_free (buf2);
3376 g_hash_table_insert (acfg->ginst_blob_hash, ginst, GUINT_TO_POINTER (offset + 1));
3377 } else {
3378 offset --;
3380 return offset;
3383 static void
3384 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3386 guint8 *p = buf;
3387 MonoGenericInst *inst;
3388 guint32 flags = (context->class_inst ? 1 : 0) | (context->method_inst ? 2 : 0);
3390 g_assert (flags);
3392 encode_value (flags, p, &p);
3393 inst = context->class_inst;
3394 if (inst) {
3395 guint32 offset = get_shared_ginst_ref (acfg, inst);
3396 encode_value (offset, p, &p);
3398 inst = context->method_inst;
3399 if (inst) {
3400 guint32 offset = get_shared_ginst_ref (acfg, inst);
3401 encode_value (offset, p, &p);
3403 *endbuf = p;
3406 static void
3407 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3409 guint8 *p = buf;
3411 if (t->has_cmods) {
3412 int count = mono_type_custom_modifier_count (t);
3414 *p = MONO_TYPE_CMOD_REQD;
3415 ++p;
3417 encode_value (count, p, &p);
3418 for (int i = 0; i < count; ++i) {
3419 ERROR_DECL (error);
3420 gboolean required;
3421 MonoType *cmod_type = mono_type_get_custom_modifier (t, i, &required, error);
3422 mono_error_assert_ok (error);
3423 encode_value (required, p, &p);
3424 encode_type (acfg, cmod_type, p, &p);
3428 /* t->attrs can be ignored */
3429 //g_assert (t->attrs == 0);
3431 if (t->pinned) {
3432 *p = MONO_TYPE_PINNED;
3433 ++p;
3435 if (t->byref) {
3436 *p = MONO_TYPE_BYREF;
3437 ++p;
3440 *p = t->type;
3441 p ++;
3443 switch (t->type) {
3444 case MONO_TYPE_VOID:
3445 case MONO_TYPE_BOOLEAN:
3446 case MONO_TYPE_CHAR:
3447 case MONO_TYPE_I1:
3448 case MONO_TYPE_U1:
3449 case MONO_TYPE_I2:
3450 case MONO_TYPE_U2:
3451 case MONO_TYPE_I4:
3452 case MONO_TYPE_U4:
3453 case MONO_TYPE_I8:
3454 case MONO_TYPE_U8:
3455 case MONO_TYPE_R4:
3456 case MONO_TYPE_R8:
3457 case MONO_TYPE_I:
3458 case MONO_TYPE_U:
3459 case MONO_TYPE_STRING:
3460 case MONO_TYPE_OBJECT:
3461 case MONO_TYPE_TYPEDBYREF:
3462 break;
3463 case MONO_TYPE_VALUETYPE:
3464 case MONO_TYPE_CLASS:
3465 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3466 break;
3467 case MONO_TYPE_SZARRAY:
3468 encode_klass_ref (acfg, t->data.klass, p, &p);
3469 break;
3470 case MONO_TYPE_PTR:
3471 encode_type (acfg, t->data.type, p, &p);
3472 break;
3473 case MONO_TYPE_GENERICINST: {
3474 MonoClass *gclass = t->data.generic_class->container_class;
3475 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3477 encode_klass_ref (acfg, gclass, p, &p);
3478 encode_ginst (acfg, inst, p, &p);
3479 break;
3481 case MONO_TYPE_ARRAY: {
3482 MonoArrayType *array = t->data.array;
3483 int i;
3485 encode_klass_ref (acfg, array->eklass, p, &p);
3486 encode_value (array->rank, p, &p);
3487 encode_value (array->numsizes, p, &p);
3488 for (i = 0; i < array->numsizes; ++i)
3489 encode_value (array->sizes [i], p, &p);
3490 encode_value (array->numlobounds, p, &p);
3491 for (i = 0; i < array->numlobounds; ++i)
3492 encode_value (array->lobounds [i], p, &p);
3493 break;
3495 case MONO_TYPE_VAR:
3496 case MONO_TYPE_MVAR:
3497 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3498 break;
3499 default:
3500 g_assert_not_reached ();
3503 *endbuf = p;
3506 static void
3507 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3509 guint8 *p = buf;
3510 guint32 flags = 0;
3511 int i;
3513 /* Similar to the metadata encoding */
3514 if (sig->generic_param_count)
3515 flags |= 0x10;
3516 if (sig->hasthis)
3517 flags |= 0x20;
3518 if (sig->explicit_this)
3519 flags |= 0x40;
3520 flags |= (sig->call_convention & 0x0F);
3522 *p = flags;
3523 ++p;
3524 if (sig->generic_param_count)
3525 encode_value (sig->generic_param_count, p, &p);
3526 encode_value (sig->param_count, p, &p);
3528 encode_type (acfg, sig->ret, p, &p);
3529 for (i = 0; i < sig->param_count; ++i) {
3530 if (sig->sentinelpos == i) {
3531 *p = MONO_TYPE_SENTINEL;
3532 ++p;
3534 encode_type (acfg, sig->params [i], p, &p);
3537 *endbuf = p;
3540 #define MAX_IMAGE_INDEX 250
3542 static void
3543 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3545 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3546 guint32 token = method->token;
3547 MonoJumpInfoToken *ji;
3548 guint8 *p = buf;
3551 * The encoding for most methods is as follows:
3552 * - image index encoded as a leb128
3553 * - token index encoded as a leb128
3554 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3555 * types of method encodings.
3558 /* Mark methods which can't use aot trampolines because they need the further
3559 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3561 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3562 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3563 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3565 if (method->wrapper_type) {
3566 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3568 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3570 encode_value (method->wrapper_type, p, &p);
3572 switch (method->wrapper_type) {
3573 case MONO_WRAPPER_REMOTING_INVOKE:
3574 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3575 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3576 MonoMethod *m;
3578 m = mono_marshal_method_from_wrapper (method);
3579 g_assert (m);
3580 encode_method_ref (acfg, m, p, &p);
3581 break;
3583 case MONO_WRAPPER_PROXY_ISINST:
3584 case MONO_WRAPPER_LDFLD:
3585 case MONO_WRAPPER_LDFLDA:
3586 case MONO_WRAPPER_STFLD: {
3587 g_assert (info);
3588 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3589 break;
3591 case MONO_WRAPPER_ALLOC: {
3592 /* The GC name is saved once in MonoAotFileInfo */
3593 g_assert (info->d.alloc.alloc_type != -1);
3594 encode_value (info->d.alloc.alloc_type, p, &p);
3595 break;
3597 case MONO_WRAPPER_WRITE_BARRIER: {
3598 g_assert (info);
3599 break;
3601 case MONO_WRAPPER_STELEMREF: {
3602 g_assert (info);
3603 encode_value (info->subtype, p, &p);
3604 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3605 encode_value (info->d.virtual_stelemref.kind, p, &p);
3606 break;
3608 case MONO_WRAPPER_OTHER: {
3609 g_assert (info);
3610 encode_value (info->subtype, p, &p);
3611 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3612 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3613 encode_klass_ref (acfg, method->klass, p, &p);
3614 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3615 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3616 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3617 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3618 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3619 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3620 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3621 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3622 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3623 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3624 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
3625 encode_value (info->d.icall.jit_icall_id, p, &p);
3626 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
3627 encode_value (info->d.aot_init.subtype, p, &p);
3628 break;
3630 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3631 g_assert (info);
3632 encode_value (info->subtype, p, &p);
3633 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3634 encode_value (info->d.icall.jit_icall_id, p, &p);
3635 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3636 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3637 } else {
3638 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3639 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3641 break;
3643 case MONO_WRAPPER_SYNCHRONIZED: {
3644 MonoMethod *m;
3646 m = mono_marshal_method_from_wrapper (method);
3647 g_assert (m);
3648 g_assert (m != method);
3649 encode_method_ref (acfg, m, p, &p);
3650 break;
3652 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3653 g_assert (info);
3654 encode_value (info->subtype, p, &p);
3656 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3657 encode_value (info->d.element_addr.rank, p, &p);
3658 encode_value (info->d.element_addr.elem_size, p, &p);
3659 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3660 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3661 } else {
3662 g_assert_not_reached ();
3664 break;
3666 case MONO_WRAPPER_CASTCLASS: {
3667 g_assert (info);
3668 encode_value (info->subtype, p, &p);
3669 break;
3671 case MONO_WRAPPER_RUNTIME_INVOKE: {
3672 g_assert (info);
3673 encode_value (info->subtype, p, &p);
3674 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3675 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3676 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3677 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3678 break;
3680 case MONO_WRAPPER_DELEGATE_INVOKE:
3681 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3682 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3683 if (method->is_inflated) {
3684 /* These wrappers are identified by their class */
3685 encode_value (1, p, &p);
3686 encode_klass_ref (acfg, method->klass, p, &p);
3687 } else {
3688 MonoMethodSignature *sig = mono_method_signature_internal (method);
3689 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3691 encode_value (0, p, &p);
3692 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3693 encode_value (info ? info->subtype : 0, p, &p);
3694 encode_signature (acfg, sig, p, &p);
3696 break;
3698 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3699 g_assert (info);
3700 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3701 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3702 break;
3704 default:
3705 g_assert_not_reached ();
3707 } else if (mono_method_signature_internal (method)->is_inflated) {
3709 * This is a generic method, find the original token which referenced it and
3710 * encode that.
3711 * Obtain the token from information recorded by the JIT.
3713 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3714 if (ji) {
3715 image_index = get_image_index (acfg, ji->image);
3716 g_assert (image_index < MAX_IMAGE_INDEX);
3717 token = ji->token;
3719 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3720 encode_value (image_index, p, &p);
3721 encode_value (token, p, &p);
3722 } else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
3723 /* Already emitted as part of an rgctx fetch */
3724 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3725 offset --;
3727 encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
3728 encode_value (offset, p, &p);
3729 } else {
3730 MonoMethod *declaring;
3731 MonoGenericContext *context = mono_method_get_context (method);
3733 g_assert (method->is_inflated);
3734 declaring = ((MonoMethodInflated*)method)->declaring;
3737 * This might be a non-generic method of a generic instance, which
3738 * doesn't have a token since the reference is generated by the JIT
3739 * like Nullable:Box/Unbox, or by generic sharing.
3741 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3742 /* Encode the klass */
3743 encode_klass_ref (acfg, method->klass, p, &p);
3744 /* Encode the method */
3745 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3746 g_assert (image_index < MAX_IMAGE_INDEX);
3747 g_assert (declaring->token);
3748 token = declaring->token;
3749 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3750 encode_value (image_index, p, &p);
3751 encode_value (mono_metadata_token_index (token), p, &p);
3752 encode_generic_context (acfg, context, p, &p);
3754 } else if (token == 0) {
3755 /* This might be a method of a constructed type like int[,].Set */
3756 /* Obtain the token from information recorded by the JIT */
3757 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3758 if (ji) {
3759 image_index = get_image_index (acfg, ji->image);
3760 g_assert (image_index < MAX_IMAGE_INDEX);
3761 token = ji->token;
3763 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3764 encode_value (image_index, p, &p);
3765 encode_value (token, p, &p);
3766 } else {
3767 /* Array methods */
3768 g_assert (m_class_get_rank (method->klass));
3770 /* Encode directly */
3771 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3772 encode_klass_ref (acfg, method->klass, p, &p);
3773 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3774 encode_value (0, p, &p);
3775 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3776 encode_value (1, p, &p);
3777 else if (!strcmp (method->name, "Get"))
3778 encode_value (2, p, &p);
3779 else if (!strcmp (method->name, "Address"))
3780 encode_value (3, p, &p);
3781 else if (!strcmp (method->name, "Set"))
3782 encode_value (4, p, &p);
3783 else
3784 g_assert_not_reached ();
3786 } else {
3787 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3789 if (image_index >= MONO_AOT_METHODREF_MIN) {
3790 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3791 encode_value (image_index, p, &p);
3792 encode_value (mono_metadata_token_index (token), p, &p);
3793 } else {
3794 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3798 acfg->stats.method_ref_count++;
3799 acfg->stats.method_ref_size += p - buf;
3801 *endbuf = p;
3804 static guint32
3805 get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
3807 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3808 if (!offset) {
3809 guint8 *buf2, *p2;
3811 buf2 = (guint8 *)g_malloc (1024);
3812 p2 = buf2;
3814 encode_method_ref (acfg, method, p2, &p2);
3815 g_assert (p2 - buf2 < 1024);
3817 offset = add_to_blob (acfg, buf2, p2 - buf2);
3818 g_free (buf2);
3820 g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
3821 } else {
3822 offset --;
3824 return offset;
3827 static gint
3828 compare_patches (gconstpointer a, gconstpointer b)
3830 int i, j;
3832 i = (*(MonoJumpInfo**)a)->ip.i;
3833 j = (*(MonoJumpInfo**)b)->ip.i;
3835 if (i < j)
3836 return -1;
3837 else
3838 if (i > j)
3839 return 1;
3840 else
3841 return 0;
3844 static G_GNUC_UNUSED char*
3845 patch_to_string (MonoJumpInfo *patch_info)
3847 GString *str;
3849 str = g_string_new ("");
3851 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3853 switch (patch_info->type) {
3854 case MONO_PATCH_INFO_VTABLE:
3855 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3856 break;
3857 default:
3858 break;
3860 g_string_append_printf (str, ")");
3861 return g_string_free (str, FALSE);
3865 * is_plt_patch:
3867 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3868 * PLT entry.
3870 static inline gboolean
3871 is_plt_patch (MonoJumpInfo *patch_info)
3873 switch (patch_info->type) {
3874 case MONO_PATCH_INFO_METHOD:
3875 case MONO_PATCH_INFO_JIT_ICALL_ID:
3876 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3877 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3878 case MONO_PATCH_INFO_RGCTX_FETCH:
3879 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
3880 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
3881 return TRUE;
3882 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
3883 default:
3884 return FALSE;
3889 * get_plt_symbol:
3891 * Return the symbol identifying the plt entry PLT_OFFSET.
3893 static char*
3894 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3896 #ifdef TARGET_MACH
3898 * The Apple linker reorganizes object files, so it doesn't like branches to local
3899 * labels, since those have no relocations.
3901 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3902 #else
3903 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3904 #endif
3908 * get_plt_entry:
3910 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3912 static MonoPltEntry*
3913 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3915 MonoPltEntry *res;
3916 gboolean synchronized = FALSE;
3917 static int synchronized_symbol_idx;
3919 if (!is_plt_patch (patch_info))
3920 return NULL;
3922 if (!acfg->patch_to_plt_entry [patch_info->type])
3923 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3924 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3926 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3928 * Allocate a separate PLT slot for each such patch, since some plt
3929 * entries will refer to the method itself, and some will refer to the
3930 * wrapper.
3932 res = NULL;
3933 synchronized = TRUE;
3936 if (!res) {
3937 MonoJumpInfo *new_ji;
3939 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3941 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3942 res->plt_offset = acfg->plt_offset;
3943 res->ji = new_ji;
3944 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3945 if (acfg->aot_opts.write_symbols)
3946 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3947 if (synchronized) {
3948 /* Avoid duplicate symbols because we don't cache */
3949 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3950 if (res->debug_sym)
3951 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3952 synchronized_symbol_idx ++;
3955 if (res->debug_sym)
3956 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3957 else
3958 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3959 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3960 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3961 char *tmp = res->llvm_symbol;
3962 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3963 g_free (tmp);
3966 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3968 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3970 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3971 //mono_print_ji (patch_info); printf ("\n");
3972 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3974 acfg->plt_offset ++;
3977 return res;
3980 static guint32
3981 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3983 guint32 got_offset;
3984 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3986 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3987 if (got_offset)
3988 return got_offset - 1;
3989 g_assert_not_reached ();
3993 * get_got_offset:
3995 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3996 * JI could be found if it exists, otherwise allocates a new one.
3998 static guint32
3999 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
4001 guint32 got_offset;
4002 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
4004 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
4005 if (got_offset)
4006 return got_offset - 1;
4008 if (llvm) {
4009 got_offset = acfg->llvm_got_offset;
4010 acfg->llvm_got_offset ++;
4011 } else {
4012 got_offset = acfg->got_offset;
4013 acfg->got_offset ++;
4016 acfg->stats.got_slots ++;
4017 acfg->stats.got_slot_types [ji->type] ++;
4019 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
4020 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
4021 g_ptr_array_add (info->got_patches, ji);
4023 return got_offset;
4026 /* Add a method to the list of methods which need to be emitted */
4027 static void
4028 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
4030 g_assert (method);
4031 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
4032 g_ptr_array_add (acfg->methods, method);
4033 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
4034 acfg->nmethods = acfg->methods->len + 1;
4037 if (method->wrapper_type || extra) {
4038 int token = mono_metadata_token_index (method->token) - 1;
4039 if (token < 0)
4040 acfg->nextra_methods++;
4041 g_ptr_array_add (acfg->extra_methods, method);
4045 static gboolean
4046 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
4048 /* One instantiation with valuetypes is generated for each async method */
4049 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")))
4050 return TRUE;
4051 else
4052 return FALSE;
4055 static guint32
4056 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
4058 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4060 g_assert (index);
4062 return index - 1;
4065 static int
4066 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
4068 int index;
4070 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4071 if (index)
4072 return index - 1;
4074 index = acfg->method_index;
4075 add_method_with_index (acfg, method, index, extra);
4077 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
4079 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
4081 acfg->method_index ++;
4083 return index;
4086 static int
4087 add_method (MonoAotCompile *acfg, MonoMethod *method)
4089 return add_method_full (acfg, method, FALSE, 0);
4092 static void
4093 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
4095 g_assert (acfg->dedup_stats);
4097 char *name = mono_aot_get_mangled_method_name (method);
4098 g_assert (name);
4100 // For stats
4101 char *stats_name = g_strdup (name);
4103 g_assert (acfg->dedup_cache);
4105 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
4106 // This AOTCompile owns this method
4107 // We do this to decide whether to write it to disk
4108 // during a dedup run (first phase, where we skip).
4110 // If never changed, then maybe can avoid a recompile
4111 // of the cache.
4113 // Files not read in during last phase.
4114 acfg->dedup_cache_changed = TRUE;
4116 // owns name
4117 g_hash_table_insert (acfg->dedup_cache, name, method);
4118 } else {
4119 // owns name
4120 g_free (name);
4123 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
4124 count++;
4125 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4128 static void
4129 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4131 ERROR_DECL (error);
4133 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4134 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4135 if (!is_ok (error)) {
4136 /* vtype constraint */
4137 mono_error_cleanup (error);
4138 return;
4140 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4141 /* Use the gsharedvt version */
4142 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4143 mono_error_assert_ok (error);
4146 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4147 mono_dedup_cache_method (acfg, method);
4149 if (!acfg->dedup_emit_mode)
4150 return;
4153 if (acfg->aot_opts.log_generics)
4154 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4156 add_method_full (acfg, method, TRUE, depth);
4159 static void
4160 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4162 add_extra_method_with_depth (acfg, method, 0);
4165 static void
4166 add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
4168 if (!callinfo->sig)
4169 return;
4171 g_assert (callinfo->name && callinfo->func);
4173 add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
4176 static void
4177 add_lazy_init_wrappers (MonoAotCompile *acfg)
4179 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD));
4180 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_MRGCTX));
4181 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_VTABLE));
4182 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_THIS));
4185 static MonoMethod*
4186 get_runtime_invoke_sig (MonoMethodSignature *sig)
4188 MonoMethodBuilder *mb;
4189 MonoMethod *m;
4191 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4192 m = mono_mb_create_method (mb, sig, 16);
4193 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4194 mono_mb_free (mb);
4195 return invoke;
4198 static MonoMethod*
4199 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4201 return mono_marshal_get_runtime_invoke (method, virtual_);
4204 static gboolean
4205 can_marshal_struct (MonoClass *klass)
4207 MonoClassField *field;
4208 gboolean can_marshal = TRUE;
4209 gpointer iter = NULL;
4210 MonoMarshalType *info;
4211 int i;
4213 if (mono_class_is_auto_layout (klass))
4214 return FALSE;
4216 info = mono_marshal_load_type_info (klass);
4218 /* Only allow a few field types to avoid asserts in the marshalling code */
4219 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4220 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4221 continue;
4223 switch (field->type->type) {
4224 case MONO_TYPE_I4:
4225 case MONO_TYPE_U4:
4226 case MONO_TYPE_I1:
4227 case MONO_TYPE_U1:
4228 case MONO_TYPE_BOOLEAN:
4229 case MONO_TYPE_I2:
4230 case MONO_TYPE_U2:
4231 case MONO_TYPE_CHAR:
4232 case MONO_TYPE_I8:
4233 case MONO_TYPE_U8:
4234 case MONO_TYPE_I:
4235 case MONO_TYPE_U:
4236 case MONO_TYPE_PTR:
4237 case MONO_TYPE_R4:
4238 case MONO_TYPE_R8:
4239 case MONO_TYPE_STRING:
4240 break;
4241 case MONO_TYPE_VALUETYPE:
4242 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4243 can_marshal = FALSE;
4244 break;
4245 case MONO_TYPE_SZARRAY: {
4246 gboolean has_mspec = FALSE;
4248 if (info) {
4249 for (i = 0; i < info->num_fields; ++i) {
4250 if (info->fields [i].field == field && info->fields [i].mspec)
4251 has_mspec = TRUE;
4254 if (!has_mspec)
4255 can_marshal = FALSE;
4256 break;
4258 default:
4259 can_marshal = FALSE;
4260 break;
4264 /* Special cases */
4265 /* Its hard to compute whenever these can be marshalled or not */
4266 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4267 return TRUE;
4269 return can_marshal;
4272 static void
4273 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4275 /* Create a vtype instantiation */
4276 MonoGenericContext shared_context;
4277 MonoType **args;
4278 MonoGenericInst *inst;
4279 MonoGenericContainer *container;
4280 MonoClass **constraints;
4281 int i;
4283 memset (ctx, 0, sizeof (MonoGenericContext));
4285 if (mono_class_is_gtd (method->klass)) {
4286 shared_context = mono_class_get_generic_container (method->klass)->context;
4287 inst = shared_context.class_inst;
4289 args = g_new0 (MonoType*, inst->type_argc);
4290 for (i = 0; i < inst->type_argc; ++i) {
4291 args [i] = mono_get_int_type ();
4293 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4295 if (method->is_generic) {
4296 container = mono_method_get_generic_container (method);
4297 g_assert (!container->is_anonymous && container->is_method);
4298 shared_context = container->context;
4299 inst = shared_context.method_inst;
4301 args = g_new0 (MonoType*, inst->type_argc);
4302 for (i = 0; i < container->type_argc; ++i) {
4303 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4304 gboolean ref_only = FALSE;
4306 if (info && info->constraints) {
4307 constraints = info->constraints;
4309 while (*constraints) {
4310 MonoClass *cklass = *constraints;
4311 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4312 /* Inflaring the method with our vtype would not be valid */
4313 ref_only = TRUE;
4314 constraints ++;
4318 if (ref_only)
4319 args [i] = mono_get_object_type ();
4320 else
4321 args [i] = mono_get_int_type ();
4323 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4327 static void
4328 add_gc_wrappers (MonoAotCompile *acfg)
4330 MonoMethod *m;
4331 /* Managed Allocators */
4332 int nallocators = mono_gc_get_managed_allocator_types ();
4333 for (int i = 0; i < nallocators; ++i) {
4334 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4335 add_method (acfg, m);
4336 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4337 add_method (acfg, m);
4338 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4339 add_method (acfg, m);
4342 /* write barriers */
4343 if (mono_gc_is_moving ()) {
4344 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4345 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4349 static gboolean
4350 contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
4352 for (int i = 0; i < cattr->num_attrs; ++i) {
4353 MonoCustomAttrEntry *attr = &cattr->attrs [i];
4355 if (!attr->ctor)
4356 return FALSE;
4358 if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
4359 return FALSE;
4361 if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
4362 return FALSE;
4365 return TRUE;
4368 gboolean
4369 mono_aot_can_specialize (MonoMethod *method)
4371 if (!method)
4372 return FALSE;
4374 if (method->wrapper_type != MONO_WRAPPER_NONE)
4375 return FALSE;
4377 // If it's not private, we can't specialize
4378 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
4379 return FALSE;
4381 // If it has the attribute disabling the specialization, we can't specialize
4383 // Set by linker, indicates that the method can be found through reflection
4384 // and that call-site specialization shouldn't be done.
4386 // Important that this attribute is used for *nothing else*
4388 // If future authors make use of it (to disable more optimizations),
4389 // change this place to use a new attribute.
4390 ERROR_DECL (cattr_error);
4391 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
4393 if (!is_ok (cattr_error)) {
4394 mono_error_cleanup (cattr_error);
4395 goto cleanup_false;
4396 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4397 goto cleanup_true;
4400 cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
4402 if (!is_ok (cattr_error)) {
4403 mono_error_cleanup (cattr_error);
4404 goto cleanup_false;
4405 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4406 goto cleanup_true;
4407 } else {
4408 goto cleanup_false;
4411 cleanup_false:
4412 if (cattr)
4413 mono_custom_attrs_free (cattr);
4414 return FALSE;
4416 cleanup_true:
4417 if (cattr)
4418 mono_custom_attrs_free (cattr);
4419 return TRUE;
4422 static void
4423 add_wrappers (MonoAotCompile *acfg)
4425 MonoMethod *method, *m;
4426 int i, j;
4427 MonoMethodSignature *sig, *csig;
4428 guint32 token;
4431 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4432 * so there is only one wrapper of a given type, or inlining their contents into their
4433 * callers.
4435 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4436 ERROR_DECL (error);
4437 MonoMethod *method;
4438 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4439 gboolean skip = FALSE;
4441 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4442 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4444 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4445 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4446 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4447 skip = TRUE;
4449 /* Skip methods which can not be handled by get_runtime_invoke () */
4450 sig = mono_method_signature_internal (method);
4451 if (!sig)
4452 continue;
4453 if ((sig->ret->type == MONO_TYPE_PTR) ||
4454 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4455 skip = TRUE;
4456 if (mono_class_is_open_constructed_type (sig->ret))
4457 skip = TRUE;
4459 for (j = 0; j < sig->param_count; j++) {
4460 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4461 skip = TRUE;
4462 if (mono_class_is_open_constructed_type (sig->params [j]))
4463 skip = TRUE;
4466 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4467 if (!mono_class_is_contextbound (method->klass)) {
4468 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4469 gboolean has_nullable = FALSE;
4471 for (j = 0; j < sig->param_count; j++) {
4472 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4473 has_nullable = TRUE;
4476 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4477 /* Supported by the dynamic runtime-invoke wrapper */
4478 skip = TRUE;
4480 if (info)
4481 mono_arch_dyn_call_free (info);
4483 #endif
4485 if (acfg->aot_opts.llvm_only)
4486 /* Supported by the gsharedvt based runtime-invoke wrapper */
4487 skip = TRUE;
4489 if (!skip) {
4490 //printf ("%s\n", mono_method_full_name (method, TRUE));
4491 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4495 if (mono_is_corlib_image (acfg->image->assembly->image)) {
4496 /* Runtime invoke wrappers */
4498 MonoType *void_type = mono_get_void_type ();
4499 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4501 /* void runtime-invoke () [.cctor] */
4502 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4503 csig->ret = void_type;
4504 add_method (acfg, get_runtime_invoke_sig (csig));
4506 /* void runtime-invoke () [Finalize] */
4507 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4508 csig->hasthis = 1;
4509 csig->ret = void_type;
4510 add_method (acfg, get_runtime_invoke_sig (csig));
4512 /* void runtime-invoke (string) [exception ctor] */
4513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4514 csig->hasthis = 1;
4515 csig->ret = void_type;
4516 csig->params [0] = string_type;
4517 add_method (acfg, get_runtime_invoke_sig (csig));
4519 /* void runtime-invoke (string, string) [exception ctor] */
4520 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4521 csig->hasthis = 1;
4522 csig->ret = void_type;
4523 csig->params [0] = string_type;
4524 csig->params [1] = string_type;
4525 add_method (acfg, get_runtime_invoke_sig (csig));
4527 /* string runtime-invoke () [Exception.ToString ()] */
4528 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4529 csig->hasthis = 1;
4530 csig->ret = string_type;
4531 add_method (acfg, get_runtime_invoke_sig (csig));
4533 /* void runtime-invoke (string, Exception) [exception ctor] */
4534 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4535 csig->hasthis = 1;
4536 csig->ret = void_type;
4537 csig->params [0] = string_type;
4538 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4539 add_method (acfg, get_runtime_invoke_sig (csig));
4541 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4542 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4543 csig->hasthis = 1;
4544 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4545 csig->params [0] = string_type;
4546 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4547 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4548 add_method (acfg, get_runtime_invoke_sig (csig));
4550 /* runtime-invoke used by finalizers */
4551 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4553 /* This is used by mono_runtime_capture_context () */
4554 method = mono_get_context_capture_method ();
4555 if (method)
4556 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4558 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4559 if (!acfg->aot_opts.llvm_only)
4560 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4561 #endif
4563 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4564 if (acfg->aot_opts.llvm_only) {
4565 int variants;
4567 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4568 for (variants = 0; variants < 4; ++variants) {
4569 for (i = 0; i < 40; ++i) {
4570 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4571 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4573 g_free (sig);
4578 /* stelemref */
4579 add_method (acfg, mono_marshal_get_stelemref ());
4581 add_gc_wrappers (acfg);
4583 /* Stelemref wrappers */
4585 MonoMethod **wrappers;
4586 int nwrappers;
4588 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4589 for (i = 0; i < nwrappers; ++i)
4590 add_method (acfg, wrappers [i]);
4591 g_free (wrappers);
4594 /* castclass_with_check wrapper */
4595 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4596 /* isinst_with_check wrapper */
4597 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4599 /* JIT icall wrappers */
4600 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
4601 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
4602 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
4606 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4607 * we use the original method instead at runtime.
4608 * Since full-aot doesn't support remoting, this is not a problem.
4610 #if 0
4611 /* remoting-invoke wrappers */
4612 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4613 ERROR_DECL (error);
4614 MonoMethodSignature *sig;
4616 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4617 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4618 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4620 sig = mono_method_signature_internal (method);
4622 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4623 m = mono_marshal_get_remoting_invoke_with_check (method);
4625 add_method (acfg, m);
4628 #endif
4630 /* delegate-invoke wrappers */
4631 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4632 ERROR_DECL (error);
4633 MonoClass *klass;
4635 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4636 klass = mono_class_get_checked (acfg->image, token, error);
4638 if (!klass) {
4639 mono_error_cleanup (error);
4640 continue;
4643 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4644 continue;
4646 if (!mono_class_is_gtd (klass)) {
4647 method = mono_get_delegate_invoke_internal (klass);
4649 m = mono_marshal_get_delegate_invoke (method, NULL);
4651 add_method (acfg, m);
4653 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4654 if (method)
4655 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4657 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4658 if (method)
4659 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4661 MonoCustomAttrInfo *cattr;
4662 cattr = mono_custom_attrs_from_class_checked (klass, error);
4663 if (!is_ok (error)) {
4664 mono_error_cleanup (error);
4665 g_assert (!cattr);
4666 continue;
4669 if (cattr) {
4670 int j;
4672 for (j = 0; j < cattr->num_attrs; ++j)
4673 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")))
4674 break;
4675 if (j < cattr->num_attrs) {
4676 MonoMethod *invoke;
4677 MonoMethod *wrapper;
4678 MonoMethod *del_invoke;
4680 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4681 invoke = mono_get_delegate_invoke_internal (klass);
4682 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4683 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4684 add_method (acfg, wrapper);
4685 add_method (acfg, del_invoke);
4687 mono_custom_attrs_free (cattr);
4689 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4690 ERROR_DECL (error);
4691 MonoGenericContext ctx;
4692 MonoMethod *inst, *gshared;
4695 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4697 /* Invoke */
4698 method = mono_get_delegate_invoke_internal (klass);
4699 create_gsharedvt_inst (acfg, method, &ctx);
4701 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4702 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4704 m = mono_marshal_get_delegate_invoke (inst, NULL);
4705 g_assert (m->is_inflated);
4707 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4708 mono_error_assert_ok (error);
4710 add_extra_method (acfg, gshared);
4712 /* begin-invoke */
4713 method = mono_get_delegate_begin_invoke_internal (klass);
4714 if (method) {
4715 create_gsharedvt_inst (acfg, method, &ctx);
4717 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4718 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4720 m = mono_marshal_get_delegate_begin_invoke (inst);
4721 g_assert (m->is_inflated);
4723 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4724 mono_error_assert_ok (error);
4726 add_extra_method (acfg, gshared);
4729 /* end-invoke */
4730 method = mono_get_delegate_end_invoke_internal (klass);
4731 if (method) {
4732 create_gsharedvt_inst (acfg, method, &ctx);
4734 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4735 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4737 m = mono_marshal_get_delegate_end_invoke (inst);
4738 g_assert (m->is_inflated);
4740 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4741 mono_error_assert_ok (error);
4743 add_extra_method (acfg, gshared);
4748 /* array access wrappers */
4749 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4750 ERROR_DECL (error);
4751 MonoClass *klass;
4753 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4754 klass = mono_class_get_checked (acfg->image, token, error);
4756 if (!klass) {
4757 mono_error_cleanup (error);
4758 continue;
4761 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4762 MonoMethod *m, *wrapper;
4764 /* Add runtime-invoke wrappers too */
4766 m = get_method_nofail (klass, "Get", -1, 0);
4767 g_assert (m);
4768 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4769 add_extra_method (acfg, wrapper);
4770 if (!acfg->aot_opts.llvm_only)
4771 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4773 m = get_method_nofail (klass, "Set", -1, 0);
4774 g_assert (m);
4775 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4776 add_extra_method (acfg, wrapper);
4777 if (!acfg->aot_opts.llvm_only)
4778 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4782 /* Synchronized wrappers */
4783 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4784 ERROR_DECL (error);
4785 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4786 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4787 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4789 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4790 if (method->is_generic) {
4791 // FIXME:
4792 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4793 ERROR_DECL (error);
4794 MonoGenericContext ctx;
4795 MonoMethod *inst, *gshared, *m;
4798 * Create a generic wrapper for a generic instance, and AOT that.
4800 create_gsharedvt_inst (acfg, method, &ctx);
4801 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4802 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4803 m = mono_marshal_get_synchronized_wrapper (inst);
4804 g_assert (m->is_inflated);
4805 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4806 mono_error_assert_ok (error);
4808 add_method (acfg, gshared);
4809 } else {
4810 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4815 /* pinvoke wrappers */
4816 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4817 ERROR_DECL (error);
4818 MonoMethod *method;
4819 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4821 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4822 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4824 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4825 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4826 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4829 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4830 if (acfg->aot_opts.llvm_only) {
4831 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4832 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4837 /* native-to-managed wrappers */
4838 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4839 ERROR_DECL (error);
4840 MonoMethod *method;
4841 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4842 MonoCustomAttrInfo *cattr;
4843 int j;
4845 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4846 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4849 * Only generate native-to-managed wrappers for methods which have an
4850 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4851 * name to avoid defining a new assembly to contain it.
4853 cattr = mono_custom_attrs_from_method_checked (method, error);
4854 if (!is_ok (error)) {
4855 char *name = mono_method_get_full_name (method);
4856 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4857 g_free (name);
4860 if (cattr) {
4861 for (j = 0; j < cattr->num_attrs; ++j)
4862 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4863 break;
4864 if (j < cattr->num_attrs) {
4865 MonoCustomAttrEntry *e = &cattr->attrs [j];
4866 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4867 const char *p = (const char*)e->data;
4868 const char *named;
4869 int slen, num_named, named_type;
4870 char *n;
4871 MonoType *t;
4872 MonoClass *klass;
4873 char *export_name = NULL;
4874 MonoMethod *wrapper;
4876 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4877 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4878 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",
4879 mono_method_full_name (method, TRUE));
4880 exit (1);
4883 g_assert (sig->param_count == 1);
4884 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4887 * Decode the cattr manually since we can't create objects
4888 * during aot compilation.
4891 /* Skip prolog */
4892 p += 2;
4894 /* From load_cattr_value () in reflection.c */
4895 slen = mono_metadata_decode_value (p, &p);
4896 n = (char *)g_memdup (p, slen + 1);
4897 n [slen] = 0;
4898 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4899 g_assert (t);
4900 mono_error_assert_ok (error);
4901 g_free (n);
4903 klass = mono_class_from_mono_type_internal (t);
4904 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4906 p += slen;
4908 num_named = read16 (p);
4909 p += 2;
4911 g_assert (num_named < 2);
4912 if (num_named == 1) {
4913 int name_len;
4914 char *name;
4916 /* parse ExportSymbol attribute */
4917 named = p;
4918 named_type = *named;
4919 named += 1;
4920 /* data_type = *named; */
4921 named += 1;
4923 name_len = mono_metadata_decode_blob_size (named, &named);
4924 name = (char *)g_malloc (name_len + 1);
4925 memcpy (name, named, name_len);
4926 name [name_len] = 0;
4927 named += name_len;
4929 g_assert (named_type == 0x54);
4930 g_assert (!strcmp (name, "ExportSymbol"));
4932 /* load_cattr_value (), string case */
4933 MONO_DISABLE_WARNING (4310) // cast truncates constant value
4934 g_assert (*named != (char)0xFF);
4935 MONO_RESTORE_WARNING
4936 slen = mono_metadata_decode_value (named, &named);
4937 export_name = (char *)g_malloc (slen + 1);
4938 memcpy (export_name, named, slen);
4939 export_name [slen] = 0;
4940 named += slen;
4943 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4944 mono_error_assert_ok (error);
4946 add_method (acfg, wrapper);
4947 if (export_name)
4948 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4950 g_free (cattr);
4953 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4954 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4955 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4959 /* StructureToPtr/PtrToStructure wrappers */
4960 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4961 ERROR_DECL (error);
4962 MonoClass *klass;
4964 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4965 klass = mono_class_get_checked (acfg->image, token, error);
4967 if (!klass) {
4968 mono_error_cleanup (error);
4969 continue;
4972 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4973 !(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)))) {
4974 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4975 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4980 static gboolean
4981 has_type_vars (MonoClass *klass)
4983 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4984 return TRUE;
4985 if (m_class_get_rank (klass))
4986 return has_type_vars (m_class_get_element_class (klass));
4987 if (mono_class_is_ginst (klass)) {
4988 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4989 if (context->class_inst) {
4990 int i;
4992 for (i = 0; i < context->class_inst->type_argc; ++i)
4993 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
4994 return TRUE;
4997 if (mono_class_is_gtd (klass))
4998 return TRUE;
4999 return FALSE;
5002 static gboolean
5003 is_vt_inst (MonoGenericInst *inst)
5005 int i;
5007 for (i = 0; i < inst->type_argc; ++i) {
5008 MonoType *t = inst->type_argv [i];
5009 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
5010 return TRUE;
5012 return FALSE;
5015 static gboolean
5016 method_has_type_vars (MonoMethod *method)
5018 if (has_type_vars (method->klass))
5019 return TRUE;
5021 if (method->is_inflated) {
5022 MonoGenericContext *context = mono_method_get_context (method);
5023 if (context->method_inst) {
5024 int i;
5026 for (i = 0; i < context->method_inst->type_argc; ++i)
5027 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
5028 return TRUE;
5031 return FALSE;
5034 static
5035 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
5037 return opts->mode == MONO_AOT_MODE_FULL;
5040 static
5041 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
5043 return opts->interp;
5046 static
5047 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
5049 return opts->mode == MONO_AOT_MODE_HYBRID;
5052 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
5054 static void
5055 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
5057 /* This might lead to a huge code blowup so only do it if neccesary */
5058 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
5059 return;
5061 add_generic_class_with_depth (acfg, klass, 0, ref);
5064 static gboolean
5065 check_type_depth (MonoType *t, int depth)
5067 int i;
5069 if (depth > 8)
5070 return TRUE;
5072 switch (t->type) {
5073 case MONO_TYPE_GENERICINST: {
5074 MonoGenericClass *gklass = t->data.generic_class;
5075 MonoGenericInst *ginst = gklass->context.class_inst;
5077 if (ginst) {
5078 for (i = 0; i < ginst->type_argc; ++i) {
5079 if (check_type_depth (ginst->type_argv [i], depth + 1))
5080 return TRUE;
5083 break;
5085 default:
5086 break;
5089 return FALSE;
5092 static void
5093 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
5096 * add_generic_class:
5098 * Add all methods of a generic class.
5100 static void
5101 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
5103 MonoMethod *method;
5104 MonoClassField *field;
5105 gpointer iter;
5106 gboolean use_gsharedvt = FALSE;
5108 if (!acfg->ginst_hash)
5109 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5111 mono_class_init_internal (klass);
5113 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
5114 return;
5116 if (has_type_vars (klass))
5117 return;
5119 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
5120 return;
5122 if (mono_class_has_failure (klass))
5123 return;
5125 if (!acfg->ginst_hash)
5126 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5128 if (g_hash_table_lookup (acfg->ginst_hash, klass))
5129 return;
5131 if (check_type_depth (m_class_get_byval_arg (klass), 0))
5132 return;
5134 if (acfg->aot_opts.log_generics) {
5135 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
5136 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
5137 g_free (s);
5140 g_hash_table_insert (acfg->ginst_hash, klass, klass);
5143 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
5144 * Enable this only for some classes since gsharedvt might not support all methods.
5146 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) &&
5147 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
5148 use_gsharedvt = TRUE;
5150 iter = NULL;
5151 while ((method = mono_class_get_methods (klass, &iter))) {
5152 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
5154 * This is partial sharing, and we can't handle it yet
5156 continue;
5159 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
5160 /* Already added */
5161 add_types_from_method_header (acfg, method);
5162 continue;
5165 if (method->is_generic)
5166 /* FIXME: */
5167 continue;
5170 * FIXME: Instances which are referenced by these methods are not added,
5171 * for example Array.Resize<int> for List<int>.Add ().
5173 add_extra_method_with_depth (acfg, method, depth + 1);
5176 iter = NULL;
5177 while ((field = mono_class_get_fields_internal (klass, &iter))) {
5178 if (field->type->type == MONO_TYPE_GENERICINST)
5179 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
5182 if (m_class_is_delegate (klass)) {
5183 method = mono_get_delegate_invoke_internal (klass);
5185 method = mono_marshal_get_delegate_invoke (method, NULL);
5187 if (acfg->aot_opts.log_generics)
5188 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
5190 add_method (acfg, method);
5193 /* Add superclasses */
5194 if (m_class_get_parent (klass))
5195 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
5197 const char *klass_name = m_class_get_name (klass);
5198 const char *klass_name_space = m_class_get_name_space (klass);
5199 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
5201 * For ICollection<T>, add instances of the helper methods
5202 * in Array, since a T[] could be cast to ICollection<T>.
5204 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
5205 (!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"))) {
5206 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5207 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
5208 gpointer iter;
5209 char *name_prefix;
5211 if (!strcmp (klass_name, "IEnumerator`1"))
5212 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
5213 else
5214 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5216 /* Add the T[]/InternalEnumerator class */
5217 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5218 ERROR_DECL (error);
5219 MonoClass *nclass;
5221 iter = NULL;
5222 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5223 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5224 break;
5226 g_assert (nclass);
5227 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5228 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5229 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5232 iter = NULL;
5233 while ((method = mono_class_get_methods (array_class, &iter))) {
5234 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5235 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5237 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5238 add_extra_method_with_depth (acfg, m, depth);
5242 g_free (name_prefix);
5245 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5246 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5247 ERROR_DECL (error);
5248 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5249 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5250 MonoGenericContext ctx;
5251 MonoType *args [16];
5253 memset (&ctx, 0, sizeof (ctx));
5255 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5257 args [0] = m_class_get_byval_arg (tclass);
5258 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5260 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5261 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5263 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5264 MonoClass *gcomparer_inst;
5265 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5266 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5267 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5269 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5273 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5274 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5275 ERROR_DECL (error);
5276 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5277 MonoClass *iface, *gcomparer, *iface_inst;
5278 MonoGenericContext ctx;
5279 MonoType *args [16];
5281 memset (&ctx, 0, sizeof (ctx));
5283 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5284 g_assert (iface);
5285 args [0] = m_class_get_byval_arg (tclass);
5286 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5288 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5289 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5291 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5292 MonoClass *gcomparer_inst;
5293 ERROR_DECL (error);
5295 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5296 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5297 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5298 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5302 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5303 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5304 MonoClass *enum_comparer;
5305 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5306 MonoGenericContext ctx;
5307 MonoType *args [16];
5309 if (m_class_is_enumtype (tclass)) {
5310 MonoClass *enum_comparer_inst;
5311 ERROR_DECL (error);
5313 memset (&ctx, 0, sizeof (ctx));
5314 args [0] = m_class_get_byval_arg (tclass);
5315 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5317 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5318 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5319 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5320 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5324 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5325 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5326 MonoClass *comparer;
5327 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5328 MonoGenericContext ctx;
5329 MonoType *args [16];
5331 if (m_class_is_enumtype (tclass)) {
5332 MonoClass *comparer_inst;
5333 ERROR_DECL (error);
5335 memset (&ctx, 0, sizeof (ctx));
5336 args [0] = m_class_get_byval_arg (tclass);
5337 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5339 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5340 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5341 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5342 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5347 static void
5348 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5350 int i;
5351 MonoGenericContext ctx;
5352 MonoType *args [16];
5354 if (acfg->aot_opts.no_instances)
5355 return;
5357 memset (&ctx, 0, sizeof (ctx));
5359 for (i = 0; i < ninsts; ++i) {
5360 ERROR_DECL (error);
5361 MonoClass *generic_inst;
5362 args [0] = insts [i];
5363 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5364 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5365 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5366 add_generic_class (acfg, generic_inst, force, "");
5370 static void
5371 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5373 ERROR_DECL (error);
5374 MonoMethodHeader *header;
5375 MonoMethodSignature *sig;
5376 int j, depth;
5378 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5380 sig = mono_method_signature_internal (method);
5382 if (sig) {
5383 for (j = 0; j < sig->param_count; ++j)
5384 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5385 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5388 header = mono_method_get_header_checked (method, error);
5390 if (header) {
5391 for (j = 0; j < header->num_locals; ++j)
5392 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5393 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5394 mono_metadata_free_mh (header);
5395 } else {
5396 mono_error_cleanup (error); /* FIXME report the error */
5402 * add_generic_instances:
5404 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5406 static void
5407 add_generic_instances (MonoAotCompile *acfg)
5409 int i;
5410 guint32 token;
5411 MonoMethod *method;
5412 MonoGenericContext *context;
5414 if (acfg->aot_opts.no_instances)
5415 return;
5417 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5418 ERROR_DECL (error);
5419 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5420 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5422 if (!method) {
5423 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5424 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5425 mono_error_cleanup (error);
5426 continue;
5429 if (m_class_get_image (method->klass) != acfg->image)
5430 continue;
5432 context = mono_method_get_context (method);
5434 if (context && ((context->class_inst && context->class_inst->is_open)))
5435 continue;
5438 * For open methods, create an instantiation which can be passed to the JIT.
5439 * FIXME: Handle class_inst as well.
5441 if (context && context->method_inst && context->method_inst->is_open) {
5442 ERROR_DECL (error);
5443 MonoGenericContext shared_context;
5444 MonoGenericInst *inst;
5445 MonoType **type_argv;
5446 int i;
5447 MonoMethod *declaring_method;
5448 gboolean supported = TRUE;
5450 /* Check that the context doesn't contain open constructed types */
5451 if (context->class_inst) {
5452 inst = context->class_inst;
5453 for (i = 0; i < inst->type_argc; ++i) {
5454 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)
5455 continue;
5456 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5457 supported = FALSE;
5460 if (context->method_inst) {
5461 inst = context->method_inst;
5462 for (i = 0; i < inst->type_argc; ++i) {
5463 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)
5464 continue;
5465 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5466 supported = FALSE;
5470 if (!supported)
5471 continue;
5473 memset (&shared_context, 0, sizeof (MonoGenericContext));
5475 inst = context->class_inst;
5476 if (inst) {
5477 type_argv = g_new0 (MonoType*, inst->type_argc);
5478 for (i = 0; i < inst->type_argc; ++i) {
5479 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)
5480 type_argv [i] = mono_get_object_type ();
5481 else
5482 type_argv [i] = inst->type_argv [i];
5485 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5486 g_free (type_argv);
5489 inst = context->method_inst;
5490 if (inst) {
5491 type_argv = g_new0 (MonoType*, inst->type_argc);
5492 for (i = 0; i < inst->type_argc; ++i) {
5493 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)
5494 type_argv [i] = mono_get_object_type ();
5495 else
5496 type_argv [i] = inst->type_argv [i];
5499 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5500 g_free (type_argv);
5503 if (method->is_generic || mono_class_is_gtd (method->klass))
5504 declaring_method = method;
5505 else
5506 declaring_method = mono_method_get_declaring_generic_method (method);
5508 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5509 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5513 * If the method is fully sharable, it was already added in place of its
5514 * generic definition.
5516 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5517 continue;
5520 * FIXME: Partially shared methods are not shared here, so we end up with
5521 * many identical methods.
5523 add_extra_method (acfg, method);
5526 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5527 ERROR_DECL (error);
5528 MonoClass *klass;
5530 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5532 klass = mono_class_get_checked (acfg->image, token, error);
5533 if (!klass || m_class_get_rank (klass)) {
5534 mono_error_cleanup (error);
5535 continue;
5538 add_generic_class (acfg, klass, FALSE, "typespec");
5541 /* Add types of args/locals */
5542 for (i = 0; i < acfg->methods->len; ++i) {
5543 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5544 add_types_from_method_header (acfg, method);
5547 if (acfg->image == mono_defaults.corlib) {
5548 MonoClass *klass;
5549 MonoType *insts [256];
5550 int ninsts = 0;
5552 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5553 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5554 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5555 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5556 MonoType *int32_type = mono_get_int32_type ();
5557 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5558 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5559 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5560 MonoType *object_type = mono_get_object_type ();
5562 insts [ninsts ++] = byte_type;
5563 insts [ninsts ++] = sbyte_type;
5564 insts [ninsts ++] = int16_type;
5565 insts [ninsts ++] = uint16_type;
5566 insts [ninsts ++] = int32_type;
5567 insts [ninsts ++] = uint32_type;
5568 insts [ninsts ++] = int64_type;
5569 insts [ninsts ++] = uint64_type;
5570 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5571 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5572 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5573 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5575 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5576 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5577 if (klass)
5578 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5579 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5580 if (klass)
5581 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5583 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5585 MonoClass *enum_comparer;
5586 MonoType *insts [16];
5587 int ninsts;
5589 ninsts = 0;
5590 insts [ninsts ++] = int32_type;
5591 insts [ninsts ++] = uint32_type;
5592 insts [ninsts ++] = uint16_type;
5593 insts [ninsts ++] = byte_type;
5594 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5595 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5597 ninsts = 0;
5598 insts [ninsts ++] = int16_type;
5599 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5600 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5602 ninsts = 0;
5603 insts [ninsts ++] = sbyte_type;
5604 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5605 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5607 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5608 ninsts = 0;
5609 insts [ninsts ++] = int64_type;
5610 insts [ninsts ++] = uint64_type;
5611 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5614 /* Add instances of the array generic interfaces for primitive types */
5615 /* This will add instances of the InternalArray_ helper methods in Array too */
5616 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5617 if (klass)
5618 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5620 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5621 if (klass)
5622 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5624 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5625 if (klass)
5626 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5629 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5630 * used for all instances of GetGenericValueImpl by the AOT runtime.
5633 ERROR_DECL (error);
5634 MonoGenericContext ctx;
5635 MonoType *args [16];
5636 MonoMethod *get_method;
5637 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5639 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5640 mono_error_assert_ok (error);
5642 if (get_method) {
5643 memset (&ctx, 0, sizeof (ctx));
5644 args [0] = object_type;
5645 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5646 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5647 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5651 /* Same for CompareExchange<T>/Exchange<T> */
5653 MonoGenericContext ctx;
5654 MonoType *args [16];
5655 MonoMethod *m;
5656 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5657 gpointer iter = NULL;
5659 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5660 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5661 ERROR_DECL (error);
5662 memset (&ctx, 0, sizeof (ctx));
5663 args [0] = object_type;
5664 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5665 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5666 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5671 /* Same for Volatile.Read/Write<T> */
5673 MonoGenericContext ctx;
5674 MonoType *args [16];
5675 MonoMethod *m;
5676 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5677 gpointer iter = NULL;
5679 if (volatile_klass) {
5680 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5681 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5682 ERROR_DECL (error);
5683 memset (&ctx, 0, sizeof (ctx));
5684 args [0] = object_type;
5685 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5686 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5687 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5693 /* object[] accessor wrappers. */
5694 for (i = 1; i < 4; ++i) {
5695 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5696 MonoMethod *m;
5698 m = get_method_nofail (obj_array_class, "Get", i, 0);
5699 g_assert (m);
5701 m = mono_marshal_get_array_accessor_wrapper (m);
5702 add_extra_method (acfg, m);
5704 m = get_method_nofail (obj_array_class, "Address", i, 0);
5705 g_assert (m);
5707 m = mono_marshal_get_array_accessor_wrapper (m);
5708 add_extra_method (acfg, m);
5710 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5711 g_assert (m);
5713 m = mono_marshal_get_array_accessor_wrapper (m);
5714 add_extra_method (acfg, m);
5719 static char *
5720 decode_direct_icall_symbol_name_attribute (MonoMethod *method)
5722 ERROR_DECL (error);
5724 int j = 0;
5725 char *symbol_name = NULL;
5727 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
5728 if (mono_error_ok(error) && cattr) {
5729 for (j = 0; j < cattr->num_attrs; j++)
5730 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
5731 break;
5733 if (j < cattr->num_attrs) {
5734 MonoCustomAttrEntry *e = &cattr->attrs [j];
5735 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
5736 if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
5738 * Decode the cattr manually since we can't create objects
5739 * during aot compilation.
5742 /* Skip prolog */
5743 const char *p = ((const char*)e->data) + 2;
5744 int slen = mono_metadata_decode_value (p, &p);
5746 symbol_name = (char *)g_memdup (p, slen + 1);
5747 if (symbol_name)
5748 symbol_name [slen] = 0;
5753 return symbol_name;
5755 static const char*
5756 lookup_external_icall_symbol_name_aot (MonoMethod *method)
5758 g_assert (method_to_external_icall_symbol_name);
5760 gpointer key, value;
5761 if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
5762 return (const char*)value;
5764 char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
5765 g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
5767 return symbol_name;
5770 static const char*
5771 lookup_icall_symbol_name_aot (MonoMethod *method)
5773 const char * symbol_name = mono_lookup_icall_symbol (method);
5774 if (!symbol_name)
5775 symbol_name = lookup_external_icall_symbol_name_aot (method);
5777 return symbol_name;
5780 gboolean
5781 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
5783 gboolean enable_icall = FALSE;
5784 if (cfg->compile_aot)
5785 enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
5786 else
5787 enable_icall = FALSE;
5789 return enable_icall;
5793 * is_direct_callable:
5795 * Return whenever the method identified by JI is directly callable without
5796 * going through the PLT.
5798 static gboolean
5799 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5801 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5802 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5803 if (callee_cfg) {
5804 gboolean direct_callable = TRUE;
5806 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5807 direct_callable = FALSE;
5809 if (direct_callable && (!acfg->llvm || acfg->aot_opts.llvm_disable_self_init) && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5810 direct_callable = FALSE;
5812 if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
5813 direct_callable = FALSE;
5816 // FIXME: Support inflated methods, it asserts in mono_aot_init_gshared_method_this () because the method is not in
5817 // amodule->extra_methods.
5819 if (direct_callable && callee_cfg->method->is_inflated)
5820 direct_callable = FALSE;
5822 if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5823 // FIXME: Maybe call the wrapper directly ?
5824 direct_callable = FALSE;
5826 if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
5827 /* Disable this so all calls go through load_method (), see the
5828 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5829 * mono_debugger_agent_init ().
5831 direct_callable = FALSE;
5834 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
5835 /* sgen does some initialization when the allocator method is created */
5836 direct_callable = FALSE;
5837 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
5838 /* we don't know at compile time whether sgen is concurrent or not */
5839 direct_callable = FALSE;
5841 if (direct_callable)
5842 return TRUE;
5844 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5845 if (acfg->aot_opts.direct_pinvoke)
5846 return TRUE;
5847 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5848 if (acfg->aot_opts.direct_icalls)
5849 return TRUE;
5850 return FALSE;
5853 return FALSE;
5856 #ifdef MONO_ARCH_AOT_SUPPORTED
5857 static const char *
5858 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5860 MonoImage *image = m_class_get_image (method->klass);
5861 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5862 MonoTableInfo *tables = image->tables;
5863 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5864 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5865 guint32 im_cols [MONO_IMPLMAP_SIZE];
5866 char *import;
5868 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5869 if (import != NULL)
5870 return import;
5872 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5873 return NULL;
5875 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5877 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5878 return NULL;
5880 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5882 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5884 return import;
5886 #else
5887 static const char *
5888 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5890 return NULL;
5892 #endif
5894 static gint
5895 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5897 if (a->native_offset == b->native_offset)
5898 return a->il_offset - b->il_offset;
5899 else
5900 return a->native_offset - b->native_offset;
5904 * compute_line_numbers:
5906 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5907 * entry.
5909 static MonoDebugSourceLocation**
5910 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5912 MonoDebugMethodInfo *minfo;
5913 MonoDebugLineNumberEntry *ln_array;
5914 MonoDebugSourceLocation *loc;
5915 int i, prev_line, prev_il_offset;
5916 int *native_to_il_offset = NULL;
5917 MonoDebugSourceLocation **res;
5918 gboolean first;
5920 minfo = mono_debug_lookup_method (method);
5921 if (!minfo)
5922 return NULL;
5923 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5924 if (debug_info->code_size != code_size)
5925 return NULL;
5927 g_assert (code_size);
5929 /* Compute the native->IL offset mapping */
5931 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5932 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5934 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5936 native_to_il_offset = g_new0 (int, code_size + 1);
5938 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5939 int j;
5940 MonoDebugLineNumberEntry *lne = &ln_array [i];
5942 if (i == 0) {
5943 for (j = 0; j < lne->native_offset; ++j)
5944 native_to_il_offset [j] = -1;
5947 if (i < debug_info->num_line_numbers - 1) {
5948 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5950 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5951 native_to_il_offset [j] = lne->il_offset;
5952 } else {
5953 for (j = lne->native_offset; j < code_size; ++j)
5954 native_to_il_offset [j] = lne->il_offset;
5957 g_free (ln_array);
5959 /* Compute the native->line number mapping */
5960 res = g_new0 (MonoDebugSourceLocation*, code_size);
5961 prev_il_offset = -1;
5962 prev_line = -1;
5963 first = TRUE;
5964 for (i = 0; i < code_size; ++i) {
5965 int il_offset = native_to_il_offset [i];
5967 if (il_offset == -1 || il_offset == prev_il_offset)
5968 continue;
5969 prev_il_offset = il_offset;
5970 loc = mono_debug_method_lookup_location (minfo, il_offset);
5971 if (!(loc && loc->source_file))
5972 continue;
5973 if (loc->row == prev_line) {
5974 mono_debug_free_source_location (loc);
5975 continue;
5977 prev_line = loc->row;
5978 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5979 if (first)
5980 /* This will cover the prolog too */
5981 res [0] = loc;
5982 else
5983 res [i] = loc;
5984 first = FALSE;
5986 return res;
5989 static int
5990 get_file_index (MonoAotCompile *acfg, const char *source_file)
5992 int findex;
5994 // FIXME: Free these
5995 if (!acfg->dwarf_ln_filenames)
5996 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5997 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5998 if (!findex) {
5999 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
6000 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
6001 emit_unset_mode (acfg);
6002 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
6004 return findex;
6007 #ifdef TARGET_ARM64
6008 #define INST_LEN 4
6009 #else
6010 #define INST_LEN 1
6011 #endif
6014 * emit_and_reloc_code:
6016 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
6017 * is true, calls are made through the GOT too. This is used for emitting trampolines
6018 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
6019 * since trampolines are needed to make PLT work.
6021 static void
6022 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
6024 int i, pindex, start_index;
6025 GPtrArray *patches;
6026 MonoJumpInfo *patch_info;
6027 MonoDebugSourceLocation **locs = NULL;
6028 gboolean skip, prologue_end = FALSE;
6029 #ifdef MONO_ARCH_AOT_SUPPORTED
6030 gboolean direct_call, external_call;
6031 guint32 got_slot;
6032 const char *direct_call_target = 0;
6033 const char *direct_pinvoke;
6034 #endif
6036 if (acfg->gas_line_numbers && method && debug_info) {
6037 locs = compute_line_numbers (method, code_len, debug_info);
6038 if (!locs) {
6039 int findex = get_file_index (acfg, "<unknown>");
6040 emit_unset_mode (acfg);
6041 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
6045 /* Collect and sort relocations */
6046 patches = g_ptr_array_new ();
6047 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
6048 g_ptr_array_add (patches, patch_info);
6049 g_ptr_array_sort (patches, compare_patches);
6051 start_index = 0;
6052 for (i = 0; i < code_len; i += INST_LEN) {
6053 patch_info = NULL;
6054 for (pindex = start_index; pindex < patches->len; ++pindex) {
6055 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6056 if (patch_info->ip.i >= i)
6057 break;
6060 if (locs && locs [i]) {
6061 MonoDebugSourceLocation *loc = locs [i];
6062 int findex;
6063 const char *options;
6065 findex = get_file_index (acfg, loc->source_file);
6066 emit_unset_mode (acfg);
6067 if (!prologue_end)
6068 options = " prologue_end";
6069 else
6070 options = "";
6071 prologue_end = TRUE;
6072 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
6073 mono_debug_free_source_location (loc);
6076 skip = FALSE;
6077 #ifdef MONO_ARCH_AOT_SUPPORTED
6078 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
6079 start_index = pindex;
6081 switch (patch_info->type) {
6082 case MONO_PATCH_INFO_NONE:
6083 break;
6084 case MONO_PATCH_INFO_GOT_OFFSET: {
6085 int code_size;
6087 arch_emit_got_offset (acfg, code + i, &code_size);
6088 i += code_size - INST_LEN;
6089 skip = TRUE;
6090 patch_info->type = MONO_PATCH_INFO_NONE;
6091 break;
6093 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
6094 int code_size, index;
6095 char *selector = (char *)patch_info->data.target;
6097 if (!acfg->objc_selector_to_index)
6098 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
6099 if (!acfg->objc_selectors)
6100 acfg->objc_selectors = g_ptr_array_new ();
6101 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
6102 if (index)
6103 index --;
6104 else {
6105 index = acfg->objc_selector_index;
6106 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
6107 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
6108 acfg->objc_selector_index ++;
6111 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
6112 i += code_size - INST_LEN;
6113 skip = TRUE;
6114 patch_info->type = MONO_PATCH_INFO_NONE;
6115 break;
6117 default: {
6119 * If this patch is a call, try emitting a direct call instead of
6120 * through a PLT entry. This is possible if the called method is in
6121 * the same assembly and requires no initialization.
6123 direct_call = FALSE;
6124 external_call = FALSE;
6125 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
6126 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6127 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
6129 // Don't compile inflated methods if we're doing dedup
6130 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
6131 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
6132 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
6133 g_free (name);
6135 direct_call = TRUE;
6136 direct_call_target = callee_cfg->asm_symbol;
6137 patch_info->type = MONO_PATCH_INFO_NONE;
6138 acfg->stats.direct_calls ++;
6142 acfg->stats.all_calls ++;
6143 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
6144 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6145 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6146 direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
6147 else
6148 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
6149 if (direct_pinvoke) {
6150 direct_call = TRUE;
6151 g_assert (strlen (direct_pinvoke) < 1000);
6152 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
6155 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
6156 const char *sym = mono_find_jit_icall_info (patch_info->data.jit_icall_id)->c_symbol;
6157 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
6158 /* Call to a C function implementing a jit icall */
6159 direct_call = TRUE;
6160 external_call = TRUE;
6161 g_assert (strlen (sym) < 1000);
6162 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6164 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
6165 MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
6166 const char * const sym = info->c_symbol;
6167 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
6168 /* Call to a jit icall without a wrapper */
6169 direct_call = TRUE;
6170 external_call = TRUE;
6171 g_assert (strlen (sym) < 1000);
6172 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6175 if (direct_call) {
6176 patch_info->type = MONO_PATCH_INFO_NONE;
6177 acfg->stats.direct_calls ++;
6180 if (!got_only && !direct_call) {
6181 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
6182 if (plt_entry) {
6183 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
6184 direct_call = TRUE;
6185 direct_call_target = plt_entry->symbol;
6187 /* Nullify the patch */
6188 patch_info->type = MONO_PATCH_INFO_NONE;
6189 plt_entry->jit_used = TRUE;
6193 if (direct_call) {
6194 int call_size;
6196 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
6197 i += call_size - INST_LEN;
6198 } else {
6199 int code_size;
6201 got_slot = get_got_offset (acfg, FALSE, patch_info);
6203 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
6204 i += code_size - INST_LEN;
6206 skip = TRUE;
6210 #endif /* MONO_ARCH_AOT_SUPPORTED */
6212 if (!skip) {
6213 /* Find next patch */
6214 patch_info = NULL;
6215 for (pindex = start_index; pindex < patches->len; ++pindex) {
6216 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6217 if (patch_info->ip.i >= i)
6218 break;
6221 /* Try to emit multiple bytes at once */
6222 if (pindex < patches->len && patch_info->ip.i > i) {
6223 int limit;
6225 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
6226 if (locs && locs [limit])
6227 break;
6230 emit_code_bytes (acfg, code + i, limit - i);
6231 i = limit - INST_LEN;
6232 } else {
6233 emit_code_bytes (acfg, code + i, INST_LEN);
6238 g_ptr_array_free (patches, TRUE);
6239 g_free (locs);
6243 * sanitize_symbol:
6245 * Return a modified version of S which only includes characters permissible in symbols.
6247 static char*
6248 sanitize_symbol (MonoAotCompile *acfg, char *s)
6250 gboolean process = FALSE;
6251 int i, len;
6252 GString *gs;
6253 char *res;
6255 if (!s)
6256 return s;
6258 len = strlen (s);
6259 for (i = 0; i < len; ++i)
6260 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
6261 process = TRUE;
6262 if (!process)
6263 return s;
6265 gs = g_string_sized_new (len);
6266 for (i = 0; i < len; ++i) {
6267 guint8 c = s [i];
6268 if (c <= 0x7f && (isalnum (c) || c == '_')) {
6269 g_string_append_c (gs, c);
6270 } else if (c > 0x7f) {
6271 /* multi-byte utf8 */
6272 g_string_append_printf (gs, "_0x%x", c);
6273 i ++;
6274 c = s [i];
6275 while (c >> 6 == 0x2) {
6276 g_string_append_printf (gs, "%x", c);
6277 i ++;
6278 c = s [i];
6280 g_string_append_printf (gs, "_");
6281 i --;
6282 } else {
6283 g_string_append_c (gs, '_');
6287 res = mono_mempool_strdup (acfg->mempool, gs->str);
6288 g_string_free (gs, TRUE);
6289 return res;
6292 static char*
6293 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
6295 char *name1, *name2, *cached;
6296 int i, j, len, count;
6297 MonoMethod *cached_method;
6299 name1 = mono_method_full_name (method, TRUE);
6301 #ifdef TARGET_MACH
6302 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6303 if ((!prefix || !*prefix) && name1 [0] == 'L')
6304 prefix = "_";
6305 #endif
6307 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6308 char adjustedPrefix [MAX_SYMBOL_SIZE];
6309 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6310 #endif
6312 len = strlen (name1);
6313 name2 = (char *) g_malloc (strlen (prefix) + len + 16);
6314 memcpy (name2, prefix, strlen (prefix));
6315 j = strlen (prefix);
6316 for (i = 0; i < len; ++i) {
6317 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6318 name2 [j ++] = '_';
6319 } else if (isalnum (name1 [i])) {
6320 name2 [j ++] = name1 [i];
6321 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6322 i += 2;
6323 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6324 name2 [j ++] = '_';
6325 i++;
6326 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6327 } else
6328 name2 [j ++] = '_';
6330 name2 [j] = '\0';
6332 g_free (name1);
6334 count = 0;
6335 while (TRUE) {
6336 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6337 if (!(cached_method && cached_method != method))
6338 break;
6339 sprintf (name2 + j, "_%d", count);
6340 count ++;
6343 cached = g_strdup (name2);
6344 g_hash_table_insert (cache, cached, method);
6346 return name2;
6349 static void
6350 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6352 MonoMethod *method;
6353 int method_index;
6354 guint8 *code;
6355 char *debug_sym = NULL;
6356 char *symbol = NULL;
6357 int func_alignment = AOT_FUNC_ALIGNMENT;
6358 char *export_name;
6360 g_assert (!ignore_cfg (cfg));
6362 method = cfg->orig_method;
6363 code = cfg->native_code;
6365 method_index = get_method_index (acfg, method);
6366 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6368 /* Make the labels local */
6369 emit_section_change (acfg, ".text", 0);
6370 emit_alignment_code (acfg, func_alignment);
6372 if (acfg->global_symbols && acfg->need_no_dead_strip)
6373 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6375 emit_label (acfg, cfg->asm_symbol);
6377 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6379 * Write a C style symbol for every method, this has two uses:
6380 * - it works on platforms where the dwarf debugging info is not
6381 * yet supported.
6382 * - it allows the setting of breakpoints of aot-ed methods.
6385 // Comment out to force dedup to link these symbols and forbid compiling
6386 // in duplicated code. This is an "assert when linking if broken" trick.
6387 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6388 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6389 /*else*/
6390 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6392 cfg->asm_debug_symbol = g_strdup (debug_sym);
6394 if (acfg->need_no_dead_strip)
6395 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6397 // Comment out to force dedup to link these symbols and forbid compiling
6398 // in duplicated code. This is an "assert when linking if broken" trick.
6399 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6400 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6401 /*else*/
6402 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6404 emit_label (acfg, debug_sym);
6407 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6408 if (export_name) {
6409 /* Emit a global symbol for the method */
6410 emit_global_inner (acfg, export_name, TRUE);
6411 emit_label (acfg, export_name);
6414 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6415 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6417 acfg->stats.code_size += cfg->code_len;
6419 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6421 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 ()));
6423 emit_line (acfg);
6425 if (acfg->aot_opts.write_symbols) {
6426 if (debug_sym)
6427 emit_symbol_size (acfg, debug_sym, ".");
6428 else
6429 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6430 g_free (debug_sym);
6433 emit_label (acfg, symbol);
6435 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6437 g_free (symbol);
6441 * encode_patch:
6443 * Encode PATCH_INFO into its disk representation.
6445 static void
6446 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6448 guint8 *p = buf;
6450 switch (patch_info->type) {
6451 case MONO_PATCH_INFO_NONE:
6452 break;
6453 case MONO_PATCH_INFO_IMAGE:
6454 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6455 break;
6456 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6457 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6458 case MONO_PATCH_INFO_GC_NURSERY_START:
6459 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6460 break;
6461 case MONO_PATCH_INFO_SWITCH: {
6462 gpointer *table = (gpointer *)patch_info->data.table->table;
6463 int k;
6465 encode_value (patch_info->data.table->table_size, p, &p);
6466 for (k = 0; k < patch_info->data.table->table_size; k++)
6467 encode_value ((int)(gssize)table [k], p, &p);
6468 break;
6470 case MONO_PATCH_INFO_METHODCONST:
6471 case MONO_PATCH_INFO_METHOD:
6472 case MONO_PATCH_INFO_METHOD_JUMP:
6473 case MONO_PATCH_INFO_METHOD_FTNDESC:
6474 case MONO_PATCH_INFO_ICALL_ADDR:
6475 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6476 case MONO_PATCH_INFO_METHOD_RGCTX:
6477 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6478 encode_method_ref (acfg, patch_info->data.method, p, &p);
6479 break;
6480 case MONO_PATCH_INFO_AOT_JIT_INFO:
6481 case MONO_PATCH_INFO_GET_TLS_TRAMP:
6482 case MONO_PATCH_INFO_SET_TLS_TRAMP:
6483 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
6484 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6485 encode_value (patch_info->data.index, p, &p);
6486 break;
6487 case MONO_PATCH_INFO_JIT_ICALL_ID:
6488 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6489 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
6490 encode_value (patch_info->data.jit_icall_id, p, &p);
6491 break;
6492 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
6493 encode_value (patch_info->data.uindex, p, &p);
6494 break;
6495 case MONO_PATCH_INFO_LDSTR_LIT: {
6496 guint32 len = strlen (patch_info->data.name);
6497 encode_value (len, p, &p);
6498 memcpy (p, patch_info->data.name, len + 1);
6499 p += len + 1;
6500 break;
6502 case MONO_PATCH_INFO_LDSTR: {
6503 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6504 guint32 token = patch_info->data.token->token;
6505 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6506 encode_value (image_index, p, &p);
6507 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6508 break;
6510 case MONO_PATCH_INFO_RVA:
6511 case MONO_PATCH_INFO_DECLSEC:
6512 case MONO_PATCH_INFO_LDTOKEN:
6513 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6514 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6515 encode_value (patch_info->data.token->token, p, &p);
6516 encode_value (patch_info->data.token->has_context, p, &p);
6517 if (patch_info->data.token->has_context)
6518 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6519 break;
6520 case MONO_PATCH_INFO_EXC_NAME: {
6521 MonoClass *ex_class;
6523 ex_class =
6524 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6525 "System", (const char *)patch_info->data.target);
6526 encode_klass_ref (acfg, ex_class, p, &p);
6527 break;
6529 case MONO_PATCH_INFO_R4:
6530 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6531 break;
6532 case MONO_PATCH_INFO_R8:
6533 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6534 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6535 break;
6536 case MONO_PATCH_INFO_VTABLE:
6537 case MONO_PATCH_INFO_CLASS:
6538 case MONO_PATCH_INFO_IID:
6539 case MONO_PATCH_INFO_ADJUSTED_IID:
6540 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6541 break;
6542 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6543 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6544 if (patch_info->data.del_tramp->method) {
6545 encode_value (1, p, &p);
6546 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6547 } else {
6548 encode_value (0, p, &p);
6550 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6551 break;
6552 case MONO_PATCH_INFO_FIELD:
6553 case MONO_PATCH_INFO_SFLDA:
6554 encode_field_info (acfg, patch_info->data.field, p, &p);
6555 break;
6556 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6557 break;
6558 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6559 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6560 break;
6561 case MONO_PATCH_INFO_RGCTX_FETCH:
6562 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6563 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6564 guint32 offset;
6567 * entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
6568 * reference the same klass/method, so encode it only once.
6569 * For patches which refer to got entries, this sharing is done by get_got_offset, but
6570 * these are not got entries.
6572 if (entry->in_mrgctx) {
6573 offset = get_shared_method_ref (acfg, entry->d.method);
6574 } else {
6575 offset = get_shared_klass_ref (acfg, entry->d.klass);
6578 encode_value (offset, p, &p);
6579 g_assert ((int)entry->info_type < 256);
6580 g_assert (entry->data->type < 256);
6581 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6582 encode_patch (acfg, entry->data, p, &p);
6583 break;
6585 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6586 case MONO_PATCH_INFO_AOT_MODULE:
6587 break;
6588 case MONO_PATCH_INFO_SIGNATURE:
6589 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6590 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6591 break;
6592 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6593 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6594 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6595 break;
6596 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6597 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6598 int i;
6600 encode_method_ref (acfg, info->method, p, &p);
6601 encode_value (info->num_entries, p, &p);
6602 for (i = 0; i < info->num_entries; ++i) {
6603 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6605 encode_value (template_->info_type, p, &p);
6606 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6607 case MONO_PATCH_INFO_CLASS:
6608 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6609 break;
6610 case MONO_PATCH_INFO_FIELD:
6611 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6612 break;
6613 default:
6614 g_assert_not_reached ();
6615 break;
6618 break;
6620 case MONO_PATCH_INFO_VIRT_METHOD:
6621 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6622 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6623 break;
6624 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6625 break;
6626 default:
6627 g_warning ("unable to handle jump info %d", patch_info->type);
6628 g_assert_not_reached ();
6631 *endbuf = p;
6634 static void
6635 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6637 guint8 *p = buf;
6638 guint32 pindex, offset;
6639 MonoJumpInfo *patch_info;
6641 encode_value (n_patches, p, &p);
6643 for (pindex = 0; pindex < patches->len; ++pindex) {
6644 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6646 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6647 /* Nothing to do */
6648 continue;
6649 /* This shouldn't allocate a new offset */
6650 offset = lookup_got_offset (acfg, llvm, patch_info);
6651 encode_value (offset, p, &p);
6654 *endbuf = p;
6657 static void
6658 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6660 MonoMethod *method;
6661 int pindex, buf_size, n_patches;
6662 GPtrArray *patches;
6663 MonoJumpInfo *patch_info;
6664 guint8 *p, *buf;
6665 guint32 offset;
6666 gboolean needs_ctx = FALSE;
6668 method = cfg->orig_method;
6670 (void)get_method_index (acfg, method);
6672 /* Sort relocations */
6673 patches = g_ptr_array_new ();
6674 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6675 g_ptr_array_add (patches, patch_info);
6676 if (!acfg->aot_opts.llvm_only)
6677 g_ptr_array_sort (patches, compare_patches);
6679 /**********************/
6680 /* Encode method info */
6681 /**********************/
6683 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6685 guint32 *got_offsets = g_new0 (guint32, patches->len);
6687 n_patches = 0;
6688 for (pindex = 0; pindex < patches->len; ++pindex) {
6689 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6691 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6692 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6693 patch_info->type = MONO_PATCH_INFO_NONE;
6694 /* Nothing to do */
6695 continue;
6698 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6699 /* Stored in a GOT slot initialized at module load time */
6700 patch_info->type = MONO_PATCH_INFO_NONE;
6701 continue;
6704 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6705 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6706 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6707 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6708 /* Stored in a GOT slot initialized at module load time */
6709 patch_info->type = MONO_PATCH_INFO_NONE;
6710 continue;
6713 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6714 /* Calls are made through the PLT */
6715 patch_info->type = MONO_PATCH_INFO_NONE;
6716 continue;
6719 if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
6720 needs_ctx = TRUE;
6722 /* This shouldn't allocate a new offset */
6723 offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
6724 if (offset >= acfg->nshared_got_entries)
6725 got_offsets [n_patches ++] = offset;
6728 if (n_patches)
6729 g_assert (cfg->has_got_slots);
6731 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6732 p = buf = (guint8 *)g_malloc (buf_size);
6734 MonoGenericContext *ctx = mono_method_get_context (cfg->method);
6736 guint8 flags = 0;
6737 if (mono_class_get_cctor (method->klass))
6738 flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
6739 if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
6740 flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
6741 if (n_patches)
6742 flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
6743 if (needs_ctx && ctx)
6744 flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
6745 encode_value (flags, p, &p);
6746 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
6747 encode_klass_ref (acfg, method->klass, p, &p);
6748 if (needs_ctx && ctx)
6749 encode_generic_context (acfg, ctx, p, &p);
6751 if (n_patches) {
6752 encode_value (n_patches, p, &p);
6753 for (int i = 0; i < n_patches; ++i)
6754 encode_value (got_offsets [i], p, &p);
6757 g_ptr_array_free (patches, TRUE);
6758 g_free (got_offsets);
6760 acfg->stats.method_info_size += p - buf;
6762 g_assert (p - buf < buf_size);
6764 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6765 g_free (buf);
6768 static guint32
6769 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6771 guint32 cache_index;
6772 guint32 offset;
6774 /* Reuse the unwind module to canonize and store unwind info entries */
6775 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6777 /* Use +/- 1 to distinguish 0s from missing entries */
6778 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6779 if (offset)
6780 return offset - 1;
6781 else {
6782 guint8 buf [16];
6783 guint8 *p;
6786 * It would be easier to use assembler symbols, but the caller needs an
6787 * offset now.
6789 offset = acfg->unwind_info_offset;
6790 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6791 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6793 p = buf;
6794 encode_value (encoded_len, p, &p);
6796 acfg->unwind_info_offset += encoded_len + (p - buf);
6797 return offset;
6801 static void
6802 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6804 int i, k, buf_size;
6805 guint32 debug_info_size, seq_points_size;
6806 guint8 *code;
6807 MonoMethodHeader *header;
6808 guint8 *p, *buf, *debug_info;
6809 MonoJitInfo *jinfo = cfg->jit_info;
6810 guint32 flags;
6811 gboolean use_unwind_ops = FALSE;
6812 MonoSeqPointInfo *seq_points;
6814 code = cfg->native_code;
6815 header = cfg->header;
6817 if (!acfg->aot_opts.nodebug) {
6818 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6819 } else {
6820 debug_info = NULL;
6821 debug_info_size = 0;
6824 seq_points = cfg->seq_point_info;
6825 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6827 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6828 if (jinfo->has_try_block_holes) {
6829 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6830 buf_size += table->num_holes * 16;
6833 p = buf = (guint8 *)g_malloc (buf_size);
6835 use_unwind_ops = cfg->unwind_ops != NULL;
6837 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);
6839 encode_value (flags, p, &p);
6841 if (use_unwind_ops) {
6842 guint32 encoded_len;
6843 guint8 *encoded;
6844 guint32 unwind_desc;
6846 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6848 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6849 encode_value (unwind_desc, p, &p);
6851 g_free (encoded);
6852 } else {
6853 encode_value (jinfo->unwind_info, p, &p);
6856 /*Encode the number of holes before the number of clauses to make decoding easier*/
6857 if (jinfo->has_try_block_holes) {
6858 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6859 encode_value (table->num_holes, p, &p);
6862 if (jinfo->has_arch_eh_info) {
6864 * In AOT mode, the code length is calculated from the address of the previous method,
6865 * which could include alignment padding, so calculating the start of the epilog as
6866 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6868 encode_value (jinfo->code_size, p, &p);
6871 /* Exception table */
6872 if (cfg->compile_llvm) {
6874 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6875 * since the information is only available to llc. Instead, we let llc save the data
6876 * into the LSDA, and read it from there at runtime.
6878 /* The assembly might be CIL stripped so emit the data ourselves */
6879 if (header->num_clauses)
6880 encode_value (header->num_clauses, p, &p);
6882 for (k = 0; k < header->num_clauses; ++k) {
6883 MonoExceptionClause *clause;
6885 clause = &header->clauses [k];
6887 encode_value (clause->flags, p, &p);
6888 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6889 if (clause->data.catch_class) {
6890 guint8 *buf2, *p2;
6891 int len;
6893 buf2 = (guint8 *)g_malloc (4096);
6894 p2 = buf2;
6895 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6896 len = p2 - buf2;
6897 g_assert (len < 4096);
6898 encode_value (len, p, &p);
6899 memcpy (p, buf2, len);
6900 p += p2 - buf2;
6901 g_free (buf2);
6902 } else {
6903 encode_value (0, p, &p);
6907 /* Emit the IL ranges too, since they might not be available at runtime */
6908 encode_value (clause->try_offset, p, &p);
6909 encode_value (clause->try_len, p, &p);
6910 encode_value (clause->handler_offset, p, &p);
6911 encode_value (clause->handler_len, p, &p);
6913 /* Emit a list of nesting clauses */
6914 for (i = 0; i < header->num_clauses; ++i) {
6915 gint32 cindex1 = k;
6916 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6917 gint32 cindex2 = i;
6918 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6920 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6921 encode_value (i, p, &p);
6923 encode_value (-1, p, &p);
6925 } else {
6926 if (jinfo->num_clauses)
6927 encode_value (jinfo->num_clauses, p, &p);
6929 for (k = 0; k < jinfo->num_clauses; ++k) {
6930 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6932 encode_value (ei->flags, p, &p);
6933 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6934 /* Not used for catch clauses */
6935 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6936 encode_value (ei->exvar_offset, p, &p);
6937 #else
6938 encode_value (ei->exvar_offset, p, &p);
6939 #endif
6941 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6942 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6943 else {
6944 if (ei->data.catch_class) {
6945 guint8 *buf2, *p2;
6946 int len;
6948 buf2 = (guint8 *)g_malloc (4096);
6949 p2 = buf2;
6950 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6951 len = p2 - buf2;
6952 g_assert (len < 4096);
6953 encode_value (len, p, &p);
6954 memcpy (p, buf2, len);
6955 p += p2 - buf2;
6956 g_free (buf2);
6957 } else {
6958 encode_value (0, p, &p);
6962 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6963 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6964 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6968 if (jinfo->has_try_block_holes) {
6969 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6970 for (i = 0; i < table->num_holes; ++i) {
6971 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6972 encode_value (hole->clause, p, &p);
6973 encode_value (hole->length, p, &p);
6974 encode_value (hole->offset, p, &p);
6978 if (jinfo->has_arch_eh_info) {
6979 MonoArchEHJitInfo *eh_info;
6981 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6982 encode_value (eh_info->stack_size, p, &p);
6983 encode_value (eh_info->epilog_size, p, &p);
6986 if (jinfo->has_generic_jit_info) {
6987 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6988 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6989 guint8 *buf2, *p2;
6990 int len;
6992 encode_value (gi->nlocs, p, &p);
6993 if (gi->nlocs) {
6994 for (i = 0; i < gi->nlocs; ++i) {
6995 MonoDwarfLocListEntry *entry = &gi->locations [i];
6997 encode_value (entry->is_reg ? 1 : 0, p, &p);
6998 encode_value (entry->reg, p, &p);
6999 if (!entry->is_reg)
7000 encode_value (entry->offset, p, &p);
7001 if (i == 0)
7002 g_assert (entry->from == 0);
7003 else
7004 encode_value (entry->from, p, &p);
7005 encode_value (entry->to, p, &p);
7007 } else {
7008 if (!cfg->compile_llvm) {
7009 encode_value (gi->has_this ? 1 : 0, p, &p);
7010 encode_value (gi->this_reg, p, &p);
7011 encode_value (gi->this_offset, p, &p);
7016 * Need to encode jinfo->method too, since it is not equal to 'method'
7017 * when using generic sharing.
7019 buf2 = (guint8 *)g_malloc (4096);
7020 p2 = buf2;
7021 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
7022 len = p2 - buf2;
7023 g_assert (len < 4096);
7024 encode_value (len, p, &p);
7025 memcpy (p, buf2, len);
7026 p += p2 - buf2;
7027 g_free (buf2);
7029 if (gsctx && gsctx->is_gsharedvt) {
7030 encode_value (1, p, &p);
7031 } else {
7032 encode_value (0, p, &p);
7036 if (seq_points_size)
7037 p += mono_seq_point_info_write (seq_points, p);
7039 g_assert (debug_info_size < buf_size);
7041 encode_value (debug_info_size, p, &p);
7042 if (debug_info_size) {
7043 memcpy (p, debug_info, debug_info_size);
7044 p += debug_info_size;
7045 g_free (debug_info);
7048 /* GC Map */
7049 if (cfg->gc_map) {
7050 encode_value (cfg->gc_map_size, p, &p);
7051 /* The GC map requires 4 bytes of alignment */
7052 while ((gsize)p % 4)
7053 p ++;
7054 memcpy (p, cfg->gc_map, cfg->gc_map_size);
7055 p += cfg->gc_map_size;
7058 acfg->stats.ex_info_size += p - buf;
7060 g_assert (p - buf < buf_size);
7062 /* Emit info */
7063 /* The GC Map requires 4 byte alignment */
7064 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
7065 g_free (buf);
7068 static guint32
7069 emit_klass_info (MonoAotCompile *acfg, guint32 token)
7071 ERROR_DECL (error);
7072 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
7073 guint8 *p, *buf;
7074 int i, buf_size, res;
7075 gboolean no_special_static, cant_encode;
7076 gpointer iter = NULL;
7078 if (!klass) {
7079 mono_error_cleanup (error);
7081 buf_size = 16;
7083 p = buf = (guint8 *)g_malloc (buf_size);
7085 /* Mark as unusable */
7086 encode_value (-1, p, &p);
7088 res = add_to_blob (acfg, buf, p - buf);
7089 g_free (buf);
7091 return res;
7094 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
7095 p = buf = (guint8 *)g_malloc (buf_size);
7097 g_assert (klass);
7099 mono_class_init_internal (klass);
7101 mono_class_get_nested_types (klass, &iter);
7102 g_assert (m_class_is_nested_classes_inited (klass));
7104 mono_class_setup_vtable (klass);
7107 * Emit all the information which is required for creating vtables so
7108 * the runtime does not need to create the MonoMethod structures which
7109 * take up a lot of space.
7112 no_special_static = !mono_class_has_special_static_fields (klass);
7114 /* Check whenever we have enough info to encode the vtable */
7115 cant_encode = FALSE;
7116 MonoMethod **klass_vtable = m_class_get_vtable (klass);
7117 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7118 MonoMethod *cm = klass_vtable [i];
7120 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
7121 cant_encode = TRUE;
7124 mono_class_has_finalizer (klass);
7125 if (mono_class_has_failure (klass))
7126 cant_encode = TRUE;
7128 if (mono_class_is_gtd (klass) || cant_encode) {
7129 encode_value (-1, p, &p);
7130 } else {
7131 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
7132 encode_value (m_class_get_vtable_size (klass), p, &p);
7133 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);
7134 if (m_class_has_cctor (klass))
7135 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
7136 if (m_class_has_finalize (klass))
7137 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
7139 encode_value (m_class_get_instance_size (klass), p, &p);
7140 encode_value (mono_class_data_size (klass), p, &p);
7141 encode_value (m_class_get_packing_size (klass), p, &p);
7142 encode_value (m_class_get_min_align (klass), p, &p);
7144 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7145 MonoMethod *cm = klass_vtable [i];
7147 if (cm)
7148 encode_method_ref (acfg, cm, p, &p);
7149 else
7150 encode_value (0, p, &p);
7154 acfg->stats.class_info_size += p - buf;
7156 g_assert (p - buf < buf_size);
7157 res = add_to_blob (acfg, buf, p - buf);
7158 g_free (buf);
7160 return res;
7163 static char*
7164 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
7166 char *debug_sym = NULL;
7167 char *prefix;
7169 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
7170 /* Need to add a prefix to create unique symbols */
7171 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
7172 } else {
7173 #if defined(TARGET_WIN32) && defined(TARGET_X86)
7174 prefix = mangle_symbol_alloc ("plt_");
7175 #else
7176 prefix = g_strdup ("plt_");
7177 #endif
7180 switch (ji->type) {
7181 case MONO_PATCH_INFO_METHOD:
7182 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
7183 break;
7184 case MONO_PATCH_INFO_JIT_ICALL_ID:
7185 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7186 break;
7187 case MONO_PATCH_INFO_RGCTX_FETCH:
7188 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
7189 break;
7190 case MONO_PATCH_INFO_ICALL_ADDR:
7191 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
7192 char *s = get_debug_sym (ji->data.method, "", cache);
7194 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
7195 g_free (s);
7196 break;
7198 case MONO_PATCH_INFO_TRAMPOLINE_FUNC_ADDR:
7199 debug_sym = g_strdup_printf ("%s_jit_icall_native_trampoline_func_%li", prefix, ji->data.index);
7200 break;
7201 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
7202 debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%lu", prefix, ji->data.uindex);
7203 break;
7204 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
7205 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7206 break;
7207 default:
7208 break;
7211 g_free (prefix);
7213 return sanitize_symbol (acfg, debug_sym);
7217 * Calls made from AOTed code are routed through a table of jumps similar to the
7218 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
7219 * control to the AOT runtime through a trampoline.
7221 static void
7222 emit_plt (MonoAotCompile *acfg)
7224 int i;
7226 if (acfg->aot_opts.llvm_only) {
7227 g_assert (acfg->plt_offset == 1);
7228 return;
7231 emit_line (acfg);
7233 emit_section_change (acfg, ".text", 0);
7234 emit_alignment_code (acfg, 16);
7235 emit_info_symbol (acfg, "plt", TRUE);
7236 emit_label (acfg, acfg->plt_symbol);
7238 for (i = 0; i < acfg->plt_offset; ++i) {
7239 char *debug_sym = NULL;
7240 MonoPltEntry *plt_entry = NULL;
7242 if (i == 0)
7244 * The first plt entry is unused.
7246 continue;
7248 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7250 debug_sym = plt_entry->debug_sym;
7252 if (acfg->thumb_mixed && !plt_entry->jit_used)
7253 /* Emit only a thumb version */
7254 continue;
7256 /* Skip plt entries not actually called */
7257 if (!plt_entry->jit_used && !plt_entry->llvm_used)
7258 continue;
7260 if (acfg->llvm && !acfg->thumb_mixed) {
7261 emit_label (acfg, plt_entry->llvm_symbol);
7262 if (acfg->llvm) {
7263 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7264 #if defined(TARGET_MACH)
7265 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
7266 #endif
7270 if (debug_sym) {
7271 if (acfg->need_no_dead_strip) {
7272 emit_unset_mode (acfg);
7273 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7275 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7276 emit_label (acfg, debug_sym);
7279 emit_label (acfg, plt_entry->symbol);
7281 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7283 if (debug_sym)
7284 emit_symbol_size (acfg, debug_sym, ".");
7287 if (acfg->thumb_mixed) {
7288 /* Make sure the ARM symbols don't alias the thumb ones */
7289 emit_zero_bytes (acfg, 16);
7292 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
7293 * code.
7295 for (i = 0; i < acfg->plt_offset; ++i) {
7296 char *debug_sym = NULL;
7297 MonoPltEntry *plt_entry = NULL;
7299 if (i == 0)
7300 continue;
7302 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7304 /* Skip plt entries not actually called by LLVM code */
7305 if (!plt_entry->llvm_used)
7306 continue;
7308 if (acfg->aot_opts.write_symbols) {
7309 if (plt_entry->debug_sym)
7310 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7313 if (debug_sym) {
7314 #if defined(TARGET_MACH)
7315 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7316 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7317 #endif
7318 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7319 emit_label (acfg, debug_sym);
7321 fprintf (acfg->fp, "\n.thumb_func\n");
7323 emit_label (acfg, plt_entry->llvm_symbol);
7325 if (acfg->llvm)
7326 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7328 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7330 if (debug_sym) {
7331 emit_symbol_size (acfg, debug_sym, ".");
7332 g_free (debug_sym);
7337 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7339 emit_info_symbol (acfg, "plt_end", TRUE);
7341 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7345 * emit_trampoline_full:
7347 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7348 * create_jit_info_for_trampoline ().
7350 static G_GNUC_UNUSED void
7351 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7353 char start_symbol [MAX_SYMBOL_SIZE];
7354 char end_symbol [MAX_SYMBOL_SIZE];
7355 char symbol [MAX_SYMBOL_SIZE];
7356 guint32 buf_size, info_offset;
7357 MonoJumpInfo *patch_info;
7358 guint8 *buf, *p;
7359 GPtrArray *patches;
7360 char *name;
7361 guint8 *code;
7362 guint32 code_size;
7363 MonoJumpInfo *ji;
7364 GSList *unwind_ops;
7366 g_assert (info);
7368 name = info->name;
7369 code = info->code;
7370 code_size = info->code_size;
7371 ji = info->ji;
7372 unwind_ops = info->unwind_ops;
7374 /* Emit code */
7376 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7378 emit_section_change (acfg, ".text", 0);
7379 emit_global (acfg, start_symbol, TRUE);
7380 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7381 emit_label (acfg, start_symbol);
7383 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7384 emit_label (acfg, symbol);
7387 * The code should access everything through the GOT, so we pass
7388 * TRUE here.
7390 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7392 emit_symbol_size (acfg, start_symbol, ".");
7394 if (emit_tinfo) {
7395 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7396 emit_label (acfg, end_symbol);
7399 /* Emit info */
7401 /* Sort relocations */
7402 patches = g_ptr_array_new ();
7403 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7404 if (patch_info->type != MONO_PATCH_INFO_NONE)
7405 g_ptr_array_add (patches, patch_info);
7406 g_ptr_array_sort (patches, compare_patches);
7408 buf_size = patches->len * 128 + 128;
7409 buf = (guint8 *)g_malloc (buf_size);
7410 p = buf;
7412 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7413 g_assert (p - buf < buf_size);
7414 g_ptr_array_free (patches, TRUE);
7416 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7418 info_offset = add_to_blob (acfg, buf, p - buf);
7420 emit_section_change (acfg, RODATA_SECT, 0);
7421 emit_global (acfg, symbol, FALSE);
7422 emit_label (acfg, symbol);
7424 emit_int32 (acfg, info_offset);
7426 if (emit_tinfo) {
7427 guint8 *encoded;
7428 guint32 encoded_len;
7429 guint32 uw_offset;
7432 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7434 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7435 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7436 g_free (encoded);
7438 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7439 emit_int32 (acfg, uw_offset);
7442 /* Emit debug info */
7443 if (unwind_ops) {
7444 char symbol2 [MAX_SYMBOL_SIZE];
7446 sprintf (symbol, "%s", name);
7447 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7449 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7451 if (acfg->dwarf)
7452 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7455 g_free (buf);
7458 static G_GNUC_UNUSED void
7459 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7461 emit_trampoline_full (acfg, info, TRUE);
7464 static void
7465 emit_trampolines (MonoAotCompile *acfg)
7467 char symbol [MAX_SYMBOL_SIZE];
7468 char end_symbol [MAX_SYMBOL_SIZE];
7469 int i, tramp_got_offset;
7470 int ntype;
7471 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7472 int tramp_type;
7473 #endif
7475 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7476 return;
7477 if (acfg->aot_opts.llvm_only)
7478 return;
7480 g_assert (acfg->image->assembly);
7482 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7483 if (mono_is_corlib_image(acfg->image->assembly->image)) {
7484 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7485 MonoTrampInfo *info;
7488 * Emit the generic trampolines.
7490 * We could save some code by treating the generic trampolines as a wrapper
7491 * method, but that approach has its own complexities, so we choose the simpler
7492 * method.
7494 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7495 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7496 #ifdef DISABLE_REMOTING
7497 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7498 continue;
7499 #endif
7500 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7501 emit_trampoline (acfg, info);
7502 mono_tramp_info_free (info);
7505 /* Emit the exception related code pieces */
7506 mono_arch_get_restore_context (&info, TRUE);
7507 emit_trampoline (acfg, info);
7508 mono_tramp_info_free (info);
7510 mono_arch_get_call_filter (&info, TRUE);
7511 emit_trampoline (acfg, info);
7512 mono_tramp_info_free (info);
7514 mono_arch_get_throw_exception (&info, TRUE);
7515 emit_trampoline (acfg, info);
7516 mono_tramp_info_free (info);
7518 mono_arch_get_rethrow_exception (&info, TRUE);
7519 emit_trampoline (acfg, info);
7520 mono_tramp_info_free (info);
7522 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7523 emit_trampoline (acfg, info);
7524 mono_tramp_info_free (info);
7526 mono_arch_get_throw_corlib_exception (&info, TRUE);
7527 emit_trampoline (acfg, info);
7528 mono_tramp_info_free (info);
7530 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7531 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7532 emit_trampoline (acfg, info);
7533 mono_tramp_info_free (info);
7535 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7536 emit_trampoline (acfg, info);
7537 mono_tramp_info_free (info);
7538 #endif
7540 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7541 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7542 if (info) {
7543 emit_trampoline_full (acfg, info, TRUE);
7545 /* Create a separate out trampoline for more information in stack traces */
7546 info->name = g_strdup ("gsharedvt_out_trampoline");
7547 emit_trampoline_full (acfg, info, TRUE);
7548 mono_tramp_info_free (info);
7550 #endif
7552 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7554 GSList *l = mono_arch_get_trampolines (TRUE);
7556 while (l) {
7557 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7559 emit_trampoline (acfg, info);
7560 l = l->next;
7563 #endif
7565 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7566 int offset;
7568 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7569 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7570 emit_trampoline (acfg, info);
7571 mono_tramp_info_free (info);
7573 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7574 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7575 emit_trampoline (acfg, info);
7576 mono_tramp_info_free (info);
7579 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7580 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7581 emit_trampoline (acfg, info);
7582 mono_tramp_info_free (info);
7583 #endif
7586 GSList *l;
7588 /* delegate_invoke_impl trampolines */
7589 l = mono_arch_get_delegate_invoke_impls ();
7590 while (l) {
7591 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7593 emit_trampoline (acfg, info);
7594 l = l->next;
7598 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
7599 mono_arch_get_interp_to_native_trampoline (&info);
7600 emit_trampoline (acfg, info);
7602 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7603 mono_arch_get_native_to_interp_trampoline (&info);
7604 emit_trampoline (acfg, info);
7605 #endif
7608 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7610 /* Emit trampolines which are numerous */
7613 * These include the following:
7614 * - specific trampolines
7615 * - static rgctx invoke trampolines
7616 * - imt trampolines
7617 * These trampolines have the same code, they are parameterized by GOT
7618 * slots.
7619 * They are defined in this file, in the arch_... routines instead of
7620 * in tramp-<ARCH>.c, since it is easier to do it this way.
7624 * When running in aot-only mode, we can't create specific trampolines at
7625 * runtime, so we create a few, and save them in the AOT file.
7626 * Normal trampolines embed their argument as a literal inside the
7627 * trampoline code, we can't do that here, so instead we embed an offset
7628 * which needs to be added to the trampoline address to get the address of
7629 * the GOT slot which contains the argument value.
7630 * The generated trampolines jump to the generic trampolines using another
7631 * GOT slot, which will be setup by the AOT loader to point to the
7632 * generic trampoline code of the given type.
7636 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7637 * each class).
7640 emit_section_change (acfg, ".text", 0);
7642 tramp_got_offset = acfg->got_offset;
7644 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7645 switch (ntype) {
7646 case MONO_AOT_TRAMP_SPECIFIC:
7647 sprintf (symbol, "specific_trampolines");
7648 break;
7649 case MONO_AOT_TRAMP_STATIC_RGCTX:
7650 sprintf (symbol, "static_rgctx_trampolines");
7651 break;
7652 case MONO_AOT_TRAMP_IMT:
7653 sprintf (symbol, "imt_trampolines");
7654 break;
7655 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7656 sprintf (symbol, "gsharedvt_arg_trampolines");
7657 break;
7658 case MONO_AOT_TRAMP_FTNPTR_ARG:
7659 sprintf (symbol, "ftnptr_arg_trampolines");
7660 break;
7661 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7662 sprintf (symbol, "unbox_arbitrary_trampolines");
7663 break;
7664 default:
7665 g_assert_not_reached ();
7668 sprintf (end_symbol, "%s_e", symbol);
7670 if (acfg->aot_opts.write_symbols)
7671 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7673 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7674 emit_info_symbol (acfg, symbol, TRUE);
7676 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7678 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7679 int tramp_size = 0;
7681 switch (ntype) {
7682 case MONO_AOT_TRAMP_SPECIFIC:
7683 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7684 tramp_got_offset += 2;
7685 break;
7686 case MONO_AOT_TRAMP_STATIC_RGCTX:
7687 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7688 tramp_got_offset += 2;
7689 break;
7690 case MONO_AOT_TRAMP_IMT:
7691 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7692 tramp_got_offset += 1;
7693 break;
7694 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7695 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7696 tramp_got_offset += 2;
7697 break;
7698 case MONO_AOT_TRAMP_FTNPTR_ARG:
7699 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7700 tramp_got_offset += 2;
7701 break;
7702 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7703 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7704 tramp_got_offset += 1;
7705 break;
7706 default:
7707 g_assert_not_reached ();
7709 if (!acfg->trampoline_size [ntype]) {
7710 g_assert (tramp_size);
7711 acfg->trampoline_size [ntype] = tramp_size;
7715 emit_label (acfg, end_symbol);
7716 emit_int32 (acfg, 0);
7719 arch_emit_specific_trampoline_pages (acfg);
7721 /* Reserve some entries at the end of the GOT for our use */
7722 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7725 acfg->got_offset += acfg->num_trampoline_got_entries;
7728 static gboolean
7729 str_begins_with (const char *str1, const char *str2)
7731 int len = strlen (str2);
7732 return strncmp (str1, str2, len) == 0;
7735 void*
7736 mono_aot_readonly_field_override (MonoClassField *field)
7738 ReadOnlyValue *rdv;
7739 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7740 char *p = rdv->name;
7741 int len;
7742 len = strlen (m_class_get_name_space (field->parent));
7743 if (strncmp (p, m_class_get_name_space (field->parent), len))
7744 continue;
7745 p += len;
7746 if (*p++ != '.')
7747 continue;
7748 len = strlen (m_class_get_name (field->parent));
7749 if (strncmp (p, m_class_get_name (field->parent), len))
7750 continue;
7751 p += len;
7752 if (*p++ != '.')
7753 continue;
7754 if (strcmp (p, field->name))
7755 continue;
7756 switch (rdv->type) {
7757 case MONO_TYPE_I1:
7758 return &rdv->value.i1;
7759 case MONO_TYPE_I2:
7760 return &rdv->value.i2;
7761 case MONO_TYPE_I4:
7762 return &rdv->value.i4;
7763 default:
7764 break;
7767 return NULL;
7770 static void
7771 add_readonly_value (MonoAotOptions *opts, const char *val)
7773 ReadOnlyValue *rdv;
7774 const char *fval;
7775 const char *tval;
7776 /* the format of val is:
7777 * namespace.typename.fieldname=type/value
7778 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7780 fval = strrchr (val, '/');
7781 if (!fval) {
7782 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7783 exit (1);
7785 tval = strrchr (val, '=');
7786 if (!tval) {
7787 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7788 exit (1);
7790 rdv = g_new0 (ReadOnlyValue, 1);
7791 rdv->name = (char *)g_malloc0 (tval - val + 1);
7792 memcpy (rdv->name, val, tval - val);
7793 tval++;
7794 fval++;
7795 if (strncmp (tval, "i1", 2) == 0) {
7796 rdv->value.i1 = atoi (fval);
7797 rdv->type = MONO_TYPE_I1;
7798 } else if (strncmp (tval, "i2", 2) == 0) {
7799 rdv->value.i2 = atoi (fval);
7800 rdv->type = MONO_TYPE_I2;
7801 } else if (strncmp (tval, "i4", 2) == 0) {
7802 rdv->value.i4 = atoi (fval);
7803 rdv->type = MONO_TYPE_I4;
7804 } else {
7805 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7806 exit (1);
7808 rdv->next = readonly_values;
7809 readonly_values = rdv;
7812 static gchar *
7813 clean_path (gchar * path)
7815 if (!path)
7816 return NULL;
7818 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7819 return path;
7821 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7822 g_free (path);
7824 return clean;
7827 static const gchar *
7828 wrap_path (const gchar * path)
7830 int len;
7831 if (!path)
7832 return NULL;
7834 // If the string contains no spaces, just return the original string.
7835 if (strstr (path, " ") == NULL)
7836 return path;
7838 // If the string is already wrapped in quotes, return it.
7839 len = strlen (path);
7840 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7841 return path;
7843 // If the string contains spaces, then wrap it in quotes.
7844 gchar *clean = g_strdup_printf ("\"%s\"", path);
7846 return clean;
7849 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7850 static void
7851 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7853 ptrdiff_t len = end-start;
7854 if (len > 0)
7855 g_ptr_array_add (args, g_strndup (start, len));
7858 static GPtrArray *
7859 mono_aot_split_options (const char *aot_options)
7861 enum MonoAotOptionState {
7862 MONO_AOT_OPTION_STATE_DEFAULT,
7863 MONO_AOT_OPTION_STATE_STRING,
7864 MONO_AOT_OPTION_STATE_ESCAPE,
7867 GPtrArray *args = g_ptr_array_new ();
7868 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7869 gchar const *opt_start = aot_options;
7870 gboolean end_of_string = FALSE;
7871 gchar cur;
7873 g_return_val_if_fail (aot_options != NULL, NULL);
7875 while ((cur = *aot_options) != '\0') {
7876 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7877 goto next;
7879 switch (cur) {
7880 case '"':
7881 // If we find a quote, then if we're in the default case then
7882 // it means we've found the start of a string, if not then it
7883 // means we've found the end of the string and should switch
7884 // back to the default case.
7885 switch (state) {
7886 case MONO_AOT_OPTION_STATE_DEFAULT:
7887 state = MONO_AOT_OPTION_STATE_STRING;
7888 break;
7889 case MONO_AOT_OPTION_STATE_STRING:
7890 state = MONO_AOT_OPTION_STATE_DEFAULT;
7891 break;
7892 case MONO_AOT_OPTION_STATE_ESCAPE:
7893 g_assert_not_reached ();
7894 break;
7896 break;
7897 case '\\':
7898 // If we've found an escaping operator, then this means we
7899 // should not process the next character if inside a string.
7900 if (state == MONO_AOT_OPTION_STATE_STRING)
7901 state = MONO_AOT_OPTION_STATE_ESCAPE;
7902 break;
7903 case ',':
7904 // If we're in the default state then this means we've found
7905 // an option, store it for later processing.
7906 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7907 goto new_opt;
7908 break;
7911 next:
7912 aot_options++;
7913 restart:
7914 // If the next character is end of string, then process the last option.
7915 if (*(aot_options) == '\0') {
7916 end_of_string = TRUE;
7917 goto new_opt;
7919 continue;
7921 new_opt:
7922 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7923 opt_start = ++aot_options;
7924 if (end_of_string)
7925 break;
7926 goto restart; // Check for null and continue loop
7929 return args;
7932 static void
7933 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7935 GPtrArray* args;
7937 args = mono_aot_split_options (aot_options ? aot_options : "");
7938 for (int i = 0; i < args->len; ++i) {
7939 const char *arg = (const char *)g_ptr_array_index (args, i);
7941 if (str_begins_with (arg, "outfile=")) {
7942 opts->outfile = g_strdup (arg + strlen ("outfile="));
7943 } else if (str_begins_with (arg, "llvm-outfile=")) {
7944 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7945 } else if (str_begins_with (arg, "temp-path=")) {
7946 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7947 } else if (str_begins_with (arg, "save-temps")) {
7948 opts->save_temps = TRUE;
7949 } else if (str_begins_with (arg, "keep-temps")) {
7950 opts->save_temps = TRUE;
7951 } else if (str_begins_with (arg, "write-symbols")) {
7952 opts->write_symbols = TRUE;
7953 } else if (str_begins_with (arg, "no-write-symbols")) {
7954 opts->write_symbols = FALSE;
7955 // Intentionally undocumented -- one-off experiment
7956 } else if (str_begins_with (arg, "metadata-only")) {
7957 opts->metadata_only = TRUE;
7958 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7959 opts->bind_to_runtime_version = TRUE;
7960 } else if (str_begins_with (arg, "full")) {
7961 opts->mode = MONO_AOT_MODE_FULL;
7962 } else if (str_begins_with (arg, "hybrid")) {
7963 opts->mode = MONO_AOT_MODE_HYBRID;
7964 } else if (str_begins_with (arg, "interp")) {
7965 opts->interp = TRUE;
7966 } else if (str_begins_with (arg, "threads=")) {
7967 opts->nthreads = atoi (arg + strlen ("threads="));
7968 } else if (str_begins_with (arg, "static")) {
7969 opts->static_link = TRUE;
7970 opts->no_dlsym = TRUE;
7971 } else if (str_begins_with (arg, "asmonly")) {
7972 opts->asm_only = TRUE;
7973 } else if (str_begins_with (arg, "asmwriter")) {
7974 opts->asm_writer = TRUE;
7975 } else if (str_begins_with (arg, "nodebug")) {
7976 opts->nodebug = TRUE;
7977 } else if (str_begins_with (arg, "dwarfdebug")) {
7978 opts->dwarf_debug = TRUE;
7979 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7980 } else if (str_begins_with (arg, "nopagetrampolines")) {
7981 opts->use_trampolines_page = FALSE;
7982 } else if (str_begins_with (arg, "ntrampolines=")) {
7983 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7984 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7985 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7986 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7987 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7988 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7989 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7990 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7991 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7992 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
7993 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
7994 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
7995 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
7996 } else if (str_begins_with (arg, "tool-prefix=")) {
7997 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7998 } else if (str_begins_with (arg, "ld-flags=")) {
7999 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
8000 } else if (str_begins_with (arg, "soft-debug")) {
8001 opts->soft_debug = TRUE;
8002 // Intentionally undocumented x2-- deprecated
8003 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
8004 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
8005 } else if (str_begins_with (arg, "gen-seq-points-file")) {
8006 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
8007 } else if (str_begins_with (arg, "msym-dir=")) {
8008 mini_debug_options.no_seq_points_compact_data = FALSE;
8009 opts->gen_msym_dir = TRUE;
8010 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
8011 } else if (str_begins_with (arg, "direct-pinvoke")) {
8012 opts->direct_pinvoke = TRUE;
8013 } else if (str_begins_with (arg, "direct-icalls")) {
8014 opts->direct_icalls = TRUE;
8015 } else if (str_begins_with (arg, "no-direct-calls")) {
8016 opts->no_direct_calls = TRUE;
8017 } else if (str_begins_with (arg, "print-skipped")) {
8018 opts->print_skipped_methods = TRUE;
8019 } else if (str_begins_with (arg, "stats")) {
8020 opts->stats = TRUE;
8021 // Intentionally undocumented-- has no known function other than to debug the compiler
8022 } else if (str_begins_with (arg, "no-instances")) {
8023 opts->no_instances = TRUE;
8024 // Intentionally undocumented x4-- Used for internal debugging of compiler
8025 } else if (str_begins_with (arg, "log-generics")) {
8026 opts->log_generics = TRUE;
8027 } else if (str_begins_with (arg, "log-instances=")) {
8028 opts->log_instances = TRUE;
8029 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
8030 } else if (str_begins_with (arg, "log-instances")) {
8031 opts->log_instances = TRUE;
8032 } else if (str_begins_with (arg, "internal-logfile=")) {
8033 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
8034 } else if (str_begins_with (arg, "dedup-skip")) {
8035 opts->dedup = TRUE;
8036 } else if (str_begins_with (arg, "dedup-include=")) {
8037 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
8038 } else if (str_begins_with (arg, "mtriple=")) {
8039 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
8040 } else if (str_begins_with (arg, "llvm-path=")) {
8041 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
8042 } else if (!strcmp (arg, "try-llvm")) {
8043 // If we can load LLVM, use it
8044 // Note: if you call this function from anywhere but mono_compile_assembly,
8045 // this will only set the try_llvm attribute and not do the probing / set the
8046 // attribute.
8047 opts->try_llvm = TRUE;
8048 } else if (!strcmp (arg, "llvm")) {
8049 opts->llvm = TRUE;
8050 } else if (str_begins_with (arg, "readonly-value=")) {
8051 add_readonly_value (opts, arg + strlen ("readonly-value="));
8052 } else if (str_begins_with (arg, "info")) {
8053 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
8054 exit (0);
8055 // Intentionally undocumented: Used for precise stack maps, which are not available yet
8056 } else if (str_begins_with (arg, "gc-maps")) {
8057 mini_gc_enable_gc_maps_for_aot ();
8058 // Intentionally undocumented: Used for internal debugging
8059 } else if (str_begins_with (arg, "dump")) {
8060 opts->dump_json = TRUE;
8061 } else if (str_begins_with (arg, "llvmonly")) {
8062 opts->mode = MONO_AOT_MODE_FULL;
8063 opts->llvm = TRUE;
8064 opts->llvm_only = TRUE;
8065 } else if (str_begins_with (arg, "data-outfile=")) {
8066 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
8067 } else if (str_begins_with (arg, "profile=")) {
8068 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
8069 } else if (!strcmp (arg, "profile-only")) {
8070 opts->profile_only = TRUE;
8071 } else if (!strcmp (arg, "verbose")) {
8072 opts->verbose = TRUE;
8073 } else if (str_begins_with (arg, "llvmopts=")){
8074 if (opts->llvm_opts) {
8075 char *s = g_strdup_printf ("%s %s", opts->llvm_opts, arg + strlen ("llvmopts="));
8076 g_free (opts->llvm_opts);
8077 opts->llvm_opts = s;
8078 } else {
8079 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
8081 } else if (str_begins_with (arg, "llvmllc=")){
8082 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
8083 } else if (!strcmp (arg, "deterministic")) {
8084 opts->deterministic = TRUE;
8085 } else if (!strcmp (arg, "no-opt")) {
8086 opts->no_opt = TRUE;
8087 } else if (str_begins_with (arg, "clangxx=")) {
8088 opts->clangxx = g_strdup (arg + strlen ("clangxx="));
8089 } else if (str_begins_with (arg, "depfile=")) {
8090 opts->depfile = g_strdup (arg + strlen ("depfile="));
8091 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
8092 printf ("Supported options for --aot:\n");
8093 printf (" asmonly\n");
8094 printf (" bind-to-runtime-version\n");
8095 printf (" bitcode\n");
8096 printf (" data-outfile=\n");
8097 printf (" direct-icalls\n");
8098 printf (" direct-pinvoke\n");
8099 printf (" dwarfdebug\n");
8100 printf (" full\n");
8101 printf (" hybrid\n");
8102 printf (" info\n");
8103 printf (" keep-temps\n");
8104 printf (" llvm\n");
8105 printf (" llvmonly\n");
8106 printf (" llvm-outfile=\n");
8107 printf (" llvm-path=\n");
8108 printf (" msym-dir=\n");
8109 printf (" mtriple\n");
8110 printf (" nimt-trampolines=\n");
8111 printf (" nodebug\n");
8112 printf (" no-direct-calls\n");
8113 printf (" no-write-symbols\n");
8114 printf (" nrgctx-trampolines=\n");
8115 printf (" nrgctx-fetch-trampolines=\n");
8116 printf (" ngsharedvt-trampolines=\n");
8117 printf (" nftnptr-arg-trampolines=\n");
8118 printf (" nunbox-arbitrary-trampolines=\n");
8119 printf (" ntrampolines=\n");
8120 printf (" outfile=\n");
8121 printf (" profile=\n");
8122 printf (" profile-only\n");
8123 printf (" print-skipped-methods\n");
8124 printf (" readonly-value=\n");
8125 printf (" save-temps\n");
8126 printf (" soft-debug\n");
8127 printf (" static\n");
8128 printf (" stats\n");
8129 printf (" temp-path=\n");
8130 printf (" tool-prefix=\n");
8131 printf (" threads=\n");
8132 printf (" write-symbols\n");
8133 printf (" verbose\n");
8134 printf (" no-opt\n");
8135 printf (" llvmopts=\n");
8136 printf (" llvmllc=\n");
8137 printf (" clangxx=\n");
8138 printf (" depfile=\n");
8139 printf (" help/?\n");
8140 exit (0);
8141 } else {
8142 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
8143 exit (1);
8146 g_free ((gpointer) arg);
8149 if (opts->use_trampolines_page) {
8150 opts->ntrampolines = 0;
8151 opts->nrgctx_trampolines = 0;
8152 opts->nimt_trampolines = 0;
8153 opts->ngsharedvt_arg_trampolines = 0;
8154 opts->nftnptr_arg_trampolines = 0;
8155 opts->nunbox_arbitrary_trampolines = 0;
8158 g_ptr_array_free (args, /*free_seg=*/TRUE);
8161 static void
8162 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
8164 MonoMethod *method = (MonoMethod*)key;
8165 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
8166 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
8167 MonoJumpInfoToken *new_ji;
8169 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
8170 new_ji->image = ji->image;
8171 new_ji->token = ji->token;
8172 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
8175 static gboolean
8176 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
8178 if (m_class_get_type_token (klass))
8179 return TRUE;
8180 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))
8181 return TRUE;
8182 if (m_class_get_rank (klass))
8183 return can_encode_class (acfg, m_class_get_element_class (klass));
8184 return FALSE;
8187 static gboolean
8188 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
8190 if (method->wrapper_type) {
8191 switch (method->wrapper_type) {
8192 case MONO_WRAPPER_NONE:
8193 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8194 case MONO_WRAPPER_XDOMAIN_INVOKE:
8195 case MONO_WRAPPER_STFLD:
8196 case MONO_WRAPPER_LDFLD:
8197 case MONO_WRAPPER_LDFLDA:
8198 case MONO_WRAPPER_STELEMREF:
8199 case MONO_WRAPPER_PROXY_ISINST:
8200 case MONO_WRAPPER_ALLOC:
8201 case MONO_WRAPPER_REMOTING_INVOKE:
8202 case MONO_WRAPPER_OTHER:
8203 case MONO_WRAPPER_WRITE_BARRIER:
8204 case MONO_WRAPPER_DELEGATE_INVOKE:
8205 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8206 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8207 case MONO_WRAPPER_SYNCHRONIZED:
8208 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8209 break;
8210 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8211 case MONO_WRAPPER_CASTCLASS: {
8212 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8214 if (info)
8215 return TRUE;
8216 else
8217 return FALSE;
8218 break;
8220 default:
8221 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
8222 return FALSE;
8224 } else {
8225 if (!method->token) {
8226 /* The method is part of a constructed type like Int[,].Set (). */
8227 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
8228 if (m_class_get_rank (method->klass))
8229 return TRUE;
8230 return FALSE;
8234 return TRUE;
8237 static gboolean
8238 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
8240 switch (patch_info->type) {
8241 case MONO_PATCH_INFO_METHOD:
8242 case MONO_PATCH_INFO_METHOD_FTNDESC:
8243 case MONO_PATCH_INFO_METHODCONST:
8244 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
8245 MonoMethod *method = patch_info->data.method;
8247 return can_encode_method (acfg, method);
8249 case MONO_PATCH_INFO_VTABLE:
8250 case MONO_PATCH_INFO_CLASS:
8251 case MONO_PATCH_INFO_IID:
8252 case MONO_PATCH_INFO_ADJUSTED_IID:
8253 if (!can_encode_class (acfg, patch_info->data.klass)) {
8254 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8255 return FALSE;
8257 break;
8258 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
8259 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
8260 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8261 return FALSE;
8263 break;
8265 case MONO_PATCH_INFO_RGCTX_FETCH:
8266 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
8267 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
8269 if (entry->in_mrgctx) {
8270 if (!can_encode_method (acfg, entry->d.method))
8271 return FALSE;
8272 } else {
8273 if (!can_encode_class (acfg, entry->d.klass))
8274 return FALSE;
8276 if (!can_encode_patch (acfg, entry->data))
8277 return FALSE;
8278 break;
8280 default:
8281 break;
8284 return TRUE;
8287 static gboolean
8288 is_concrete_type (MonoType *t)
8290 MonoClass *klass;
8291 int i;
8293 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
8294 return FALSE;
8295 if (t->type == MONO_TYPE_GENERICINST) {
8296 MonoGenericContext *orig_ctx;
8297 MonoGenericInst *inst;
8298 MonoType *arg;
8300 if (!MONO_TYPE_ISSTRUCT (t))
8301 return TRUE;
8302 klass = mono_class_from_mono_type_internal (t);
8303 orig_ctx = &mono_class_get_generic_class (klass)->context;
8305 inst = orig_ctx->class_inst;
8306 if (inst) {
8307 for (i = 0; i < inst->type_argc; ++i) {
8308 arg = mini_get_underlying_type (inst->type_argv [i]);
8309 if (!is_concrete_type (arg))
8310 return FALSE;
8313 inst = orig_ctx->method_inst;
8314 if (inst) {
8315 for (i = 0; i < inst->type_argc; ++i) {
8316 arg = mini_get_underlying_type (inst->type_argv [i]);
8317 if (!is_concrete_type (arg))
8318 return FALSE;
8322 return TRUE;
8325 static MonoMethodSignature*
8326 get_concrete_sig (MonoMethodSignature *sig)
8328 gboolean concrete = TRUE;
8330 if (!sig->has_type_parameters)
8331 return sig;
8333 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8334 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8335 int i;
8337 //printf ("%s\n", mono_signature_full_name (sig));
8339 if (sig->ret->byref)
8340 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8341 else
8342 copy->ret = mini_get_underlying_type (sig->ret);
8343 if (!is_concrete_type (copy->ret))
8344 concrete = FALSE;
8345 for (i = 0; i < sig->param_count; ++i) {
8346 if (sig->params [i]->byref) {
8347 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8348 t = mini_get_underlying_type (t);
8349 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8350 } else {
8351 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8353 if (!is_concrete_type (copy->params [i]))
8354 concrete = FALSE;
8356 copy->has_type_parameters = 0;
8357 if (!concrete)
8358 return NULL;
8359 return copy;
8362 /* LOCKING: Assumes the loader lock is held */
8363 static void
8364 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8366 MonoMethod *wrapper;
8367 gboolean add_in = gsharedvt_in;
8368 gboolean add_out = gsharedvt_out;
8370 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8371 add_in = FALSE;
8372 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8373 add_out = FALSE;
8375 if (!add_in && !add_out)
8376 return;
8378 if (mini_is_gsharedvt_variable_signature (sig))
8379 return;
8381 if (add_in)
8382 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8383 if (add_out)
8384 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8386 sig = get_concrete_sig (sig);
8387 if (!sig)
8388 return;
8389 //printf ("%s\n", mono_signature_full_name (sig));
8391 if (gsharedvt_in) {
8392 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8393 add_extra_method (acfg, wrapper);
8395 if (gsharedvt_out) {
8396 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8397 add_extra_method (acfg, wrapper);
8400 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8401 if (interp_in) {
8402 wrapper = mini_get_interp_in_wrapper (sig);
8403 add_extra_method (acfg, wrapper);
8404 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8406 #endif
8410 * compile_method:
8412 * AOT compile a given method.
8413 * This function might be called by multiple threads, so it must be thread-safe.
8415 static void
8416 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8418 MonoCompile *cfg;
8419 MonoJumpInfo *patch_info;
8420 gboolean skip;
8421 int index, depth;
8422 MonoMethod *wrapped;
8423 gint64 jit_time_start;
8424 JitFlags flags;
8426 if (acfg->aot_opts.metadata_only)
8427 return;
8429 mono_acfg_lock (acfg);
8430 index = get_method_index (acfg, method);
8431 mono_acfg_unlock (acfg);
8433 /* fixme: maybe we can also precompile wrapper methods */
8434 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8435 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8436 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8437 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8438 return;
8441 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8442 return;
8444 wrapped = mono_marshal_method_from_wrapper (method);
8445 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8446 // FIXME: The wrapper should be generic too, but it is not
8447 return;
8449 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8450 return;
8452 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8453 return;
8455 mono_atomic_inc_i32 (&acfg->stats.mcount);
8457 #if 0
8458 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8459 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8460 return;
8462 #endif
8464 //acfg->aot_opts.print_skipped_methods = TRUE;
8467 * Since these methods are the only ones which are compiled with
8468 * AOT support, and they are not used by runtime startup/shutdown code,
8469 * the runtime will not see AOT methods during AOT compilation,so it
8470 * does not need to support them by creating a fake GOT etc.
8472 flags = JIT_FLAG_AOT;
8473 if (mono_aot_mode_is_full (&acfg->aot_opts))
8474 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8475 if (acfg->llvm)
8476 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8477 if (acfg->aot_opts.llvm_only)
8478 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8479 if (acfg->aot_opts.no_direct_calls)
8480 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8481 if (acfg->aot_opts.direct_pinvoke)
8482 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8483 if (acfg->aot_opts.interp)
8484 flags = (JitFlags)(flags | JIT_FLAG_INTERP);
8486 jit_time_start = mono_time_track_start ();
8487 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8488 mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
8490 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8491 if (acfg->aot_opts.print_skipped_methods)
8492 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8493 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8494 return;
8496 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8497 /* Some instances cannot be JITted due to constraints etc. */
8498 if (!method->is_inflated)
8499 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));
8500 /* Let the exception happen at runtime */
8501 return;
8504 if (cfg->disable_aot) {
8505 if (acfg->aot_opts.print_skipped_methods)
8506 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8507 mono_atomic_inc_i32 (&acfg->stats.ocount);
8508 return;
8510 cfg->method_index = index;
8512 /* Nullify patches which need no aot processing */
8513 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8514 switch (patch_info->type) {
8515 case MONO_PATCH_INFO_LABEL:
8516 case MONO_PATCH_INFO_BB:
8517 patch_info->type = MONO_PATCH_INFO_NONE;
8518 break;
8519 default:
8520 break;
8524 /* Collect method->token associations from the cfg */
8525 mono_acfg_lock (acfg);
8526 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8527 mono_acfg_unlock (acfg);
8528 g_hash_table_destroy (cfg->token_info_hash);
8529 cfg->token_info_hash = NULL;
8532 * Check for absolute addresses.
8534 skip = FALSE;
8535 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8536 switch (patch_info->type) {
8537 case MONO_PATCH_INFO_ABS:
8538 /* unable to handle this */
8539 skip = TRUE;
8540 break;
8541 default:
8542 break;
8546 if (skip) {
8547 if (acfg->aot_opts.print_skipped_methods)
8548 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8549 mono_atomic_inc_i32 (&acfg->stats.abscount);
8550 return;
8553 /* Lock for the rest of the code */
8554 mono_acfg_lock (acfg);
8556 if (cfg->gsharedvt)
8557 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8558 else if (cfg->gshared)
8559 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8560 else if (cfg->method->wrapper_type)
8561 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8562 else
8563 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8566 * Check for methods/klasses we can't encode.
8568 skip = FALSE;
8569 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8570 if (!can_encode_patch (acfg, patch_info))
8571 skip = TRUE;
8574 if (skip) {
8575 if (acfg->aot_opts.print_skipped_methods)
8576 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8577 acfg->stats.ocount++;
8578 mono_acfg_unlock (acfg);
8579 return;
8582 if (!cfg->compile_llvm)
8583 acfg->has_jitted_code = TRUE;
8585 if (method->is_inflated && acfg->aot_opts.log_instances) {
8586 if (acfg->instances_logfile)
8587 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8588 else
8589 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8592 /* Adds generic instances referenced by this method */
8594 * The depth is used to avoid infinite loops when generic virtual recursion is
8595 * encountered.
8597 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8598 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8599 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8600 switch (patch_info->type) {
8601 case MONO_PATCH_INFO_RGCTX_FETCH:
8602 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8603 case MONO_PATCH_INFO_METHOD:
8604 case MONO_PATCH_INFO_METHOD_FTNDESC:
8605 case MONO_PATCH_INFO_METHOD_RGCTX: {
8606 MonoMethod *m = NULL;
8608 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8609 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8611 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
8612 m = e->data->data.method;
8613 } else {
8614 m = patch_info->data.method;
8617 if (!m)
8618 break;
8619 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8620 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8621 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8622 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8623 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8624 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8625 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8626 } else {
8627 add_extra_method_with_depth (acfg, m, depth + 1);
8628 add_types_from_method_header (acfg, m);
8631 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8633 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8634 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8636 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8637 add_extra_method_with_depth (acfg, m, depth + 1);
8639 break;
8641 case MONO_PATCH_INFO_VTABLE: {
8642 MonoClass *klass = patch_info->data.klass;
8644 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8645 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8646 break;
8648 case MONO_PATCH_INFO_SFLDA: {
8649 MonoClass *klass = patch_info->data.field->parent;
8651 /* The .cctor needs to run at runtime. */
8652 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))
8653 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8654 break;
8656 default:
8657 break;
8662 /* Determine whenever the method has GOT slots */
8663 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8664 switch (patch_info->type) {
8665 case MONO_PATCH_INFO_GOT_OFFSET:
8666 case MONO_PATCH_INFO_NONE:
8667 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8668 case MONO_PATCH_INFO_GC_NURSERY_START:
8669 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8670 break;
8671 case MONO_PATCH_INFO_IMAGE:
8672 /* The assembly is stored in GOT slot 0 */
8673 if (patch_info->data.image != acfg->image)
8674 cfg->has_got_slots = TRUE;
8675 break;
8676 default:
8677 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8678 cfg->has_got_slots = TRUE;
8679 break;
8683 if (!cfg->has_got_slots)
8684 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8686 /* Add gsharedvt wrappers for signatures used by the method */
8687 if (acfg->aot_opts.llvm_only) {
8688 GSList *l;
8690 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8691 /* These only need out wrappers */
8692 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8694 for (l = cfg->signatures; l; l = l->next) {
8695 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8697 /* These only need in wrappers */
8698 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8701 for (l = cfg->interp_in_signatures; l; l = l->next) {
8702 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8704 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8706 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8707 /* The interpreter uses these wrappers to call aot-ed code */
8708 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8709 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8712 if (cfg->llvm_only)
8713 acfg->stats.llvm_count ++;
8716 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8718 /* Make a copy of the patch info which is in the mempool */
8720 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8722 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8723 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8725 if (!patches)
8726 patches = new_patch_info;
8727 else
8728 patches_end->next = new_patch_info;
8729 patches_end = new_patch_info;
8731 cfg->patch_info = patches;
8733 /* Make a copy of the unwind info */
8735 GSList *l, *unwind_ops;
8736 MonoUnwindOp *op;
8738 unwind_ops = NULL;
8739 for (l = cfg->unwind_ops; l; l = l->next) {
8740 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8741 memcpy (op, l->data, sizeof (MonoUnwindOp));
8742 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8744 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8746 /* Make a copy of the argument/local info */
8748 ERROR_DECL (error);
8749 MonoInst **args, **locals;
8750 MonoMethodSignature *sig;
8751 MonoMethodHeader *header;
8752 int i;
8754 sig = mono_method_signature_internal (method);
8755 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8756 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8757 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8758 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8760 cfg->args = args;
8762 header = mono_method_get_header_checked (method, error);
8763 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8764 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8765 for (i = 0; i < header->num_locals; ++i) {
8766 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8767 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8769 mono_metadata_free_mh (header);
8770 cfg->locals = locals;
8773 /* Free some fields used by cfg to conserve memory */
8774 mono_empty_compile (cfg);
8776 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8778 while (index >= acfg->cfgs_size) {
8779 MonoCompile **new_cfgs;
8780 int new_size;
8782 new_size = acfg->cfgs_size * 2;
8783 new_cfgs = g_new0 (MonoCompile*, new_size);
8784 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8785 g_free (acfg->cfgs);
8786 acfg->cfgs = new_cfgs;
8787 acfg->cfgs_size = new_size;
8789 acfg->cfgs [index] = cfg;
8791 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8793 /* Update global stats while holding a lock. */
8794 mono_update_jit_stats (cfg);
8797 if (cfg->orig_method->wrapper_type)
8798 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8801 mono_acfg_unlock (acfg);
8803 mono_atomic_inc_i32 (&acfg->stats.ccount);
8806 static mono_thread_start_return_t WINAPI
8807 compile_thread_main (gpointer user_data)
8809 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8810 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8811 int i;
8813 ERROR_DECL (error);
8814 MonoInternalThread *internal = mono_thread_internal_current ();
8815 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8816 mono_error_assert_ok (error);
8817 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8818 mono_error_assert_ok (error);
8820 for (i = 0; i < methods->len; ++i)
8821 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8823 return 0;
8826 /* Used by the LLVM backend */
8827 guint32
8828 mono_aot_get_got_offset (MonoJumpInfo *ji)
8830 return get_got_offset (llvm_acfg, TRUE, ji);
8834 * mono_aot_is_shared_got_offset:
8836 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8837 * when the AOT image is loaded.
8839 gboolean
8840 mono_aot_is_shared_got_offset (int offset)
8842 return offset < llvm_acfg->nshared_got_entries;
8845 char*
8846 mono_aot_get_method_name (MonoCompile *cfg)
8848 MonoMethod *method = cfg->orig_method;
8850 /* Use the mangled name if possible */
8851 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
8852 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8853 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8854 return mono_aot_get_mangled_method_name (method);
8857 if (llvm_acfg->aot_opts.static_link)
8858 /* Include the assembly name too to avoid duplicate symbol errors */
8859 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8860 else
8861 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8864 static gboolean
8865 append_mangled_type (GString *s, MonoType *t)
8867 if (t->byref)
8868 g_string_append_printf (s, "b");
8869 switch (t->type) {
8870 case MONO_TYPE_VOID:
8871 g_string_append_printf (s, "void");
8872 break;
8873 case MONO_TYPE_I1:
8874 g_string_append_printf (s, "i1");
8875 break;
8876 case MONO_TYPE_U1:
8877 g_string_append_printf (s, "u1");
8878 break;
8879 case MONO_TYPE_I2:
8880 g_string_append_printf (s, "i2");
8881 break;
8882 case MONO_TYPE_U2:
8883 g_string_append_printf (s, "u2");
8884 break;
8885 case MONO_TYPE_I4:
8886 g_string_append_printf (s, "i4");
8887 break;
8888 case MONO_TYPE_U4:
8889 g_string_append_printf (s, "u4");
8890 break;
8891 case MONO_TYPE_I8:
8892 g_string_append_printf (s, "i8");
8893 break;
8894 case MONO_TYPE_U8:
8895 g_string_append_printf (s, "u8");
8896 break;
8897 case MONO_TYPE_I:
8898 g_string_append_printf (s, "ii");
8899 break;
8900 case MONO_TYPE_U:
8901 g_string_append_printf (s, "ui");
8902 break;
8903 case MONO_TYPE_R4:
8904 g_string_append_printf (s, "fl");
8905 break;
8906 case MONO_TYPE_R8:
8907 g_string_append_printf (s, "do");
8908 break;
8909 case MONO_TYPE_OBJECT:
8910 g_string_append_printf (s, "obj");
8911 break;
8912 default: {
8913 char *fullname = mono_type_full_name (t);
8914 GString *temp;
8915 char *temps;
8916 int i, len;
8919 * Have to create a mangled name which is:
8920 * - a valid symbol
8921 * - unique
8923 temp = g_string_new ("");
8924 len = strlen (fullname);
8925 for (i = 0; i < len; ++i) {
8926 char c = fullname [i];
8927 if (isalnum (c)) {
8928 g_string_append_c (temp, c);
8929 } else if (c == '_') {
8930 g_string_append_c (temp, '_');
8931 g_string_append_c (temp, '_');
8932 } else {
8933 g_string_append_c (temp, '_');
8934 g_string_append_printf (temp, "%x", (int)c);
8937 temps = g_string_free (temp, FALSE);
8938 /* Include the length to avoid different length type names aliasing each other */
8939 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8940 g_free (temps);
8943 if (t->attrs)
8944 g_string_append_printf (s, "_attrs_%d", t->attrs);
8945 return TRUE;
8948 static gboolean
8949 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8951 int i;
8952 gboolean supported;
8954 if (sig->pinvoke)
8955 g_string_append_printf (s, "pinvoke_");
8956 supported = append_mangled_type (s, sig->ret);
8957 if (!supported)
8958 return FALSE;
8959 g_string_append_printf (s, "_");
8960 if (sig->hasthis)
8961 g_string_append_printf (s, "this_");
8962 for (i = 0; i < sig->param_count; ++i) {
8963 supported = append_mangled_type (s, sig->params [i]);
8964 if (!supported)
8965 return FALSE;
8968 return TRUE;
8971 static void
8972 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8974 const char *label;
8976 switch (wrapper_type) {
8977 case MONO_WRAPPER_REMOTING_INVOKE:
8978 label = "remoting_invoke";
8979 break;
8980 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8981 label = "remoting_invoke_check";
8982 break;
8983 case MONO_WRAPPER_XDOMAIN_INVOKE:
8984 label = "remoting_invoke_xdomain";
8985 break;
8986 case MONO_WRAPPER_PROXY_ISINST:
8987 label = "proxy_isinst";
8988 break;
8989 case MONO_WRAPPER_LDFLD:
8990 label = "ldfld";
8991 break;
8992 case MONO_WRAPPER_LDFLDA:
8993 label = "ldflda";
8994 break;
8995 case MONO_WRAPPER_STFLD:
8996 label = "stfld";
8997 break;
8998 case MONO_WRAPPER_ALLOC:
8999 label = "alloc";
9000 break;
9001 case MONO_WRAPPER_WRITE_BARRIER:
9002 label = "write_barrier";
9003 break;
9004 case MONO_WRAPPER_STELEMREF:
9005 label = "stelemref";
9006 break;
9007 case MONO_WRAPPER_OTHER:
9008 label = "unknown";
9009 break;
9010 case MONO_WRAPPER_MANAGED_TO_NATIVE:
9011 label = "man2native";
9012 break;
9013 case MONO_WRAPPER_SYNCHRONIZED:
9014 label = "synch";
9015 break;
9016 case MONO_WRAPPER_MANAGED_TO_MANAGED:
9017 label = "man2man";
9018 break;
9019 case MONO_WRAPPER_CASTCLASS:
9020 label = "castclass";
9021 break;
9022 case MONO_WRAPPER_RUNTIME_INVOKE:
9023 label = "run_invoke";
9024 break;
9025 case MONO_WRAPPER_DELEGATE_INVOKE:
9026 label = "del_inv";
9027 break;
9028 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9029 label = "del_beg_inv";
9030 break;
9031 case MONO_WRAPPER_DELEGATE_END_INVOKE:
9032 label = "del_end_inv";
9033 break;
9034 case MONO_WRAPPER_NATIVE_TO_MANAGED:
9035 label = "native2man";
9036 break;
9037 default:
9038 g_assert_not_reached ();
9041 g_string_append_printf (s, "%s_", label);
9044 static void
9045 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
9047 const char *label;
9049 switch (subtype)
9051 case WRAPPER_SUBTYPE_NONE:
9052 return;
9053 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
9054 label = "elem_addr";
9055 break;
9056 case WRAPPER_SUBTYPE_STRING_CTOR:
9057 label = "str_ctor";
9058 break;
9059 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
9060 label = "virt_stelem";
9061 break;
9062 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
9063 label = "fast_mon_enter";
9064 break;
9065 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
9066 label = "fast_mon_enter_4";
9067 break;
9068 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
9069 label = "fast_monitor_exit";
9070 break;
9071 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
9072 label = "ptr2struct";
9073 break;
9074 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
9075 label = "struct2ptr";
9076 break;
9077 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
9078 label = "castclass_w_cache";
9079 break;
9080 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
9081 label = "isinst_w_cache";
9082 break;
9083 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
9084 label = "run_inv_norm";
9085 break;
9086 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
9087 label = "run_inv_dyn";
9088 break;
9089 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
9090 label = "run_inv_dir";
9091 break;
9092 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
9093 label = "run_inv_vir";
9094 break;
9095 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
9096 label = "icall";
9097 break;
9098 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
9099 label = "native_func_aot";
9100 break;
9101 case WRAPPER_SUBTYPE_PINVOKE:
9102 label = "pinvoke";
9103 break;
9104 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
9105 label = "synch_inner";
9106 break;
9107 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
9108 label = "gshared_in";
9109 break;
9110 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
9111 label = "gshared_out";
9112 break;
9113 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
9114 label = "array_acc";
9115 break;
9116 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
9117 label = "generic_arry_help";
9118 break;
9119 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
9120 label = "del_inv_virt";
9121 break;
9122 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
9123 label = "del_inv_bound";
9124 break;
9125 case WRAPPER_SUBTYPE_INTERP_IN:
9126 label = "interp_in";
9127 break;
9128 case WRAPPER_SUBTYPE_INTERP_LMF:
9129 label = "interp_lmf";
9130 break;
9131 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
9132 label = "gsharedvt_in_sig";
9133 break;
9134 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
9135 label = "gsharedvt_out_sig";
9136 break;
9137 case WRAPPER_SUBTYPE_AOT_INIT:
9138 label = "aot_init";
9139 break;
9140 default:
9141 g_assert_not_reached ();
9144 g_string_append_printf (s, "%s_", label);
9147 static char *
9148 sanitize_mangled_string (const char *input)
9150 GString *s = g_string_new ("");
9152 for (int i=0; input [i] != '\0'; i++) {
9153 char c = input [i];
9154 switch (c) {
9155 case '.':
9156 g_string_append (s, "_dot_");
9157 break;
9158 case ' ':
9159 g_string_append (s, "_");
9160 break;
9161 case '`':
9162 g_string_append (s, "_bt_");
9163 break;
9164 case '<':
9165 g_string_append (s, "_le_");
9166 break;
9167 case '>':
9168 g_string_append (s, "_gt_");
9169 break;
9170 case '/':
9171 g_string_append (s, "_sl_");
9172 break;
9173 case '[':
9174 g_string_append (s, "_lbrack_");
9175 break;
9176 case ']':
9177 g_string_append (s, "_rbrack_");
9178 break;
9179 case '(':
9180 g_string_append (s, "_lparen_");
9181 break;
9182 case '-':
9183 g_string_append (s, "_dash_");
9184 break;
9185 case ')':
9186 g_string_append (s, "_rparen_");
9187 break;
9188 case ',':
9189 g_string_append (s, "_comma_");
9190 break;
9191 case ':':
9192 g_string_append (s, "_colon_");
9193 break;
9194 default:
9195 g_string_append_c (s, c);
9199 return g_string_free (s, FALSE);
9202 static gboolean
9203 append_mangled_klass (GString *s, MonoClass *klass)
9205 char *klass_desc = mono_class_full_name (klass);
9206 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
9207 g_free (klass_desc);
9209 // Success
9210 return TRUE;
9213 static gboolean
9214 append_mangled_method (GString *s, MonoMethod *method);
9216 static gboolean
9217 append_mangled_wrapper (GString *s, MonoMethod *method)
9219 gboolean success = TRUE;
9220 gboolean append_sig = TRUE;
9221 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9222 g_string_append_printf (s, "wrapper_");
9223 /* Most wrappers are in mscorlib */
9224 if (m_class_get_image (method->klass) != mono_get_corlib ())
9225 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9227 if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
9228 append_mangled_wrapper_type (s, method->wrapper_type);
9230 switch (method->wrapper_type) {
9231 case MONO_WRAPPER_REMOTING_INVOKE:
9232 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
9233 case MONO_WRAPPER_XDOMAIN_INVOKE: {
9234 MonoMethod *m = mono_marshal_method_from_wrapper (method);
9235 g_assert (m);
9236 success = success && append_mangled_method (s, m);
9237 break;
9239 case MONO_WRAPPER_PROXY_ISINST:
9240 case MONO_WRAPPER_LDFLD:
9241 case MONO_WRAPPER_LDFLDA:
9242 case MONO_WRAPPER_STFLD: {
9243 g_assert (info);
9244 success = success && append_mangled_klass (s, info->d.proxy.klass);
9245 break;
9247 case MONO_WRAPPER_ALLOC: {
9248 /* The GC name is saved once in MonoAotFileInfo */
9249 g_assert (info->d.alloc.alloc_type != -1);
9250 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
9251 // SlowAlloc, etc
9252 g_string_append_printf (s, "%s_", method->name);
9253 break;
9255 case MONO_WRAPPER_WRITE_BARRIER: {
9256 g_string_append_printf (s, "%s_", method->name);
9257 break;
9259 case MONO_WRAPPER_STELEMREF: {
9260 append_mangled_wrapper_subtype (s, info->subtype);
9261 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
9262 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
9263 break;
9265 case MONO_WRAPPER_OTHER: {
9266 append_mangled_wrapper_subtype (s, info->subtype);
9267 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
9268 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
9269 success = success && append_mangled_klass (s, method->klass);
9270 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
9271 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
9272 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
9273 success = success && append_mangled_method (s, info->d.array_accessor.method);
9274 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
9275 append_mangled_signature (s, info->d.interp_in.sig);
9276 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
9277 append_mangled_signature (s, info->d.gsharedvt.sig);
9278 append_sig = FALSE;
9279 } else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
9280 append_mangled_signature (s, info->d.gsharedvt.sig);
9281 append_sig = FALSE;
9282 } else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
9283 g_string_append_printf (s, "%s", method->name);
9284 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
9285 g_string_append_printf (s, "%s_%d_", m_class_get_image (method->klass)->assembly->aname.name, info->d.aot_init.subtype);
9286 append_sig = FALSE;
9288 break;
9290 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
9291 append_mangled_wrapper_subtype (s, info->subtype);
9292 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
9293 const char *name = method->name;
9294 const char *prefix = "__icall_wrapper_";
9295 if (strstr (name, prefix) == name)
9296 name += strlen (prefix);
9297 g_string_append_printf (s, "%s", name);
9298 append_sig = FALSE;
9299 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
9300 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9301 } else {
9302 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
9303 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9305 break;
9307 case MONO_WRAPPER_SYNCHRONIZED: {
9308 MonoMethod *m;
9310 m = mono_marshal_method_from_wrapper (method);
9311 g_assert (m);
9312 g_assert (m != method);
9313 success = success && append_mangled_method (s, m);
9314 break;
9316 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
9317 append_mangled_wrapper_subtype (s, info->subtype);
9319 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
9320 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
9321 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
9322 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
9323 success = success && append_mangled_method (s, info->d.string_ctor.method);
9324 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
9325 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
9326 } else {
9327 success = FALSE;
9329 break;
9331 case MONO_WRAPPER_CASTCLASS: {
9332 append_mangled_wrapper_subtype (s, info->subtype);
9333 break;
9335 case MONO_WRAPPER_RUNTIME_INVOKE: {
9336 append_mangled_wrapper_subtype (s, info->subtype);
9337 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
9338 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
9339 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
9340 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
9341 break;
9343 case MONO_WRAPPER_DELEGATE_INVOKE:
9344 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9345 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
9346 if (method->is_inflated) {
9347 /* These wrappers are identified by their class */
9348 g_string_append_printf (s, "i_");
9349 success = success && append_mangled_klass (s, method->klass);
9350 } else {
9351 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9353 g_string_append_printf (s, "u_");
9354 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
9355 append_mangled_wrapper_subtype (s, info->subtype);
9356 g_string_append_printf (s, "u_sigstart");
9358 break;
9360 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
9361 g_assert (info);
9362 success = success && append_mangled_method (s, info->d.native_to_managed.method);
9363 success = success && append_mangled_klass (s, method->klass);
9364 break;
9366 default:
9367 g_assert_not_reached ();
9369 if (success && append_sig)
9370 success = append_mangled_signature (s, mono_method_signature_internal (method));
9371 return success;
9374 static void
9375 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
9377 int i;
9379 for (i = 0; i < ginst->type_argc; ++i) {
9380 if (i > 0)
9381 g_string_append (str, ", ");
9382 MonoType *type = ginst->type_argv [i];
9383 switch (type->type) {
9384 case MONO_TYPE_VAR:
9385 case MONO_TYPE_MVAR: {
9386 MonoType *constraint = NULL;
9387 if (type->data.generic_param)
9388 constraint = type->data.generic_param->gshared_constraint;
9389 if (constraint) {
9390 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9391 g_string_append (str, "gshared:");
9392 mono_type_get_desc (str, constraint, TRUE);
9393 break;
9395 // Else falls through to common case
9397 default:
9398 mono_type_get_desc (str, type, TRUE);
9403 static void
9404 append_mangled_context (GString *str, MonoGenericContext *context)
9406 GString *res = g_string_new ("");
9408 g_string_append_printf (res, "gens_");
9409 g_string_append (res, "00");
9411 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9412 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9413 g_assert (good);
9415 if (context->class_inst)
9416 append_mangled_ginst (res, context->class_inst);
9417 if (context->method_inst) {
9418 if (context->class_inst)
9419 g_string_append (res, "11");
9420 append_mangled_ginst (res, context->method_inst);
9422 g_string_append_printf (str, "gens_%s", res->str);
9423 g_free (res);
9426 static gboolean
9427 append_mangled_method (GString *s, MonoMethod *method)
9429 if (method->wrapper_type)
9430 return append_mangled_wrapper (s, method);
9432 if (method->is_inflated) {
9433 g_string_append_printf (s, "inflated_");
9434 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9435 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9437 append_mangled_context (s, &imethod->context);
9438 g_string_append_printf (s, "_declared_by_%s_", m_class_get_image (imethod->declaring->klass)->assembly->aname.name);
9439 append_mangled_method (s, imethod->declaring);
9440 } else if (method->is_generic) {
9441 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9443 g_string_append_printf (s, "generic_");
9444 append_mangled_klass (s, method->klass);
9445 g_string_append_printf (s, "_%s_", method->name);
9447 MonoGenericContainer *container = mono_method_get_generic_container (method);
9448 g_string_append_printf (s, "_");
9449 append_mangled_context (s, &container->context);
9451 return append_mangled_signature (s, mono_method_signature_internal (method));
9452 } else {
9453 g_string_append_printf (s, "%s", m_class_get_image (method->klass)->assembly->aname.name);
9454 append_mangled_klass (s, method->klass);
9455 g_string_append_printf (s, "_%s_", method->name);
9456 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9457 g_string_free (s, TRUE);
9458 return FALSE;
9462 return TRUE;
9466 * mono_aot_get_mangled_method_name:
9468 * Return a unique mangled name for METHOD, or NULL.
9470 char*
9471 mono_aot_get_mangled_method_name (MonoMethod *method)
9473 // FIXME: use static cache (mempool?)
9474 // We call this a *lot*
9476 GString *s = g_string_new ("aot_");
9477 if (!append_mangled_method (s, method)) {
9478 g_string_free (s, TRUE);
9479 return NULL;
9480 } else {
9481 char *out = g_string_free (s, FALSE);
9482 // Scrub method and class names
9483 char *cleaned = sanitize_mangled_string (out);
9484 g_free (out);
9485 return cleaned;
9489 gboolean
9490 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9492 return is_direct_callable (llvm_acfg, NULL, patch_info);
9495 void
9496 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9498 MonoPltEntry *plt_entry;
9500 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9501 plt_entry->llvm_used = FALSE;
9504 char*
9505 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9507 const char *sym = NULL;
9509 if (llvm_acfg->aot_opts.direct_icalls) {
9510 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9511 /* Call to a C function implementing a jit icall */
9512 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9513 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9514 MonoMethod *method = (MonoMethod *)data;
9515 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9516 sym = lookup_icall_symbol_name_aot (method);
9517 else if (llvm_acfg->aot_opts.direct_pinvoke)
9518 sym = get_pinvoke_import (llvm_acfg, method);
9519 } else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
9520 MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
9521 char const * const name = info->c_symbol;
9522 if (name && info->func == info->wrapper)
9523 sym = name;
9525 if (sym)
9526 return g_strdup (sym);
9528 return NULL;
9531 char*
9532 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9534 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9535 MonoPltEntry *plt_entry;
9536 const char *sym = NULL;
9538 ji->type = type;
9539 ji->data.target = data;
9541 if (!can_encode_patch (llvm_acfg, ji))
9542 return NULL;
9544 if (llvm_acfg->aot_opts.direct_icalls) {
9545 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9546 /* Call to a C function implementing a jit icall */
9547 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9548 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9549 MonoMethod *method = (MonoMethod *)data;
9550 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9551 sym = lookup_icall_symbol_name_aot (method);
9553 if (sym)
9554 return g_strdup (sym);
9557 plt_entry = get_plt_entry (llvm_acfg, ji);
9558 plt_entry->llvm_used = TRUE;
9560 #if defined(TARGET_MACH)
9561 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9562 #else
9563 return g_strdup (plt_entry->llvm_symbol);
9564 #endif
9568 mono_aot_get_method_index (MonoMethod *method)
9570 g_assert (llvm_acfg);
9571 return get_method_index (llvm_acfg, method);
9574 MonoJumpInfo*
9575 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9577 MonoJumpInfo *res;
9579 mono_acfg_lock (llvm_acfg);
9580 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9581 mono_acfg_unlock (llvm_acfg);
9583 return res;
9586 static int
9587 execute_system (const char * command)
9589 int status = 0;
9591 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9592 // We need an extra set of quotes around the whole command to properly handle commands
9593 // with spaces since internally the command is called through "cmd /c.
9594 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9596 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9597 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9598 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9599 status = _wsystem (wstr);
9600 g_free (wstr);
9602 g_free (quoted_command);
9603 #elif defined (HAVE_SYSTEM)
9604 status = system (command);
9605 #else
9606 g_assert_not_reached ();
9607 #endif
9609 return status;
9612 #ifdef ENABLE_LLVM
9615 * emit_llvm_file:
9617 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9618 * tools.
9620 static gboolean
9621 emit_llvm_file (MonoAotCompile *acfg)
9623 char *command, *opts, *tempbc, *optbc, *output_fname;
9625 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9626 if (acfg->aot_opts.no_opt)
9627 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9628 else
9629 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9630 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9631 } else {
9632 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9633 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9636 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9638 if (acfg->aot_opts.no_opt)
9639 return TRUE;
9641 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9642 * a lot of time, and doesn't seem to save much space.
9643 * The following optimizations cannot be enabled:
9644 * - 'tailcallelim'
9645 * - 'jump-threading' changes our blockaddress references to int constants.
9646 * - 'basiccg' fails because it contains:
9647 * if (CS && !isa<IntrinsicInst>(II)) {
9648 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9649 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9650 * The opt list below was produced by taking the output of:
9651 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9652 * then removing tailcallelim + the global opts.
9653 * strip-dead-prototypes deletes unused intrinsics definitions.
9655 /* The dse pass is disabled because of #13734 and #17616 */
9657 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9658 * // If we have no DataLayout information around, then the size of the store
9659 * // is inferrable from the pointee type. If they are the same type, then
9660 * // we know that the store is safe.
9661 * if (AA.getDataLayout() == 0 &&
9662 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9663 * return OverwriteComplete;
9664 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9666 if (acfg->aot_opts.llvm_only) {
9667 // FIXME: This doesn't work yet
9668 opts = g_strdup ("");
9669 } else {
9670 #if LLVM_API_VERSION > 100
9671 opts = g_strdup ("-O2 -disable-tail-calls -place-safepoints -spp-all-backedges");
9672 #else
9673 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 -place-safepoints -spp-all-backedges");
9674 #endif
9677 if (acfg->aot_opts.llvm_opts) {
9678 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9681 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9682 aot_printf (acfg, "Executing opt: %s\n", command);
9683 if (execute_system (command) != 0)
9684 return FALSE;
9685 g_free (opts);
9687 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9688 /* Nothing else to do */
9689 return TRUE;
9691 if (acfg->aot_opts.llvm_only) {
9692 /* Use the stock clang from xcode */
9693 // FIXME: arch
9694 command = g_strdup_printf ("%s -fexceptions -fpic -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
9696 aot_printf (acfg, "Executing clang: %s\n", command);
9697 if (execute_system (command) != 0)
9698 return FALSE;
9699 return TRUE;
9702 if (!acfg->llc_args)
9703 acfg->llc_args = g_string_new ("");
9705 /* Verbose asm slows down llc greatly */
9706 g_string_append (acfg->llc_args, " -asm-verbose=false");
9708 if (acfg->aot_opts.mtriple)
9709 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9711 #if defined(TARGET_X86_64_WIN32_MSVC) && LLVM_API_VERSION >= 600
9712 if (!acfg->aot_opts.mtriple)
9713 g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
9714 #endif
9716 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9718 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9720 #if LLVM_API_VERSION > 100
9721 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9722 #endif
9724 #if LLVM_API_VERSION > 500 && (defined(TARGET_AMD64) || defined(TARGET_X86))
9725 /* This generates stack adjustments in the middle of functions breaking unwind info */
9726 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9727 #endif
9729 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC)
9730 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9731 #else
9732 if (llvm_acfg->aot_opts.static_link)
9733 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9734 else
9735 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9736 #endif
9738 if (acfg->llvm_owriter) {
9739 /* Emit an object file directly */
9740 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9741 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9742 } else {
9743 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9746 if (acfg->aot_opts.llvm_llc) {
9747 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9750 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9751 g_free (output_fname);
9753 aot_printf (acfg, "Executing llc: %s\n", command);
9755 if (execute_system (command) != 0)
9756 return FALSE;
9757 return TRUE;
9759 #endif
9761 /* Set the skip flag for methods which do not need to be emitted because of dedup */
9762 static void
9763 dedup_skip_methods (MonoAotCompile *acfg)
9765 int oindex, i;
9767 if (acfg->aot_opts.llvm_only)
9768 return;
9770 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9771 MonoCompile *cfg;
9772 MonoMethod *method;
9774 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9776 cfg = acfg->cfgs [i];
9778 if (!cfg)
9779 continue;
9781 method = cfg->orig_method;
9783 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9784 gboolean dedupable = mono_aot_can_dedup (method);
9786 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9787 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9788 mono_dedup_cache_method (acfg, method);
9790 // Don't compile inflated methods if we're in first phase of
9791 // dedup
9793 // In second phase, we emit methods that
9794 // are dedupable. We also emit later methods
9795 // which are referenced by them and added later.
9796 // For this reason, when in the dedup_include mode,
9797 // we never set skip.
9798 if (acfg->aot_opts.dedup)
9799 cfg->skip = TRUE;
9802 // Don't compile anything in this mode
9803 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9804 cfg->skip = TRUE;
9806 // Compile everything in this mode
9807 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9808 cfg->skip = FALSE;
9810 /*if (dedup_collect) {*/
9811 /*char *name = mono_aot_get_mangled_method_name (method);*/
9813 /*if (ignore_cfg (cfg))*/
9814 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9815 /*else*/
9816 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9818 /*g_free (name);*/
9819 /*}*/
9823 static void
9824 emit_code (MonoAotCompile *acfg)
9826 int oindex, i, prev_index;
9827 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9828 char symbol [MAX_SYMBOL_SIZE];
9830 if (acfg->aot_opts.llvm_only)
9831 return;
9833 #if defined(TARGET_POWERPC64)
9834 sprintf (symbol, ".Lgot_addr");
9835 emit_section_change (acfg, ".text", 0);
9836 emit_alignment (acfg, 8);
9837 emit_label (acfg, symbol);
9838 emit_pointer (acfg, acfg->got_symbol);
9839 #endif
9842 * This global symbol is used to compute the address of each method using the
9843 * code_offsets array. It is also used to compute the memory ranges occupied by
9844 * AOT code, so it must be equal to the address of the first emitted method.
9846 emit_section_change (acfg, ".text", 0);
9847 emit_alignment_code (acfg, 8);
9848 emit_info_symbol (acfg, "jit_code_start", TRUE);
9851 * Emit some padding so the local symbol for the first method doesn't have the
9852 * same address as 'methods'.
9854 emit_padding (acfg, 16);
9856 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9857 MonoCompile *cfg;
9858 MonoMethod *method;
9860 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9862 cfg = acfg->cfgs [i];
9864 if (!cfg)
9865 continue;
9867 method = cfg->orig_method;
9869 if (ignore_cfg (cfg))
9870 continue;
9872 /* Emit unbox trampoline */
9873 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9874 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9876 emit_section_change (acfg, ".text", 0);
9878 if (acfg->thumb_mixed && cfg->compile_llvm) {
9879 emit_set_thumb_mode (acfg);
9880 fprintf (acfg->fp, "\n.thumb_func\n");
9883 emit_label (acfg, symbol);
9885 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9887 if (acfg->thumb_mixed && cfg->compile_llvm)
9888 emit_set_arm_mode (acfg);
9890 if (!saved_unbox_info) {
9891 char user_symbol [128];
9892 GSList *unwind_ops;
9893 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9895 emit_label (acfg, "ut_end");
9897 unwind_ops = mono_unwind_get_cie_program ();
9898 save_unwind_info (acfg, user_symbol, unwind_ops);
9899 mono_free_unwind_info (unwind_ops);
9901 /* Save the unbox trampoline size */
9902 #ifdef TARGET_AMD64
9903 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9904 // due to the last instruction being 2 or 5 bytes.
9905 // There is no need to describe interior bytes of instructions
9906 // however, so state the size as if the last instruction is size 1.
9907 emit_int32 (acfg, 5);
9908 #else
9909 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9910 #endif
9911 saved_unbox_info = TRUE;
9915 if (cfg->compile_llvm) {
9916 acfg->stats.llvm_count ++;
9917 } else {
9918 emit_method_code (acfg, cfg);
9922 emit_section_change (acfg, ".text", 0);
9923 emit_alignment_code (acfg, 8);
9924 emit_info_symbol (acfg, "jit_code_end", TRUE);
9926 /* To distinguish it from the next symbol */
9927 emit_padding (acfg, 4);
9930 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9931 * from optimizing them away, since it doesn't see that code_offsets references them.
9932 * JITted methods don't need this since they are referenced using assembler local
9933 * symbols.
9934 * FIXME: This is why write-symbols doesn't work on OSX ?
9936 if (acfg->llvm && acfg->need_no_dead_strip) {
9937 fprintf (acfg->fp, "\n");
9938 for (i = 0; i < acfg->nmethods; ++i) {
9939 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9940 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9945 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9946 * This is PIE code, and the linker can update it if needed.
9949 sprintf (symbol, "method_addresses");
9950 emit_section_change (acfg, ".text", 1);
9951 emit_alignment_code (acfg, 8);
9952 emit_info_symbol (acfg, symbol, TRUE);
9953 if (acfg->aot_opts.write_symbols)
9954 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9955 emit_unset_mode (acfg);
9956 if (acfg->need_no_dead_strip)
9957 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9959 for (i = 0; i < acfg->nmethods; ++i) {
9960 #ifdef MONO_ARCH_AOT_SUPPORTED
9961 int call_size;
9963 if (!ignore_cfg (acfg->cfgs [i])) {
9964 arch_emit_label_address (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9965 } else {
9966 arch_emit_label_address (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9968 #endif
9971 sprintf (symbol, "method_addresses_end");
9972 emit_label (acfg, symbol);
9973 emit_line (acfg);
9975 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9976 sprintf (symbol, "unbox_trampolines");
9977 emit_section_change (acfg, RODATA_SECT, 0);
9978 emit_alignment (acfg, 8);
9979 emit_info_symbol (acfg, symbol, FALSE);
9981 prev_index = -1;
9982 for (i = 0; i < acfg->nmethods; ++i) {
9983 MonoCompile *cfg;
9984 MonoMethod *method;
9985 int index;
9987 cfg = acfg->cfgs [i];
9988 if (ignore_cfg (cfg))
9989 continue;
9991 method = cfg->orig_method;
9993 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9994 index = get_method_index (acfg, method);
9996 emit_int32 (acfg, index);
9997 /* Make sure the table is sorted by index */
9998 g_assert (index > prev_index);
9999 prev_index = index;
10002 sprintf (symbol, "unbox_trampolines_end");
10003 emit_info_symbol (acfg, symbol, FALSE);
10004 emit_int32 (acfg, 0);
10006 /* Emit a separate table with the trampoline addresses/offsets */
10007 sprintf (symbol, "unbox_trampoline_addresses");
10008 emit_section_change (acfg, ".text", 0);
10009 emit_alignment_code (acfg, 8);
10010 emit_info_symbol (acfg, symbol, TRUE);
10012 for (i = 0; i < acfg->nmethods; ++i) {
10013 MonoCompile *cfg;
10014 MonoMethod *method;
10015 int index;
10017 cfg = acfg->cfgs [i];
10018 if (ignore_cfg (cfg))
10019 continue;
10021 method = cfg->orig_method;
10023 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
10024 #ifdef MONO_ARCH_AOT_SUPPORTED
10025 int call_size;
10027 index = get_method_index (acfg, method);
10028 sprintf (symbol, "ut_%d", index);
10030 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
10031 #endif
10034 emit_int32 (acfg, 0);
10037 static void
10038 emit_info (MonoAotCompile *acfg)
10040 int oindex, i;
10041 gint32 *offsets;
10043 offsets = g_new0 (gint32, acfg->nmethods);
10045 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
10046 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
10048 if (acfg->cfgs [i]) {
10049 emit_method_info (acfg, acfg->cfgs [i]);
10050 offsets [i] = acfg->cfgs [i]->method_info_offset;
10051 } else {
10052 offsets [i] = 0;
10056 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10058 g_free (offsets);
10061 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
10063 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
10064 #define mix(a,b,c) { \
10065 a -= c; a ^= rot(c, 4); c += b; \
10066 b -= a; b ^= rot(a, 6); a += c; \
10067 c -= b; c ^= rot(b, 8); b += a; \
10068 a -= c; a ^= rot(c,16); c += b; \
10069 b -= a; b ^= rot(a,19); a += c; \
10070 c -= b; c ^= rot(b, 4); b += a; \
10072 #define mono_final(a,b,c) { \
10073 c ^= b; c -= rot(b,14); \
10074 a ^= c; a -= rot(c,11); \
10075 b ^= a; b -= rot(a,25); \
10076 c ^= b; c -= rot(b,16); \
10077 a ^= c; a -= rot(c,4); \
10078 b ^= a; b -= rot(a,14); \
10079 c ^= b; c -= rot(b,24); \
10082 static guint
10083 mono_aot_type_hash (MonoType *t1)
10085 guint hash = t1->type;
10087 hash |= t1->byref << 6; /* do not collide with t1->type values */
10088 switch (t1->type) {
10089 case MONO_TYPE_VALUETYPE:
10090 case MONO_TYPE_CLASS:
10091 case MONO_TYPE_SZARRAY:
10092 /* check if the distribution is good enough */
10093 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
10094 case MONO_TYPE_PTR:
10095 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
10096 case MONO_TYPE_ARRAY:
10097 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
10098 case MONO_TYPE_GENERICINST:
10099 return ((hash << 5) - hash) ^ 0;
10100 default:
10101 return hash;
10106 * mono_aot_method_hash:
10108 * Return a hash code for methods which only depends on metadata.
10110 guint32
10111 mono_aot_method_hash (MonoMethod *method)
10113 MonoMethodSignature *sig;
10114 MonoClass *klass;
10115 int i, hindex;
10116 int hashes_count;
10117 guint32 *hashes_start, *hashes;
10118 guint32 a, b, c;
10119 MonoGenericInst *class_ginst = NULL;
10120 MonoGenericInst *ginst = NULL;
10122 /* Similar to the hash in mono_method_get_imt_slot () */
10124 sig = mono_method_signature_internal (method);
10126 if (mono_class_is_ginst (method->klass))
10127 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
10128 if (method->is_inflated)
10129 ginst = ((MonoMethodInflated*)method)->context.method_inst;
10131 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
10132 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
10133 hashes = hashes_start;
10135 /* Some wrappers are assigned to random classes */
10136 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
10137 klass = method->klass;
10138 else
10139 klass = mono_defaults.object_class;
10141 if (!method->wrapper_type) {
10142 char *full_name;
10144 if (mono_class_is_ginst (klass))
10145 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
10146 else
10147 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
10149 hashes [0] = mono_metadata_str_hash (full_name);
10150 hashes [1] = 0;
10151 g_free (full_name);
10152 } else {
10153 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
10154 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
10156 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
10157 /* The method name includes a stringified pointer */
10158 hashes [2] = 0;
10159 else
10160 hashes [2] = mono_metadata_str_hash (method->name);
10161 hashes [3] = method->wrapper_type;
10162 hashes [4] = mono_aot_type_hash (sig->ret);
10163 hindex = 5;
10164 for (i = 0; i < sig->param_count; i++) {
10165 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
10167 if (class_ginst) {
10168 for (i = 0; i < class_ginst->type_argc; ++i)
10169 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
10171 if (ginst) {
10172 for (i = 0; i < ginst->type_argc; ++i)
10173 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
10175 g_assert (hindex == hashes_count);
10177 /* Setup internal state */
10178 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
10180 /* Handle most of the hashes */
10181 while (hashes_count > 3) {
10182 a += hashes [0];
10183 b += hashes [1];
10184 c += hashes [2];
10185 mix (a,b,c);
10186 hashes_count -= 3;
10187 hashes += 3;
10190 /* Handle the last 3 hashes (all the case statements fall through) */
10191 switch (hashes_count) {
10192 case 3 : c += hashes [2];
10193 case 2 : b += hashes [1];
10194 case 1 : a += hashes [0];
10195 mono_final (a,b,c);
10196 case 0: /* nothing left to add */
10197 break;
10200 g_free (hashes_start);
10202 return c;
10204 #undef rot
10205 #undef mix
10206 #undef mono_final
10209 * mono_aot_get_array_helper_from_wrapper;
10211 * Get the helper method in Array called by an array wrapper method.
10213 MonoMethod*
10214 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
10216 MonoMethod *m;
10217 const char *prefix;
10218 MonoGenericContext ctx;
10219 MonoType *args [16];
10220 char *mname, *iname, *s, *s2, *helper_name = NULL;
10222 prefix = "System.Collections.Generic";
10223 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
10224 s2 = strstr (s, "`1.");
10225 g_assert (s2);
10226 s2 [0] = '\0';
10227 iname = s;
10228 mname = s2 + 3;
10230 //printf ("X: %s %s\n", iname, mname);
10232 if (!strcmp (iname, "IList"))
10233 helper_name = g_strdup_printf ("InternalArray__%s", mname);
10234 else
10235 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
10236 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
10237 g_assert (m);
10238 g_free (helper_name);
10239 g_free (s);
10241 if (m->is_generic) {
10242 ERROR_DECL (error);
10243 memset (&ctx, 0, sizeof (ctx));
10244 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
10245 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
10246 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
10247 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
10250 return m;
10253 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
10255 typedef struct HashEntry {
10256 guint32 key, value, index;
10257 struct HashEntry *next;
10258 } HashEntry;
10261 * emit_extra_methods:
10263 * Emit methods which are not in the METHOD table, like wrappers.
10265 static void
10266 emit_extra_methods (MonoAotCompile *acfg)
10268 int i, table_size, buf_size;
10269 guint8 *p, *buf;
10270 guint32 *info_offsets;
10271 guint32 hash;
10272 GPtrArray *table;
10273 HashEntry *entry, *new_entry;
10274 int nmethods, max_chain_length;
10275 int *chain_lengths;
10277 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
10279 /* Emit method info */
10280 nmethods = 0;
10281 for (i = 0; i < acfg->extra_methods->len; ++i) {
10282 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10283 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10285 if (ignore_cfg (cfg))
10286 continue;
10288 buf_size = 10240;
10289 p = buf = (guint8 *)g_malloc (buf_size);
10291 nmethods ++;
10293 method = cfg->method_to_register;
10295 encode_method_ref (acfg, method, p, &p);
10297 g_assert ((p - buf) < buf_size);
10299 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10300 g_free (buf);
10304 * Construct a chained hash table for mapping indexes in extra_method_info to
10305 * method indexes.
10307 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
10308 table = g_ptr_array_sized_new (table_size);
10309 for (i = 0; i < table_size; ++i)
10310 g_ptr_array_add (table, NULL);
10311 chain_lengths = g_new0 (int, table_size);
10312 max_chain_length = 0;
10313 for (i = 0; i < acfg->extra_methods->len; ++i) {
10314 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10315 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10316 guint32 key, value;
10318 if (ignore_cfg (cfg))
10319 continue;
10321 key = info_offsets [i];
10322 value = get_method_index (acfg, method);
10324 hash = mono_aot_method_hash (method) % table_size;
10325 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
10327 chain_lengths [hash] ++;
10328 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
10330 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
10331 new_entry->key = key;
10332 new_entry->value = value;
10334 entry = (HashEntry *)g_ptr_array_index (table, hash);
10335 if (entry == NULL) {
10336 new_entry->index = hash;
10337 g_ptr_array_index (table, hash) = new_entry;
10338 } else {
10339 while (entry->next)
10340 entry = entry->next;
10342 entry->next = new_entry;
10343 new_entry->index = table->len;
10344 g_ptr_array_add (table, new_entry);
10347 g_free (chain_lengths);
10349 //printf ("MAX: %d\n", max_chain_length);
10351 buf_size = table->len * 12 + 4;
10352 p = buf = (guint8 *)g_malloc (buf_size);
10353 encode_int (table_size, p, &p);
10355 for (i = 0; i < table->len; ++i) {
10356 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
10358 if (entry == NULL) {
10359 encode_int (0, p, &p);
10360 encode_int (0, p, &p);
10361 encode_int (0, p, &p);
10362 } else {
10363 //g_assert (entry->key > 0);
10364 encode_int (entry->key, p, &p);
10365 encode_int (entry->value, p, &p);
10366 if (entry->next)
10367 encode_int (entry->next->index, p, &p);
10368 else
10369 encode_int (0, p, &p);
10372 g_assert (p - buf <= buf_size);
10374 /* Emit the table */
10375 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
10377 g_free (buf);
10380 * Emit a table reverse mapping method indexes to their index in extra_method_info.
10381 * This is used by mono_aot_find_jit_info ().
10383 buf_size = acfg->extra_methods->len * 8 + 4;
10384 p = buf = (guint8 *)g_malloc (buf_size);
10385 encode_int (acfg->extra_methods->len, p, &p);
10386 for (i = 0; i < acfg->extra_methods->len; ++i) {
10387 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10389 encode_int (get_method_index (acfg, method), p, &p);
10390 encode_int (info_offsets [i], p, &p);
10392 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
10394 g_free (buf);
10395 g_free (info_offsets);
10396 g_ptr_array_free (table, TRUE);
10399 static void
10400 generate_aotid (guint8* aotid)
10402 gpointer rand_handle;
10403 ERROR_DECL (error);
10405 mono_rand_open ();
10406 rand_handle = mono_rand_init (NULL, 0);
10408 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
10409 mono_error_assert_ok (error);
10411 mono_rand_close (rand_handle);
10414 static void
10415 emit_exception_info (MonoAotCompile *acfg)
10417 int i;
10418 gint32 *offsets;
10419 SeqPointData sp_data;
10420 gboolean seq_points_to_file = FALSE;
10422 offsets = g_new0 (gint32, acfg->nmethods);
10423 for (i = 0; i < acfg->nmethods; ++i) {
10424 if (acfg->cfgs [i]) {
10425 MonoCompile *cfg = acfg->cfgs [i];
10427 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10428 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10429 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10430 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10431 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10433 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10434 offsets [i] = cfg->ex_info_offset;
10436 if (method_seq_points_to_file) {
10437 if (!seq_points_to_file) {
10438 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10439 seq_points_to_file = TRUE;
10441 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10443 } else {
10444 offsets [i] = 0;
10448 if (seq_points_to_file) {
10449 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10450 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
10451 char *image_basename = g_path_get_basename (acfg->image->name);
10452 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10453 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
10455 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10456 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10457 exit (1);
10460 mono_seq_point_data_write (&sp_data, aot_file_path);
10461 mono_seq_point_data_free (&sp_data);
10463 g_free (aotid);
10464 g_free (dir);
10465 g_free (image_basename);
10466 g_free (aot_file);
10467 g_free (aot_file_path);
10470 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10471 g_free (offsets);
10474 static void
10475 emit_unwind_info (MonoAotCompile *acfg)
10477 int i;
10478 char symbol [128];
10480 if (acfg->aot_opts.llvm_only) {
10481 g_assert (acfg->unwind_ops->len == 0);
10482 return;
10486 * The unwind info contains a lot of duplicates so we emit each unique
10487 * entry once, and only store the offset from the start of the table in the
10488 * exception info.
10491 sprintf (symbol, "unwind_info");
10492 emit_section_change (acfg, RODATA_SECT, 1);
10493 emit_alignment (acfg, 8);
10494 emit_info_symbol (acfg, symbol, TRUE);
10496 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10497 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10498 guint8 *unwind_info;
10499 guint32 unwind_info_len;
10500 guint8 buf [16];
10501 guint8 *p;
10503 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10505 p = buf;
10506 encode_value (unwind_info_len, p, &p);
10507 emit_bytes (acfg, buf, p - buf);
10508 emit_bytes (acfg, unwind_info, unwind_info_len);
10510 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10514 static void
10515 emit_class_info (MonoAotCompile *acfg)
10517 int i;
10518 gint32 *offsets;
10520 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10521 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10522 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10524 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);
10525 g_free (offsets);
10528 typedef struct ClassNameTableEntry {
10529 guint32 token, index;
10530 struct ClassNameTableEntry *next;
10531 } ClassNameTableEntry;
10533 static void
10534 emit_class_name_table (MonoAotCompile *acfg)
10536 int i, table_size, buf_size;
10537 guint32 token, hash;
10538 MonoClass *klass;
10539 GPtrArray *table;
10540 char *full_name;
10541 guint8 *buf, *p;
10542 ClassNameTableEntry *entry, *new_entry;
10545 * Construct a chained hash table for mapping class names to typedef tokens.
10547 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10548 table = g_ptr_array_sized_new (table_size);
10549 for (i = 0; i < table_size; ++i)
10550 g_ptr_array_add (table, NULL);
10551 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10552 ERROR_DECL (error);
10553 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10554 klass = mono_class_get_checked (acfg->image, token, error);
10555 if (!klass) {
10556 mono_error_cleanup (error);
10557 continue;
10559 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10560 hash = mono_metadata_str_hash (full_name) % table_size;
10561 g_free (full_name);
10563 /* FIXME: Allocate from the mempool */
10564 new_entry = g_new0 (ClassNameTableEntry, 1);
10565 new_entry->token = token;
10567 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10568 if (entry == NULL) {
10569 new_entry->index = hash;
10570 g_ptr_array_index (table, hash) = new_entry;
10571 } else {
10572 while (entry->next)
10573 entry = entry->next;
10575 entry->next = new_entry;
10576 new_entry->index = table->len;
10577 g_ptr_array_add (table, new_entry);
10581 /* Emit the table */
10582 buf_size = table->len * 4 + 4;
10583 p = buf = (guint8 *)g_malloc0 (buf_size);
10585 /* FIXME: Optimize memory usage */
10586 g_assert (table_size < 65000);
10587 encode_int16 (table_size, p, &p);
10588 g_assert (table->len < 65000);
10589 for (i = 0; i < table->len; ++i) {
10590 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10592 if (entry == NULL) {
10593 encode_int16 (0, p, &p);
10594 encode_int16 (0, p, &p);
10595 } else {
10596 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10597 if (entry->next)
10598 encode_int16 (entry->next->index, p, &p);
10599 else
10600 encode_int16 (0, p, &p);
10602 g_free (entry);
10604 g_assert (p - buf <= buf_size);
10605 g_ptr_array_free (table, TRUE);
10607 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10609 g_free (buf);
10612 static void
10613 emit_image_table (MonoAotCompile *acfg)
10615 int i, buf_size;
10616 guint8 *buf, *p;
10619 * The image table is small but referenced in a lot of places.
10620 * So we emit it at once, and reference its elements by an index.
10622 buf_size = acfg->image_table->len * 28 + 4;
10623 for (i = 0; i < acfg->image_table->len; i++) {
10624 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10625 MonoAssemblyName *aname = &image->assembly->aname;
10627 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10630 buf = p = (guint8 *)g_malloc0 (buf_size);
10631 encode_int (acfg->image_table->len, p, &p);
10632 for (i = 0; i < acfg->image_table->len; i++) {
10633 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10634 MonoAssemblyName *aname = &image->assembly->aname;
10636 /* FIXME: Support multi-module assemblies */
10637 g_assert (image->assembly->image == image);
10639 encode_string (image->assembly_name, p, &p);
10640 encode_string (image->guid, p, &p);
10641 encode_string (aname->culture ? aname->culture : "", p, &p);
10642 encode_string ((const char*)aname->public_key_token, p, &p);
10644 while (GPOINTER_TO_UINT (p) % 8 != 0)
10645 p ++;
10647 encode_int (aname->flags, p, &p);
10648 encode_int (aname->major, p, &p);
10649 encode_int (aname->minor, p, &p);
10650 encode_int (aname->build, p, &p);
10651 encode_int (aname->revision, p, &p);
10653 g_assert (p - buf <= buf_size);
10655 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10657 g_free (buf);
10660 static void
10661 emit_weak_field_indexes (MonoAotCompile *acfg)
10663 GHashTable *indexes;
10664 GHashTableIter iter;
10665 gpointer key, value;
10666 int buf_size;
10667 guint8 *buf, *p;
10669 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10670 mono_assembly_init_weak_fields (acfg->image);
10671 indexes = acfg->image->weak_field_indexes;
10672 g_assert (indexes);
10674 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10675 buf = p = (guint8 *)g_malloc0 (buf_size);
10677 encode_int (g_hash_table_size (indexes), p, &p);
10678 g_hash_table_iter_init (&iter, indexes);
10679 while (g_hash_table_iter_next (&iter, &key, &value)) {
10680 guint32 index = GPOINTER_TO_UINT (key);
10681 encode_int (index, p, &p);
10683 g_assert (p - buf <= buf_size);
10685 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10687 g_free (buf);
10690 static void
10691 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10693 int i, first_plt_got_patch = 0, buf_size;
10694 guint8 *p, *buf;
10695 guint32 *got_info_offsets;
10696 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10698 /* Add the patches needed by the PLT to the GOT */
10699 if (!llvm) {
10700 acfg->plt_got_offset_base = acfg->got_offset;
10701 first_plt_got_patch = info->got_patches->len;
10702 for (i = 1; i < acfg->plt_offset; ++i) {
10703 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10705 g_ptr_array_add (info->got_patches, plt_entry->ji);
10707 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10710 acfg->got_offset += acfg->plt_offset;
10714 * FIXME:
10715 * - optimize offsets table.
10716 * - reduce number of exported symbols.
10717 * - emit info for a klass only once.
10718 * - determine when a method uses a GOT slot which is guaranteed to be already
10719 * initialized.
10720 * - clean up and document the code.
10721 * - use String.Empty in class libs.
10724 /* Encode info required to decode shared GOT entries */
10725 buf_size = info->got_patches->len * 128;
10726 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10727 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10728 if (!llvm) {
10729 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10730 /* Unused */
10731 if (acfg->plt_offset)
10732 acfg->plt_got_info_offsets [0] = 0;
10734 for (i = 0; i < info->got_patches->len; ++i) {
10735 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10736 guint8 *p2;
10738 p = buf;
10740 encode_value (ji->type, p, &p);
10741 p2 = p;
10742 encode_patch (acfg, ji, p, &p);
10743 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10744 g_assert (p - buf <= buf_size);
10745 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10747 if (!llvm && i >= first_plt_got_patch)
10748 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10749 acfg->stats.got_info_size += p - buf;
10752 /* Emit got_info_offsets table */
10754 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10755 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);
10758 static void
10759 emit_got (MonoAotCompile *acfg)
10761 char symbol [MAX_SYMBOL_SIZE];
10763 if (acfg->aot_opts.llvm_only)
10764 return;
10766 /* Don't make GOT global so accesses to it don't need relocations */
10767 sprintf (symbol, "%s", acfg->got_symbol);
10769 #ifdef TARGET_MACH
10770 emit_unset_mode (acfg);
10771 fprintf (acfg->fp, ".section __DATA, __bss\n");
10772 emit_alignment (acfg, 8);
10773 if (acfg->llvm)
10774 emit_info_symbol (acfg, "jit_got", FALSE);
10775 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10776 #else
10777 emit_section_change (acfg, ".bss", 0);
10778 emit_alignment (acfg, 8);
10779 if (acfg->aot_opts.write_symbols)
10780 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10781 emit_label (acfg, symbol);
10782 if (acfg->llvm)
10783 emit_info_symbol (acfg, "jit_got", FALSE);
10784 if (acfg->got_offset > 0)
10785 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10786 #endif
10788 sprintf (symbol, "got_end");
10789 emit_label (acfg, symbol);
10792 typedef struct GlobalsTableEntry {
10793 guint32 value, index;
10794 struct GlobalsTableEntry *next;
10795 } GlobalsTableEntry;
10797 #ifdef TARGET_WIN32_MSVC
10798 #define DLL_ENTRY_POINT "DllMain"
10800 static void
10801 emit_library_info (MonoAotCompile *acfg)
10803 // Only include for shared libraries linked directly from generated object.
10804 if (link_shared_library (acfg)) {
10805 char *name = NULL;
10806 char symbol [MAX_SYMBOL_SIZE];
10808 // Ask linker to export all global symbols.
10809 emit_section_change (acfg, ".drectve", 0);
10810 for (guint i = 0; i < acfg->globals->len; ++i) {
10811 name = (char *)g_ptr_array_index (acfg->globals, i);
10812 g_assert (name != NULL);
10813 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10814 emit_string (acfg, symbol);
10817 // Emit DLLMain function, needed by MSVC linker for DLL's.
10818 // NOTE, DllMain should not go into exports above.
10819 emit_section_change (acfg, ".text", 0);
10820 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10821 emit_label (acfg, DLL_ENTRY_POINT);
10823 // Simple implementation of DLLMain, just returning TRUE.
10824 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10825 fprintf (acfg->fp, "movl $1, %%eax\n");
10826 fprintf (acfg->fp, "ret\n");
10828 // Inform linker about our dll entry function.
10829 emit_section_change (acfg, ".drectve", 0);
10830 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10831 return;
10835 #else
10837 static inline void
10838 emit_library_info (MonoAotCompile *acfg)
10840 return;
10842 #endif
10844 static void
10845 emit_globals (MonoAotCompile *acfg)
10847 int i, table_size;
10848 guint32 hash;
10849 GPtrArray *table;
10850 char symbol [1024];
10851 GlobalsTableEntry *entry, *new_entry;
10853 if (!acfg->aot_opts.static_link)
10854 return;
10856 if (acfg->aot_opts.llvm_only) {
10857 g_assert (acfg->globals->len == 0);
10858 return;
10862 * When static linking, we emit a table containing our globals.
10866 * Construct a chained hash table for mapping global names to their index in
10867 * the globals table.
10869 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10870 table = g_ptr_array_sized_new (table_size);
10871 for (i = 0; i < table_size; ++i)
10872 g_ptr_array_add (table, NULL);
10873 for (i = 0; i < acfg->globals->len; ++i) {
10874 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10876 hash = mono_metadata_str_hash (name) % table_size;
10878 /* FIXME: Allocate from the mempool */
10879 new_entry = g_new0 (GlobalsTableEntry, 1);
10880 new_entry->value = i;
10882 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10883 if (entry == NULL) {
10884 new_entry->index = hash;
10885 g_ptr_array_index (table, hash) = new_entry;
10886 } else {
10887 while (entry->next)
10888 entry = entry->next;
10890 entry->next = new_entry;
10891 new_entry->index = table->len;
10892 g_ptr_array_add (table, new_entry);
10896 /* Emit the table */
10897 sprintf (symbol, ".Lglobals_hash");
10898 emit_section_change (acfg, RODATA_SECT, 0);
10899 emit_alignment (acfg, 8);
10900 emit_label (acfg, symbol);
10902 /* FIXME: Optimize memory usage */
10903 g_assert (table_size < 65000);
10904 emit_int16 (acfg, table_size);
10905 for (i = 0; i < table->len; ++i) {
10906 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10908 if (entry == NULL) {
10909 emit_int16 (acfg, 0);
10910 emit_int16 (acfg, 0);
10911 } else {
10912 emit_int16 (acfg, entry->value + 1);
10913 if (entry->next)
10914 emit_int16 (acfg, entry->next->index);
10915 else
10916 emit_int16 (acfg, 0);
10920 /* Emit the names */
10921 for (i = 0; i < acfg->globals->len; ++i) {
10922 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10924 sprintf (symbol, "name_%d", i);
10925 emit_section_change (acfg, RODATA_SECT, 1);
10926 #ifdef TARGET_MACH
10927 emit_alignment (acfg, 4);
10928 #endif
10929 emit_label (acfg, symbol);
10930 emit_string (acfg, name);
10933 /* Emit the globals table */
10934 sprintf (symbol, "globals");
10935 emit_section_change (acfg, ".data", 0);
10936 /* This is not a global, since it is accessed by the init function */
10937 emit_alignment (acfg, 8);
10938 emit_info_symbol (acfg, symbol, FALSE);
10940 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10941 emit_pointer (acfg, symbol);
10943 for (i = 0; i < acfg->globals->len; ++i) {
10944 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10946 sprintf (symbol, "name_%d", i);
10947 emit_pointer (acfg, symbol);
10949 g_assert (strlen (name) < sizeof (symbol));
10950 sprintf (symbol, "%s", name);
10951 emit_pointer (acfg, symbol);
10953 /* Null terminate the table */
10954 emit_int32 (acfg, 0);
10955 emit_int32 (acfg, 0);
10958 static void
10959 emit_mem_end (MonoAotCompile *acfg)
10961 char symbol [128];
10963 if (acfg->aot_opts.llvm_only)
10964 return;
10966 sprintf (symbol, "mem_end");
10967 emit_section_change (acfg, ".text", 1);
10968 emit_alignment_code (acfg, 8);
10969 emit_label (acfg, symbol);
10972 static void
10973 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10975 int i;
10977 info->version = MONO_AOT_FILE_VERSION;
10978 info->plt_got_offset_base = acfg->plt_got_offset_base;
10979 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10980 info->plt_size = acfg->plt_offset;
10981 info->nmethods = acfg->nmethods;
10982 info->nextra_methods = acfg->nextra_methods;
10983 info->flags = acfg->flags;
10984 info->opts = acfg->opts;
10985 info->simd_opts = acfg->simd_opts;
10986 info->gc_name_index = acfg->gc_name_offset;
10987 info->datafile_size = acfg->datafile_offset;
10988 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10989 info->table_offsets [i] = acfg->table_offsets [i];
10990 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10991 info->num_trampolines [i] = acfg->num_trampolines [i];
10992 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10993 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10994 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10995 info->trampoline_size [i] = acfg->trampoline_size [i];
10996 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10998 int card_table_shift_bits = 0;
10999 target_mgreg_t card_table_mask = 0;
11001 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
11004 * Sanity checking variables used to make sure the host and target
11005 * environment matches when cross compiling.
11007 info->double_align = MONO_ABI_ALIGNOF (double);
11008 info->long_align = MONO_ABI_ALIGNOF (gint64);
11009 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
11010 info->card_table_shift_bits = card_table_shift_bits;
11011 info->card_table_mask = card_table_mask;
11013 info->tramp_page_size = acfg->tramp_page_size;
11014 info->nshared_got_entries = acfg->nshared_got_entries;
11015 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11016 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
11018 memcpy(&info->aotid, acfg->image->aotid, 16);
11021 static void
11022 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
11024 char symbol [MAX_SYMBOL_SIZE];
11025 int i, sindex;
11026 const char **symbols;
11028 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11029 sindex = 0;
11030 symbols [sindex ++] = acfg->got_symbol;
11031 if (acfg->llvm) {
11032 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
11033 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
11034 } else {
11035 symbols [sindex ++] = NULL;
11036 symbols [sindex ++] = NULL;
11038 /* llvm_get_method */
11039 symbols [sindex ++] = NULL;
11040 /* llvm_get_unbox_tramp */
11041 symbols [sindex ++] = NULL;
11042 if (!acfg->aot_opts.llvm_only) {
11043 symbols [sindex ++] = "jit_code_start";
11044 symbols [sindex ++] = "jit_code_end";
11045 symbols [sindex ++] = "method_addresses";
11046 } else {
11047 symbols [sindex ++] = NULL;
11048 symbols [sindex ++] = NULL;
11049 symbols [sindex ++] = NULL;
11051 symbols [sindex ++] = NULL;
11052 symbols [sindex ++] = NULL;
11054 if (acfg->data_outfile) {
11055 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11056 symbols [sindex ++] = NULL;
11057 } else {
11058 symbols [sindex ++] = "blob";
11059 symbols [sindex ++] = "class_name_table";
11060 symbols [sindex ++] = "class_info_offsets";
11061 symbols [sindex ++] = "method_info_offsets";
11062 symbols [sindex ++] = "ex_info_offsets";
11063 symbols [sindex ++] = "extra_method_info_offsets";
11064 symbols [sindex ++] = "extra_method_table";
11065 symbols [sindex ++] = "got_info_offsets";
11066 if (acfg->llvm)
11067 symbols [sindex ++] = "llvm_got_info_offsets";
11068 else
11069 symbols [sindex ++] = NULL;
11070 symbols [sindex ++] = "image_table";
11071 symbols [sindex ++] = "weak_field_indexes";
11074 symbols [sindex ++] = "mem_end";
11075 symbols [sindex ++] = "assembly_guid";
11076 symbols [sindex ++] = "runtime_version";
11077 if (acfg->num_trampoline_got_entries) {
11078 symbols [sindex ++] = "specific_trampolines";
11079 symbols [sindex ++] = "static_rgctx_trampolines";
11080 symbols [sindex ++] = "imt_trampolines";
11081 symbols [sindex ++] = "gsharedvt_arg_trampolines";
11082 symbols [sindex ++] = "ftnptr_arg_trampolines";
11083 symbols [sindex ++] = "unbox_arbitrary_trampolines";
11084 } else {
11085 symbols [sindex ++] = NULL;
11086 symbols [sindex ++] = NULL;
11087 symbols [sindex ++] = NULL;
11088 symbols [sindex ++] = NULL;
11089 symbols [sindex ++] = NULL;
11090 symbols [sindex ++] = NULL;
11092 if (acfg->aot_opts.static_link) {
11093 symbols [sindex ++] = "globals";
11094 } else {
11095 symbols [sindex ++] = NULL;
11097 symbols [sindex ++] = "assembly_name";
11098 symbols [sindex ++] = "plt";
11099 symbols [sindex ++] = "plt_end";
11100 symbols [sindex ++] = "unwind_info";
11101 if (!acfg->aot_opts.llvm_only) {
11102 symbols [sindex ++] = "unbox_trampolines";
11103 symbols [sindex ++] = "unbox_trampolines_end";
11104 symbols [sindex ++] = "unbox_trampoline_addresses";
11105 } else {
11106 symbols [sindex ++] = NULL;
11107 symbols [sindex ++] = NULL;
11108 symbols [sindex ++] = NULL;
11111 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11113 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
11114 emit_section_change (acfg, ".data", 0);
11115 emit_alignment (acfg, 8);
11116 emit_label (acfg, symbol);
11117 if (!acfg->aot_opts.static_link)
11118 emit_global (acfg, symbol, FALSE);
11120 /* The data emitted here must match MonoAotFileInfo. */
11122 emit_int32 (acfg, info->version);
11123 emit_int32 (acfg, info->dummy);
11126 * We emit pointers to our data structures instead of emitting global symbols which
11127 * point to them, to reduce the number of globals, and because using globals leads to
11128 * various problems (i.e. arm/thumb).
11130 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
11131 emit_pointer (acfg, symbols [i]);
11133 emit_int32 (acfg, info->plt_got_offset_base);
11134 emit_int32 (acfg, info->got_size);
11135 emit_int32 (acfg, info->plt_size);
11136 emit_int32 (acfg, info->nmethods);
11137 emit_int32 (acfg, info->nextra_methods);
11138 emit_int32 (acfg, info->flags);
11139 emit_int32 (acfg, info->opts);
11140 emit_int32 (acfg, info->simd_opts);
11141 emit_int32 (acfg, info->gc_name_index);
11142 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
11143 emit_int32 (acfg, info->double_align);
11144 emit_int32 (acfg, info->long_align);
11145 emit_int32 (acfg, info->generic_tramp_num);
11146 emit_int32 (acfg, info->card_table_shift_bits);
11147 emit_int32 (acfg, info->card_table_mask);
11148 emit_int32 (acfg, info->tramp_page_size);
11149 emit_int32 (acfg, info->nshared_got_entries);
11150 emit_int32 (acfg, info->datafile_size);
11151 emit_int32 (acfg, 0);
11152 emit_int32 (acfg, 0);
11154 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11155 emit_int32 (acfg, info->table_offsets [i]);
11156 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11157 emit_int32 (acfg, info->num_trampolines [i]);
11158 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11159 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
11160 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11161 emit_int32 (acfg, info->trampoline_size [i]);
11162 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11163 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
11165 emit_bytes (acfg, info->aotid, 16);
11167 if (acfg->aot_opts.static_link) {
11168 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
11169 emit_alignment (acfg, sizeof (target_mgreg_t));
11170 emit_label (acfg, acfg->static_linking_symbol);
11171 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
11176 * Emit a structure containing all the information not stored elsewhere.
11178 static void
11179 emit_file_info (MonoAotCompile *acfg)
11181 char *build_info;
11182 MonoAotFileInfo *info;
11184 if (acfg->aot_opts.bind_to_runtime_version) {
11185 build_info = mono_get_runtime_build_info ();
11186 emit_string_symbol (acfg, "runtime_version", build_info);
11187 g_free (build_info);
11188 } else {
11189 emit_string_symbol (acfg, "runtime_version", "");
11192 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
11194 /* Emit a string holding the assembly name */
11195 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
11197 info = g_new0 (MonoAotFileInfo, 1);
11198 init_aot_file_info (acfg, info);
11200 if (acfg->aot_opts.static_link) {
11201 char symbol [MAX_SYMBOL_SIZE];
11202 char *p;
11205 * Emit a global symbol which can be passed by an embedding app to
11206 * mono_aot_register_module (). The symbol points to a pointer to the the file info
11207 * structure.
11209 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
11211 /* Get rid of characters which cannot occur in symbols */
11212 p = symbol;
11213 for (p = symbol; *p; ++p) {
11214 if (!(isalnum (*p) || *p == '_'))
11215 *p = '_';
11217 acfg->static_linking_symbol = g_strdup (symbol);
11220 if (acfg->llvm)
11221 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
11222 else
11223 emit_aot_file_info (acfg, info);
11226 static void
11227 emit_blob (MonoAotCompile *acfg)
11229 acfg->blob_closed = TRUE;
11231 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
11234 static void
11235 emit_objc_selectors (MonoAotCompile *acfg)
11237 int i;
11238 char symbol [128];
11240 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
11241 return;
11244 * From
11245 * cat > foo.m << EOF
11246 * void *ret ()
11248 * return @selector(print:);
11250 * EOF
11253 mono_img_writer_emit_unset_mode (acfg->w);
11254 g_assert (acfg->fp);
11255 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
11256 fprintf (acfg->fp, ".align 3\n");
11257 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11258 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
11259 emit_label (acfg, symbol);
11260 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
11261 emit_pointer (acfg, symbol);
11264 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
11265 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11266 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
11267 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
11270 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
11271 fprintf (acfg->fp, ".align 3\n");
11272 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
11273 fprintf (acfg->fp, ".long 0\n");
11274 fprintf (acfg->fp, ".long 16\n");
11277 static void
11278 emit_dwarf_info (MonoAotCompile *acfg)
11280 #ifdef EMIT_DWARF_INFO
11281 int i;
11282 char symbol2 [128];
11284 /* DIEs for methods */
11285 for (i = 0; i < acfg->nmethods; ++i) {
11286 MonoCompile *cfg = acfg->cfgs [i];
11288 if (ignore_cfg (cfg))
11289 continue;
11291 // FIXME: LLVM doesn't define .Lme_...
11292 if (cfg->compile_llvm)
11293 continue;
11295 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
11297 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 ()));
11299 #endif
11302 #ifdef EMIT_WIN32_CODEVIEW_INFO
11303 typedef struct _CodeViewSubSectionData
11305 gchar *start_section;
11306 gchar *end_section;
11307 gchar *start_section_record;
11308 gchar *end_section_record;
11309 int section_type;
11310 int section_record_type;
11311 int section_id;
11312 } CodeViewSubsectionData;
11314 typedef struct _CodeViewCompilerVersion
11316 gint major;
11317 gint minor;
11318 gint revision;
11319 gint patch;
11320 } CodeViewCompilerVersion;
11322 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
11323 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
11324 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
11325 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
11326 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
11327 #define CODEVIEW_CPU_TYPE 0x0
11328 #define CODEVIEW_MAGIC_HEADER 0x4
11330 static void
11331 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
11333 g_free (section_data->start_section);
11334 g_free (section_data->end_section);
11335 g_free (section_data->start_section_record);
11336 g_free (section_data->end_section_record);
11338 memset (section_data, 0, sizeof (CodeViewSubsectionData));
11341 static void
11342 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
11344 gint values[4] = { 0 };
11345 gint *value = values;
11347 while (*version && (value < values + G_N_ELEMENTS (values))) {
11348 if (isdigit (*version)) {
11349 *value *= 10;
11350 *value += *version - '0';
11352 else if (*version == '.') {
11353 value++;
11356 version++;
11359 data->major = values[0];
11360 data->minor = values[1];
11361 data->revision = values[2];
11362 data->patch = values[3];
11365 static void
11366 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
11368 // Starting a new subsection, clear old data.
11369 codeview_clear_subsection_data (section_data);
11371 // Keep subsection data.
11372 section_data->section_id = section_id;
11373 section_data->section_type = section_type;
11374 section_data->section_record_type = section_record_type;
11376 // Allocate all labels used in subsection.
11377 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
11378 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
11379 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
11380 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
11382 // Subsection type, function symbol.
11383 emit_int32 (acfg, section_data->section_type);
11385 // Subsection size.
11386 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
11387 emit_label (acfg, section_data->start_section);
11389 // Subsection record size.
11390 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
11391 emit_label (acfg, section_data->start_section_record);
11393 // Subsection record type.
11394 emit_int16 (acfg, section_record_type);
11397 static void
11398 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11400 g_assert (section_data->start_section);
11401 g_assert (section_data->end_section);
11402 g_assert (section_data->start_section_record);
11403 g_assert (section_data->end_section_record);
11405 emit_label (acfg, section_data->end_section_record);
11407 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
11408 // Emit record length.
11409 emit_int16 (acfg, 2);
11411 // Emit specific record type end.
11412 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
11415 emit_label (acfg, section_data->end_section);
11417 // Next subsection needs to be 4 byte aligned.
11418 emit_alignment (acfg, 4);
11420 *section_id = section_data->section_id + 1;
11421 codeview_clear_subsection_data (section_data);
11424 inline static void
11425 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11427 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11430 inline static void
11431 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11433 emit_codeview_end_subsection (acfg, section_data, section_id);
11436 static void
11437 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11439 CodeViewSubsectionData section_data = { 0 };
11440 CodeViewCompilerVersion compiler_version = { 0 };
11442 // Start new compiler record subsection.
11443 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11445 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11446 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11448 // Get compiler version information.
11449 codeview_parse_compiler_version (VERSION, &compiler_version);
11451 // Compiler frontend version, 4 digits.
11452 emit_int16 (acfg, compiler_version.major);
11453 emit_int16 (acfg, compiler_version.minor);
11454 emit_int16 (acfg, compiler_version.revision);
11455 emit_int16 (acfg, compiler_version.patch);
11457 // Compiler backend version, 4 digits (currently same as frontend).
11458 emit_int16 (acfg, compiler_version.major);
11459 emit_int16 (acfg, compiler_version.minor);
11460 emit_int16 (acfg, compiler_version.revision);
11461 emit_int16 (acfg, compiler_version.patch);
11463 // Compiler string.
11464 emit_string (acfg, "Mono AOT compiler");
11466 // Done with section.
11467 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11470 static void
11471 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11473 CodeViewSubsectionData section_data = { 0 };
11474 gchar *full_method_name = NULL;
11476 // Start new function record subsection.
11477 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11479 // Emit 3 int 0 byte padding, currently not used.
11480 emit_zero_bytes (acfg, sizeof (int) * 3);
11482 // Emit size of function.
11483 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11485 // Emit 3 int 0 byte padding, currently not used.
11486 emit_zero_bytes (acfg, sizeof (int) * 3);
11488 // Emit reallocation info.
11489 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11490 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11492 // Emit flag, currently not used.
11493 emit_zero_bytes (acfg, 1);
11495 // Emit function name, exclude signature since it should be described by own metadata.
11496 full_method_name = mono_method_full_name (method, FALSE);
11497 emit_string (acfg, full_method_name ? full_method_name : "");
11498 g_free (full_method_name);
11500 // Done with section.
11501 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11504 static void
11505 emit_codeview_info (MonoAotCompile *acfg)
11507 int i;
11508 int section_id = 0;
11509 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11511 // Emit codeview debug info section
11512 emit_section_change (acfg, ".debug$S", 0);
11514 // Emit magic header.
11515 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11517 emit_codeview_compiler_info (acfg, &section_id);
11519 for (i = 0; i < acfg->nmethods; ++i) {
11520 MonoCompile *cfg = acfg->cfgs[i];
11522 if (!cfg || COMPILE_LLVM (cfg))
11523 continue;
11525 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11526 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11527 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11530 #else
11531 static void
11532 emit_codeview_info (MonoAotCompile *acfg)
11535 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11537 #ifdef EMIT_WIN32_UNWIND_INFO
11538 static UnwindInfoSectionCacheItem *
11539 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11541 UnwindInfoSectionCacheItem *item = NULL;
11543 if (!acfg->unwind_info_section_cache)
11544 acfg->unwind_info_section_cache = g_list_alloc ();
11546 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11548 // Search for unwind info in cache.
11549 GList *list = acfg->unwind_info_section_cache;
11550 int list_size = 0;
11551 while (list && list->data) {
11552 item = (UnwindInfoSectionCacheItem*)list->data;
11553 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11554 // Cache hit, return cached item.
11555 return item;
11557 list = list->next;
11558 list_size++;
11561 // Add to cache.
11562 if (acfg->unwind_info_section_cache) {
11563 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11564 if (item) {
11565 // Format .xdata section label for function, used to get unwind info address RVA.
11566 // Since the unwind info is similar for most functions, the symbol will be reused.
11567 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11569 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11570 //over ownership of unwind info.
11571 item->unwind_info = unwind_info;
11573 // Needs to be emitted once.
11574 item->xdata_section_emitted = FALSE;
11576 // Prepend to beginning of list to speed up inserts.
11577 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11581 return item;
11584 static void
11585 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11587 GList *list = acfg->unwind_info_section_cache;
11589 while (list) {
11590 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11591 if (item) {
11592 g_free (item->xdata_section_label);
11593 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11595 g_free (item);
11596 list->data = NULL;
11599 list = list->next;
11602 g_list_free (acfg->unwind_info_section_cache);
11603 acfg->unwind_info_section_cache = NULL;
11606 static void
11607 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11609 // Emit the unwind info struct.
11610 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11612 // Emit all unwind codes encoded in unwind info struct.
11613 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11614 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11616 while (current_unwind_node < last_unwind_node) {
11617 guint8 node_count = 0;
11618 switch (current_unwind_node->UnwindOp) {
11619 case UWOP_PUSH_NONVOL:
11620 case UWOP_ALLOC_SMALL:
11621 case UWOP_SET_FPREG:
11622 case UWOP_PUSH_MACHFRAME:
11623 node_count = 1;
11624 break;
11625 case UWOP_SAVE_NONVOL:
11626 case UWOP_SAVE_XMM128:
11627 node_count = 2;
11628 break;
11629 case UWOP_SAVE_NONVOL_FAR:
11630 case UWOP_SAVE_XMM128_FAR:
11631 node_count = 3;
11632 break;
11633 case UWOP_ALLOC_LARGE:
11634 if (current_unwind_node->OpInfo == 0)
11635 node_count = 2;
11636 else
11637 node_count = 3;
11638 break;
11639 default:
11640 g_assert (!"Unknown unwind opcode.");
11643 while (node_count > 0) {
11644 g_assert (current_unwind_node < last_unwind_node);
11646 //Emit current node.
11647 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11649 node_count--;
11650 current_unwind_node++;
11655 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11656 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11657 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11658 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11659 static void
11660 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11662 char *pdata_section_label = NULL;
11664 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11665 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11666 temp_prefix_len = 0;
11669 // Format .pdata section label for function.
11670 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11672 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11673 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11675 // Emit .pdata section.
11676 emit_section_change (acfg, ".pdata", 0);
11677 emit_alignment (acfg, sizeof (DWORD));
11678 emit_label (acfg, pdata_section_label);
11680 // Emit function start address RVA.
11681 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11683 // Emit function end address RVA.
11684 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11686 // Emit unwind info address RVA.
11687 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11689 if (!cache_item->xdata_section_emitted) {
11690 // Emit .xdata section.
11691 emit_section_change (acfg, ".xdata", 0);
11692 emit_alignment (acfg, sizeof (DWORD));
11693 emit_label (acfg, cache_item->xdata_section_label);
11695 // Emit unwind info into .xdata section.
11696 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11697 cache_item->xdata_section_emitted = TRUE;
11700 g_free (pdata_section_label);
11702 #endif
11704 static gboolean
11705 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11707 #ifdef TARGET_WASM
11708 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11709 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11710 return FALSE;
11711 #endif
11712 return TRUE;
11715 static gboolean
11716 collect_methods (MonoAotCompile *acfg)
11718 int mindex, i;
11719 MonoImage *image = acfg->image;
11721 /* Collect methods */
11722 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11723 ERROR_DECL (error);
11724 MonoMethod *method;
11725 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11727 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11729 if (!method) {
11730 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11731 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11732 mono_error_cleanup (error);
11733 return FALSE;
11736 /* Load all methods eagerly to skip the slower lazy loading code */
11737 mono_class_setup_methods (method->klass);
11739 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11740 /* Compile the wrapper instead */
11741 /* We do this here instead of add_wrappers () because it is easy to do it here */
11742 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11743 method = wrapper;
11746 /* FIXME: Some mscorlib methods don't have debug info */
11748 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11749 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11750 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11751 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11752 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11753 if (!mono_debug_lookup_method (method)) {
11754 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11755 exit (1);
11761 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11762 /* Compile the ref shared version instead */
11763 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11764 if (!method) {
11765 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11766 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11767 mono_error_cleanup (error);
11768 return FALSE;
11772 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11773 add_method_with_index (acfg, method, i, FALSE);
11774 acfg->method_index ++;
11777 /* gsharedvt methods */
11778 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11779 ERROR_DECL (error);
11780 MonoMethod *method;
11781 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11783 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11784 continue;
11786 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11787 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11789 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11790 MonoMethod *gshared;
11792 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11793 mono_error_assert_ok (error);
11795 add_extra_method (acfg, gshared);
11799 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11800 add_generic_instances (acfg);
11802 if (mono_aot_mode_is_full (&acfg->aot_opts))
11803 add_wrappers (acfg);
11804 return TRUE;
11807 static void
11808 compile_methods (MonoAotCompile *acfg)
11810 int i, methods_len;
11812 if (acfg->aot_opts.nthreads > 0) {
11813 GPtrArray *frag;
11814 int len, j;
11815 GPtrArray *threads;
11816 MonoThreadHandle *thread_handle;
11817 gpointer *user_data;
11818 MonoMethod **methods;
11820 methods_len = acfg->methods->len;
11822 len = acfg->methods->len / acfg->aot_opts.nthreads;
11823 g_assert (len > 0);
11825 * Partition the list of methods into fragments, and hand it to threads to
11826 * process.
11828 threads = g_ptr_array_new ();
11829 /* Make a copy since acfg->methods is modified by compile_method () */
11830 methods = g_new0 (MonoMethod*, methods_len);
11831 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11832 for (i = 0; i < methods_len; ++i)
11833 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11834 i = 0;
11835 while (i < methods_len) {
11836 ERROR_DECL (error);
11837 MonoInternalThread *thread;
11839 frag = g_ptr_array_new ();
11840 for (j = 0; j < len; ++j) {
11841 if (i < methods_len) {
11842 g_ptr_array_add (frag, methods [i]);
11843 i ++;
11847 user_data = g_new0 (gpointer, 3);
11848 user_data [0] = acfg;
11849 user_data [1] = frag;
11851 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11852 mono_error_assert_ok (error);
11854 thread_handle = mono_threads_open_thread_handle (thread->handle);
11855 g_ptr_array_add (threads, thread_handle);
11857 g_free (methods);
11859 for (i = 0; i < threads->len; ++i) {
11860 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11861 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11863 } else {
11864 methods_len = 0;
11867 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11868 for (i = methods_len; i < acfg->methods->len; ++i) {
11869 /* This can add new methods to acfg->methods */
11870 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11873 #ifdef ENABLE_LLVM
11874 if (acfg->llvm)
11875 mono_llvm_fixup_aot_module ();
11876 #endif
11879 static int
11880 compile_asm (MonoAotCompile *acfg)
11882 char *command, *objfile;
11883 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11884 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11885 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11887 #ifdef TARGET_WIN32_MSVC
11888 #define AS_OPTIONS "-c -x assembler"
11889 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11890 #define AS_OPTIONS "--64"
11891 #elif defined(TARGET_POWERPC64)
11892 #define AS_OPTIONS "-a64 -mppc64"
11893 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11894 #define AS_OPTIONS "-xarch=v9"
11895 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11896 #define AS_OPTIONS "-arch i386"
11897 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11898 #define AS_OPTIONS "--32"
11899 #else
11900 #define AS_OPTIONS ""
11901 #endif
11903 #if defined(TARGET_OSX)
11904 #define AS_NAME "clang"
11905 #elif defined(TARGET_WIN32_MSVC)
11906 #define AS_NAME "clang.exe"
11907 #else
11908 #define AS_NAME "as"
11909 #endif
11911 #ifdef TARGET_WIN32_MSVC
11912 #define AS_OBJECT_FILE_SUFFIX "obj"
11913 #else
11914 #define AS_OBJECT_FILE_SUFFIX "o"
11915 #endif
11917 #if defined(sparc)
11918 #define LD_NAME "ld"
11919 #define LD_OPTIONS "-shared -G"
11920 #elif defined(__ppc__) && defined(TARGET_MACH)
11921 #define LD_NAME "gcc"
11922 #define LD_OPTIONS "-dynamiclib"
11923 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11924 #define LD_NAME "clang"
11925 #define LD_OPTIONS "--shared"
11926 #elif defined(TARGET_WIN32_MSVC)
11927 #define LD_NAME "link.exe"
11928 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11929 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11930 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11931 #define LD_NAME "gcc"
11932 #define LD_OPTIONS "-shared"
11933 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11934 #define LD_NAME "clang"
11935 #define LD_OPTIONS "-m32 -dynamiclib"
11936 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11937 #define LD_OPTIONS "-m elf_i386"
11938 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11939 #define LD_NAME "gcc"
11940 #define LD_OPTIONS "--shared"
11941 #elif defined(TARGET_POWERPC64)
11942 #define LD_OPTIONS "-m elf64ppc"
11943 #endif
11945 #ifndef LD_OPTIONS
11946 #define LD_OPTIONS ""
11947 #endif
11949 if (acfg->aot_opts.asm_only) {
11950 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11951 if (acfg->aot_opts.static_link)
11952 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11953 if (acfg->llvm)
11954 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11955 return 0;
11958 if (acfg->aot_opts.static_link) {
11959 if (acfg->aot_opts.outfile)
11960 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11961 else
11962 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11963 } else {
11964 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11967 #ifdef TARGET_OSX
11968 g_string_append (acfg->as_args, "-c -x assembler");
11969 #endif
11971 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11972 acfg->as_args ? acfg->as_args->str : "",
11973 wrap_path (objfile), wrap_path (acfg->tmpfname));
11974 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11975 if (execute_system (command) != 0) {
11976 g_free (command);
11977 g_free (objfile);
11978 return 1;
11981 if (acfg->llvm && !acfg->llvm_owriter) {
11982 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11983 acfg->as_args ? acfg->as_args->str : "",
11984 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11985 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11986 if (execute_system (command) != 0) {
11987 g_free (command);
11988 g_free (objfile);
11989 return 1;
11993 g_free (command);
11995 if (acfg->aot_opts.static_link) {
11996 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11997 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11998 g_free (objfile);
11999 return 0;
12002 if (acfg->aot_opts.outfile)
12003 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12004 else
12005 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
12007 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
12009 if (acfg->llvm) {
12010 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
12011 } else {
12012 llvm_ofile = g_strdup ("");
12015 /* replace the ; flags separators with spaces */
12016 g_strdelimit (ld_flags, ';', ' ');
12018 if (acfg->aot_opts.llvm_only)
12019 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
12021 #ifdef TARGET_WIN32_MSVC
12022 g_assert (tmp_outfile_name != NULL);
12023 g_assert (objfile != NULL);
12024 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
12025 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
12026 #elif defined(LD_NAME)
12027 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
12028 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12029 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12030 #else
12031 // Default (linux)
12032 if (acfg->aot_opts.tool_prefix) {
12033 /* Cross compiling */
12034 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
12035 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12036 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12037 } else {
12038 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
12039 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12040 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12042 if (acfg->aot_opts.llvm_only) {
12043 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
12044 } else {
12045 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
12047 g_free (args);
12049 #endif
12050 aot_printf (acfg, "Executing the native linker: %s\n", command);
12051 if (execute_system (command) != 0) {
12052 g_free (tmp_outfile_name);
12053 g_free (outfile_name);
12054 g_free (command);
12055 g_free (objfile);
12056 g_free (ld_flags);
12057 return 1;
12060 g_free (command);
12062 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
12063 printf ("Stripping the binary: %s\n", com);
12064 execute_system (com);
12065 g_free (com);*/
12067 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
12069 * gas generates 'mapping symbols' each time code and data is mixed, which
12070 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
12072 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
12073 aot_printf (acfg, "Stripping the binary: %s\n", command);
12074 if (execute_system (command) != 0) {
12075 g_free (tmp_outfile_name);
12076 g_free (outfile_name);
12077 g_free (command);
12078 g_free (objfile);
12079 return 1;
12081 #endif
12083 if (0 != rename (tmp_outfile_name, outfile_name)) {
12084 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
12085 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
12086 unlink (outfile_name);
12087 rename (tmp_outfile_name, outfile_name);
12091 #if defined(TARGET_MACH)
12092 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
12093 aot_printf (acfg, "Executing dsymutil: %s\n", command);
12094 if (execute_system (command) != 0) {
12095 return 1;
12097 #endif
12099 if (!acfg->aot_opts.save_temps)
12100 unlink (objfile);
12102 g_free (tmp_outfile_name);
12103 g_free (outfile_name);
12104 g_free (objfile);
12106 if (acfg->aot_opts.save_temps)
12107 aot_printf (acfg, "Retained input file.\n");
12108 else
12109 unlink (acfg->tmpfname);
12111 return 0;
12114 static guint8
12115 profread_byte (FILE *infile)
12117 guint8 i;
12118 int res;
12120 res = fread (&i, 1, 1, infile);
12121 g_assert (res == 1);
12122 return i;
12125 static int
12126 profread_int (FILE *infile)
12128 int i, res;
12130 res = fread (&i, 4, 1, infile);
12131 g_assert (res == 1);
12132 return i;
12135 static char*
12136 profread_string (FILE *infile)
12138 int len, res;
12139 char *pbuf;
12141 len = profread_int (infile);
12142 pbuf = (char*)g_malloc (len + 1);
12143 res = fread (pbuf, 1, len, infile);
12144 g_assert (res == len);
12145 pbuf [len] = '\0';
12146 return pbuf;
12149 static void
12150 load_profile_file (MonoAotCompile *acfg, char *filename)
12152 FILE *infile;
12153 char buf [1024];
12154 int res, len, version;
12155 char magic [32];
12157 infile = fopen (filename, "r");
12158 if (!infile) {
12159 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
12160 exit (1);
12163 printf ("Using profile data file '%s'\n", filename);
12165 sprintf (magic, AOT_PROFILER_MAGIC);
12166 len = strlen (magic);
12167 res = fread (buf, 1, len, infile);
12168 magic [len] = '\0';
12169 buf [len] = '\0';
12170 if ((res != len) || strcmp (buf, magic) != 0) {
12171 printf ("Profile file has wrong header: '%s'.\n", buf);
12172 fclose (infile);
12173 exit (1);
12175 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
12176 version = profread_int (infile);
12177 if (version != expected_version) {
12178 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
12179 fclose (infile);
12180 exit (1);
12183 ProfileData *data = g_new0 (ProfileData, 1);
12184 data->images = g_hash_table_new (NULL, NULL);
12185 data->classes = g_hash_table_new (NULL, NULL);
12186 data->ginsts = g_hash_table_new (NULL, NULL);
12187 data->methods = g_hash_table_new (NULL, NULL);
12189 while (TRUE) {
12190 int type = profread_byte (infile);
12191 int id = profread_int (infile);
12193 if (type == AOTPROF_RECORD_NONE)
12194 break;
12196 switch (type) {
12197 case AOTPROF_RECORD_IMAGE: {
12198 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
12199 idata->name = profread_string (infile);
12200 char *mvid = profread_string (infile);
12201 g_free (mvid);
12202 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
12203 break;
12205 case AOTPROF_RECORD_GINST: {
12206 int i;
12207 int len = profread_int (infile);
12209 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
12210 gdata->argc = len;
12211 gdata->argv = g_new0 (ClassProfileData*, len);
12213 for (i = 0; i < len; ++i) {
12214 int class_id = profread_int (infile);
12216 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12217 g_assert (gdata->argv [i]);
12219 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
12220 break;
12222 case AOTPROF_RECORD_TYPE: {
12223 int type = profread_byte (infile);
12225 switch (type) {
12226 case MONO_TYPE_CLASS: {
12227 int image_id = profread_int (infile);
12228 int ginst_id = profread_int (infile);
12229 char *class_name = profread_string (infile);
12231 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
12232 g_assert (image);
12234 char *p = strrchr (class_name, '.');
12235 g_assert (p);
12236 *p = '\0';
12238 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
12239 cdata->image = image;
12240 cdata->ns = g_strdup (class_name);
12241 cdata->name = g_strdup (p + 1);
12243 if (ginst_id != -1) {
12244 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12245 g_assert (cdata->inst);
12247 g_free (class_name);
12249 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
12250 break;
12252 #if 0
12253 case MONO_TYPE_SZARRAY: {
12254 int elem_id = profread_int (infile);
12255 // FIXME:
12256 break;
12258 #endif
12259 default:
12260 g_assert_not_reached ();
12261 break;
12263 break;
12265 case AOTPROF_RECORD_METHOD: {
12266 int class_id = profread_int (infile);
12267 int ginst_id = profread_int (infile);
12268 int param_count = profread_int (infile);
12269 char *method_name = profread_string (infile);
12270 char *sig = profread_string (infile);
12272 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12273 g_assert (klass);
12275 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
12276 mdata->id = id;
12277 mdata->klass = klass;
12278 mdata->name = method_name;
12279 mdata->signature = sig;
12280 mdata->param_count = param_count;
12282 if (ginst_id != -1) {
12283 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12284 g_assert (mdata->inst);
12286 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
12287 break;
12289 default:
12290 printf ("%d\n", type);
12291 g_assert_not_reached ();
12292 break;
12296 fclose (infile);
12297 acfg->profile_data = g_list_append (acfg->profile_data, data);
12300 static void
12301 resolve_class (ClassProfileData *cdata);
12303 static void
12304 resolve_ginst (GInstProfileData *inst_data)
12306 int i;
12308 if (inst_data->inst)
12309 return;
12311 for (i = 0; i < inst_data->argc; ++i) {
12312 resolve_class (inst_data->argv [i]);
12313 if (!inst_data->argv [i]->klass)
12314 return;
12316 MonoType **args = g_new0 (MonoType*, inst_data->argc);
12317 for (i = 0; i < inst_data->argc; ++i)
12318 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
12320 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
12323 static void
12324 resolve_class (ClassProfileData *cdata)
12326 ERROR_DECL (error);
12327 MonoClass *klass;
12329 if (!cdata->image->image)
12330 return;
12332 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
12333 if (!klass) {
12334 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
12335 return;
12337 if (cdata->inst) {
12338 resolve_ginst (cdata->inst);
12339 if (!cdata->inst->inst)
12340 return;
12341 MonoGenericContext ctx;
12343 memset (&ctx, 0, sizeof (ctx));
12344 ctx.class_inst = cdata->inst->inst;
12345 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
12346 } else {
12347 cdata->klass = klass;
12352 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
12354 static void
12355 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
12357 GHashTableIter iter;
12358 gpointer key, value;
12359 int i;
12361 if (!data)
12362 return;
12364 /* Images */
12365 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
12366 g_hash_table_iter_init (&iter, data->images);
12367 while (g_hash_table_iter_next (&iter, &key, &value)) {
12368 ImageProfileData *idata = (ImageProfileData*)value;
12370 if (!strcmp (current->aname.name, idata->name)) {
12371 idata->image = current->image;
12372 break;
12375 for (i = 0; i < assemblies->len; ++i) {
12376 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
12378 if (!strcmp (ass->aname.name, idata->name)) {
12379 idata->image = ass->image;
12380 break;
12384 g_ptr_array_free (assemblies, TRUE);
12386 /* Classes */
12387 g_hash_table_iter_init (&iter, data->classes);
12388 while (g_hash_table_iter_next (&iter, &key, &value)) {
12389 ClassProfileData *cdata = (ClassProfileData*)value;
12391 if (!cdata->image->image) {
12392 if (acfg->aot_opts.verbose)
12393 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
12394 continue;
12397 resolve_class (cdata);
12399 if (cdata->klass)
12400 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
12404 /* Methods */
12405 g_hash_table_iter_init (&iter, data->methods);
12406 while (g_hash_table_iter_next (&iter, &key, &value)) {
12407 MethodProfileData *mdata = (MethodProfileData*)value;
12408 MonoClass *klass;
12409 MonoMethod *m;
12410 gpointer miter;
12412 resolve_class (mdata->klass);
12413 klass = mdata->klass->klass;
12414 if (!klass) {
12415 if (acfg->aot_opts.verbose)
12416 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
12417 continue;
12419 miter = NULL;
12420 while ((m = mono_class_get_methods (klass, &miter))) {
12421 ERROR_DECL (error);
12423 if (strcmp (m->name, mdata->name))
12424 continue;
12425 MonoMethodSignature *sig = mono_method_signature_internal (m);
12426 if (!sig)
12427 continue;
12428 if (sig->param_count != mdata->param_count)
12429 continue;
12430 if (mdata->inst) {
12431 resolve_ginst (mdata->inst);
12432 if (!mdata->inst->inst)
12433 continue;
12434 MonoGenericContext ctx;
12436 memset (&ctx, 0, sizeof (ctx));
12437 ctx.method_inst = mdata->inst->inst;
12439 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12440 if (!m)
12441 continue;
12442 sig = mono_method_signature_checked (m, error);
12443 if (!is_ok (error)) {
12444 mono_error_cleanup (error);
12445 continue;
12448 char *sig_str = mono_signature_full_name (sig);
12449 gboolean match = !strcmp (sig_str, mdata->signature);
12450 g_free (sig_str);
12451 if (!match)
12453 continue;
12454 //printf ("%s\n", mono_method_full_name (m, 1));
12455 mdata->method = m;
12456 break;
12458 if (!mdata->method) {
12459 if (acfg->aot_opts.verbose)
12460 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12465 static gboolean
12466 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12468 int i;
12470 for (i = 0; i < inst->type_argc; ++i) {
12471 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12472 if (m_class_get_image (k) == image)
12473 return TRUE;
12474 if (mono_class_is_ginst (k)) {
12475 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12476 if (inst_references_image (kinst, image))
12477 return TRUE;
12480 return FALSE;
12483 static gboolean
12484 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12486 int i;
12488 for (i = 0; i < inst->type_argc; ++i) {
12489 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12490 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12491 return FALSE;
12493 return TRUE;
12496 static void
12497 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12499 GHashTableIter iter;
12500 gpointer key, value;
12501 int count = 0;
12503 if (!data)
12504 return;
12506 if (acfg->aot_opts.profile_only) {
12507 /* Add methods referenced by the profile */
12508 g_hash_table_iter_init (&iter, data->methods);
12509 while (g_hash_table_iter_next (&iter, &key, &value)) {
12510 MethodProfileData *mdata = (MethodProfileData*)value;
12511 MonoMethod *m = mdata->method;
12513 if (!m)
12514 continue;
12515 if (m->is_inflated)
12516 continue;
12517 add_extra_method (acfg, m);
12518 g_hash_table_insert (acfg->profile_methods, m, m);
12519 count ++;
12524 * Add method instances 'related' to this assembly to the AOT image.
12526 g_hash_table_iter_init (&iter, data->methods);
12527 while (g_hash_table_iter_next (&iter, &key, &value)) {
12528 MethodProfileData *mdata = (MethodProfileData*)value;
12529 MonoMethod *m = mdata->method;
12530 MonoGenericContext *ctx;
12532 if (!m)
12533 continue;
12534 if (!m->is_inflated)
12535 continue;
12537 ctx = mono_method_get_context (m);
12538 /* For simplicity, add instances which reference the assembly we are compiling */
12539 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12540 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12541 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12542 //printf ("%s\n", mono_method_full_name (m, TRUE));
12543 add_extra_method (acfg, m);
12544 count ++;
12545 } else if (m_class_get_image (m->klass) == acfg->image &&
12546 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12547 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12548 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12549 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12550 //printf ("%s\n", mono_method_full_name (m, TRUE));
12551 add_extra_method (acfg, m);
12552 count ++;
12555 * FIXME: We might skip some instances, for example:
12556 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12557 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12561 printf ("Added %d methods from profile.\n", count);
12564 static void
12565 init_got_info (GotInfo *info)
12567 int i;
12569 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12570 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12571 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12572 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12573 info->got_patches = g_ptr_array_new ();
12576 static MonoAotCompile*
12577 acfg_create (MonoAssembly *ass, guint32 opts)
12579 MonoImage *image = ass->image;
12580 MonoAotCompile *acfg;
12582 acfg = g_new0 (MonoAotCompile, 1);
12583 acfg->methods = g_ptr_array_new ();
12584 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12585 acfg->method_depth = g_hash_table_new (NULL, NULL);
12586 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12587 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12588 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12589 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12590 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12591 acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12592 acfg->image_hash = g_hash_table_new (NULL, NULL);
12593 acfg->image_table = g_ptr_array_new ();
12594 acfg->globals = g_ptr_array_new ();
12595 acfg->image = image;
12596 acfg->opts = opts;
12597 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12598 #ifndef MONO_CROSS_COMPILE
12599 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12600 #endif
12601 acfg->mempool = mono_mempool_new ();
12602 acfg->extra_methods = g_ptr_array_new ();
12603 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12604 acfg->unwind_ops = g_ptr_array_new ();
12605 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12606 acfg->method_order = g_ptr_array_new ();
12607 acfg->export_names = g_hash_table_new (NULL, NULL);
12608 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12609 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12610 acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
12611 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12612 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12613 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12614 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12615 mono_os_mutex_init_recursive (&acfg->mutex);
12617 init_got_info (&acfg->got_info);
12618 init_got_info (&acfg->llvm_got_info);
12620 method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
12621 return acfg;
12624 static void
12625 got_info_free (GotInfo *info)
12627 int i;
12629 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12630 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12631 g_free (info->patch_to_got_offset_by_type);
12632 g_hash_table_destroy (info->patch_to_got_offset);
12633 g_ptr_array_free (info->got_patches, TRUE);
12636 static void
12637 acfg_free (MonoAotCompile *acfg)
12639 int i;
12641 mono_img_writer_destroy (acfg->w);
12642 for (i = 0; i < acfg->nmethods; ++i)
12643 if (acfg->cfgs [i])
12644 mono_destroy_compile (acfg->cfgs [i]);
12646 g_free (acfg->cfgs);
12648 g_free (acfg->static_linking_symbol);
12649 g_free (acfg->got_symbol);
12650 g_free (acfg->plt_symbol);
12651 g_ptr_array_free (acfg->methods, TRUE);
12652 g_ptr_array_free (acfg->image_table, TRUE);
12653 g_ptr_array_free (acfg->globals, TRUE);
12654 g_ptr_array_free (acfg->unwind_ops, TRUE);
12655 g_hash_table_destroy (acfg->method_indexes);
12656 g_hash_table_destroy (acfg->method_depth);
12657 g_hash_table_destroy (acfg->plt_offset_to_entry);
12658 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12659 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12660 g_free (acfg->patch_to_plt_entry);
12661 g_hash_table_destroy (acfg->method_to_cfg);
12662 g_hash_table_destroy (acfg->token_info_hash);
12663 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12664 g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
12665 g_hash_table_destroy (acfg->image_hash);
12666 g_hash_table_destroy (acfg->unwind_info_offsets);
12667 g_hash_table_destroy (acfg->method_label_hash);
12668 g_hash_table_destroy (acfg->typespec_classes);
12669 g_hash_table_destroy (acfg->export_names);
12670 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12671 g_hash_table_destroy (acfg->klass_blob_hash);
12672 g_hash_table_destroy (acfg->method_blob_hash);
12673 got_info_free (&acfg->got_info);
12674 got_info_free (&acfg->llvm_got_info);
12675 arch_free_unwind_info_section_cache (acfg);
12676 mono_mempool_destroy (acfg->mempool);
12678 method_to_external_icall_symbol_name = NULL;
12679 g_free (acfg);
12682 #define WRAPPER(e,n) n,
12683 static const char* const
12684 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12685 #include "mono/metadata/wrapper-types.h"
12686 NULL
12689 static G_GNUC_UNUSED const char*
12690 get_wrapper_type_name (int type)
12692 return wrapper_type_names [type];
12695 //#define DUMP_PLT
12696 //#define DUMP_GOT
12698 static void aot_dump (MonoAotCompile *acfg)
12700 FILE *dumpfile;
12701 char * dumpname;
12703 JsonWriter writer;
12704 mono_json_writer_init (&writer);
12706 mono_json_writer_object_begin(&writer);
12708 // Methods
12709 mono_json_writer_indent (&writer);
12710 mono_json_writer_object_key(&writer, "methods");
12711 mono_json_writer_array_begin (&writer);
12713 int i;
12714 for (i = 0; i < acfg->nmethods; ++i) {
12715 MonoCompile *cfg;
12716 MonoMethod *method;
12717 MonoClass *klass;
12719 cfg = acfg->cfgs [i];
12720 if (ignore_cfg (cfg))
12721 continue;
12723 method = cfg->orig_method;
12725 mono_json_writer_indent (&writer);
12726 mono_json_writer_object_begin(&writer);
12728 mono_json_writer_indent (&writer);
12729 mono_json_writer_object_key(&writer, "name");
12730 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12732 mono_json_writer_indent (&writer);
12733 mono_json_writer_object_key(&writer, "signature");
12734 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12736 mono_json_writer_indent (&writer);
12737 mono_json_writer_object_key(&writer, "code_size");
12738 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12740 klass = method->klass;
12742 mono_json_writer_indent (&writer);
12743 mono_json_writer_object_key(&writer, "class");
12744 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12746 mono_json_writer_indent (&writer);
12747 mono_json_writer_object_key(&writer, "namespace");
12748 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12750 mono_json_writer_indent (&writer);
12751 mono_json_writer_object_key(&writer, "wrapper_type");
12752 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12754 mono_json_writer_indent_pop (&writer);
12755 mono_json_writer_indent (&writer);
12756 mono_json_writer_object_end (&writer);
12757 mono_json_writer_printf (&writer, ",\n");
12760 mono_json_writer_indent_pop (&writer);
12761 mono_json_writer_indent (&writer);
12762 mono_json_writer_array_end (&writer);
12763 mono_json_writer_printf (&writer, ",\n");
12765 // PLT entries
12766 #ifdef DUMP_PLT
12767 mono_json_writer_indent_push (&writer);
12768 mono_json_writer_indent (&writer);
12769 mono_json_writer_object_key(&writer, "plt");
12770 mono_json_writer_array_begin (&writer);
12772 for (i = 0; i < acfg->plt_offset; ++i) {
12773 MonoPltEntry *plt_entry = NULL;
12774 MonoJumpInfo *ji;
12776 if (i == 0)
12778 * The first plt entry is unused.
12780 continue;
12782 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12783 ji = plt_entry->ji;
12785 mono_json_writer_indent (&writer);
12786 mono_json_writer_printf (&writer, "{ ");
12787 mono_json_writer_object_key(&writer, "symbol");
12788 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12791 mono_json_writer_indent_pop (&writer);
12792 mono_json_writer_indent (&writer);
12793 mono_json_writer_array_end (&writer);
12794 mono_json_writer_printf (&writer, ",\n");
12795 #endif
12797 // GOT entries
12798 #ifdef DUMP_GOT
12799 mono_json_writer_indent_push (&writer);
12800 mono_json_writer_indent (&writer);
12801 mono_json_writer_object_key(&writer, "got");
12802 mono_json_writer_array_begin (&writer);
12804 mono_json_writer_indent_push (&writer);
12805 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12806 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12808 mono_json_writer_indent (&writer);
12809 mono_json_writer_printf (&writer, "{ ");
12810 mono_json_writer_object_key(&writer, "patch_name");
12811 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12814 mono_json_writer_indent_pop (&writer);
12815 mono_json_writer_indent (&writer);
12816 mono_json_writer_array_end (&writer);
12817 mono_json_writer_printf (&writer, ",\n");
12818 #endif
12820 mono_json_writer_indent_pop (&writer);
12821 mono_json_writer_indent (&writer);
12822 mono_json_writer_object_end (&writer);
12824 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12825 dumpfile = fopen (dumpname, "w+");
12826 g_free (dumpname);
12828 fprintf (dumpfile, "%s", writer.text->str);
12829 fclose (dumpfile);
12831 mono_json_writer_destroy (&writer);
12834 static const MonoJitICallId preinited_jit_icalls [] = {
12835 MONO_JIT_ICALL_mini_llvm_init_method,
12836 MONO_JIT_ICALL_mini_llvm_init_gshared_method_this,
12837 MONO_JIT_ICALL_mini_llvm_init_gshared_method_mrgctx,
12838 MONO_JIT_ICALL_mini_llvm_init_gshared_method_vtable,
12839 MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
12840 MONO_JIT_ICALL_mono_llvm_throw_corlib_exception,
12841 MONO_JIT_ICALL_mono_threads_state_poll,
12842 MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
12843 MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
12844 MONO_JIT_ICALL_mono_fill_method_rgctx,
12845 MONO_JIT_ICALL_mono_fill_class_rgctx
12848 static void
12849 add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
12851 if (!acfg->aot_opts.llvm_only)
12852 get_got_offset (acfg, FALSE, ji);
12853 get_got_offset (acfg, TRUE, ji);
12856 static void
12857 add_preinit_got_slots (MonoAotCompile *acfg)
12859 MonoJumpInfo *ji;
12860 int i;
12863 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12864 * during method initialization etc.
12867 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12868 ji->type = MONO_PATCH_INFO_IMAGE;
12869 ji->data.image = acfg->image;
12870 add_preinit_slot (acfg, ji);
12872 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12873 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12874 add_preinit_slot (acfg, ji);
12876 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12877 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12878 add_preinit_slot (acfg, ji);
12880 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12881 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12882 add_preinit_slot (acfg, ji);
12884 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12885 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12886 add_preinit_slot (acfg, ji);
12888 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12889 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12890 add_preinit_slot (acfg, ji);
12892 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12893 ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
12894 add_preinit_slot (acfg, ji);
12896 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12897 ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
12898 add_preinit_slot (acfg, ji);
12900 if (!acfg->aot_opts.llvm_only) {
12901 for (i = 0; i < TLS_KEY_NUM; i++) {
12902 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12903 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12904 ji->data.index = i;
12905 add_preinit_slot (acfg, ji);
12907 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12908 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12909 ji->data.index = i;
12910 add_preinit_slot (acfg, ji);
12914 /* Called by native-to-managed wrappers on possibly unattached threads */
12915 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12916 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12917 ji->data.jit_icall_id = MONO_JIT_ICALL_mono_threads_attach_coop;
12918 add_preinit_slot (acfg, ji);
12920 for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
12921 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12922 ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
12923 ji->data.jit_icall_id = preinited_jit_icalls [i];
12924 add_preinit_slot (acfg, ji);
12927 if (acfg->aot_opts.llvm_only)
12928 acfg->nshared_got_entries = acfg->llvm_got_offset;
12929 else
12930 acfg->nshared_got_entries = acfg->got_offset;
12931 g_assert (acfg->nshared_got_entries);
12934 static void
12935 mono_dedup_log_stats (MonoAotCompile *acfg)
12937 GHashTableIter iter;
12938 g_assert (acfg->dedup_stats);
12940 if (!acfg->dedup_emit_mode)
12941 return;
12943 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12944 // deduped modules
12945 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12946 MonoCompile *dcfg = NULL;
12947 MonoMethod *method = NULL;
12949 size_t wrappers_size_saved = 0;
12950 size_t inflated_size_saved = 0;
12951 size_t copied_singles = 0;
12952 int wrappers_saved = 0;
12953 int instances_saved = 0;
12954 int copied = 0;
12956 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12957 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12958 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12960 if (count == 0)
12961 continue;
12963 if (acfg->dedup_emit_mode) {
12964 // Size *saved* is the size due to things not emitted.
12965 if (count < 2) {
12966 // Just moved, didn't save space / dedup
12967 copied ++;
12968 copied_singles += dcfg->code_len;
12969 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12970 wrappers_saved ++;
12971 wrappers_size_saved += dcfg->code_len * (count - 1);
12972 } else {
12973 instances_saved ++;
12974 inflated_size_saved += dcfg->code_len * (count - 1);
12977 if (acfg->aot_opts.dedup) {
12978 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12979 wrappers_saved ++;
12980 wrappers_size_saved += dcfg->code_len * count;
12981 } else {
12982 instances_saved ++;
12983 inflated_size_saved += dcfg->code_len * count;
12988 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %zu bytes\n", wrappers_saved, wrappers_size_saved);
12989 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %zu bytes\n", instances_saved, inflated_size_saved);
12990 if (acfg->dedup_emit_mode)
12991 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %zu bytes\n", copied, copied_singles);
12993 g_hash_table_destroy (acfg->dedup_stats);
12994 acfg->dedup_stats = NULL;
12997 // Flush the cache to tell future calls what to skip
12998 static void
12999 mono_flush_method_cache (MonoAotCompile *acfg)
13001 GHashTable *method_cache = acfg->dedup_cache;
13002 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
13003 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
13004 g_free (filename);
13005 return;
13008 acfg->dedup_cache = NULL;
13010 FILE *cache = fopen (filename, "w");
13012 if (!cache)
13013 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
13015 GHashTableIter iter;
13016 gchar *name = NULL;
13017 g_hash_table_iter_init (&iter, method_cache);
13018 gboolean cont = TRUE;
13019 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
13020 int res = fprintf (cache, "%s\n", name);
13021 cont = res >= 0;
13023 // FIXME: don't assert if error when flushing
13024 g_assert (cont);
13026 fclose (cache);
13027 g_free (filename);
13029 // The keys are all in the imageset, nothing to free
13030 // Values are just pointers to memory owned elsewhere, or sentinels
13031 g_hash_table_destroy (method_cache);
13034 // Read in what has been emitted by previous invocations,
13035 // what can be skipped
13036 static void
13037 mono_read_method_cache (MonoAotCompile *acfg)
13039 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
13040 // Only do once, when dedup_cache is null
13041 if (acfg->dedup_cache)
13042 goto early_exit;
13044 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
13045 g_assert (acfg->dedup_stats);
13047 // only in skip mode
13048 if (!acfg->aot_opts.dedup)
13049 goto early_exit;
13051 g_assert (acfg->dedup_cache);
13053 FILE *cache;
13054 cache = fopen (filename, "r");
13055 if (!cache)
13056 goto early_exit;
13058 // Since we do pointer comparisons, and it can't be allocated at
13059 // the address 0x1 due to alignment, we use this as a sentinel
13060 gpointer other_acfg_sentinel;
13061 other_acfg_sentinel = GINT_TO_POINTER (0x1);
13063 if (fseek (cache, 0L, SEEK_END))
13064 goto cleanup;
13066 size_t fileLength;
13067 fileLength = ftell (cache);
13068 g_assert (fileLength > 0);
13070 if (fseek (cache, 0L, SEEK_SET))
13071 goto cleanup;
13073 // Avoid thousands of new malloc entries
13074 // FIXME: allocate into imageset, so we don't need to free.
13075 // put the other mangled names there too.
13076 char *bulk;
13077 bulk = g_malloc0 (fileLength * sizeof (char));
13078 size_t offset;
13079 offset = 0;
13081 while (fgets (&bulk [offset], fileLength - offset, cache)) {
13082 // strip newline
13083 char *line = &bulk [offset];
13084 size_t len = strlen (line);
13085 if (len == 0)
13086 break;
13088 if (len >= 0 && line [len] == '\n')
13089 line [len] = '\0';
13090 offset += strlen (line) + 1;
13091 g_assert (fileLength >= offset);
13093 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
13096 cleanup:
13097 fclose (cache);
13099 early_exit:
13100 g_free (filename);
13101 return;
13104 typedef struct {
13105 GHashTable *cache;
13106 GHashTable *stats;
13107 gboolean emit_inflated_methods;
13108 MonoAssembly *inflated_assembly;
13109 } MonoAotState;
13111 static MonoAotState *
13112 alloc_aot_state (void)
13114 MonoAotState *state = g_malloc (sizeof (MonoAotState));
13115 // FIXME: Should this own the memory?
13116 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
13117 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
13118 // Start in "collect mode"
13119 state->emit_inflated_methods = FALSE;
13120 state->inflated_assembly = NULL;
13121 return state;
13124 static void
13125 free_aot_state (MonoAotState *astate)
13127 g_hash_table_destroy (astate->cache);
13128 g_free (astate);
13131 static void
13132 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
13134 GHashTableIter iter;
13135 gchar *name = NULL;
13136 MonoMethod *method = NULL;
13138 acfg->dedup_emit_mode = TRUE;
13140 g_hash_table_iter_init (&iter, astate->cache);
13141 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
13142 add_method_full (acfg, method, TRUE, 0);
13144 return;
13147 static void
13148 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
13150 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
13151 return;
13153 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
13154 // Thread the state through when making the inflate pass
13155 *astate = *global_aot_state;
13158 if (!*astate) {
13159 *astate = alloc_aot_state ();
13160 *global_aot_state = *astate;
13163 acfg->dedup_cache = (*astate)->cache;
13164 acfg->dedup_stats = (*astate)->stats;
13166 // fills out acfg->dedup_cache
13167 if (acfg->aot_opts.dedup)
13168 mono_read_method_cache (acfg);
13170 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
13171 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
13172 gchar *asm_file = NULL;
13174 // Get the last part of the path, the filename
13175 for (int i=0; asm_path [i] != NULL; i++)
13176 asm_file = asm_path [i];
13178 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
13179 // Save
13180 *is_dedup_dummy = TRUE;
13181 (*astate)->inflated_assembly = ass;
13183 g_strfreev (asm_path);
13184 } else if ((*astate)->inflated_assembly) {
13185 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
13189 int
13190 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13192 // create assembly, loop and add extra_methods
13193 // in add_generic_instances , rip out what's in that for loop
13194 // and apply that to this aot_state inside of mono_compile_assembly
13195 MonoAotState *astate;
13196 astate = *(MonoAotState **)aot_state;
13197 g_assert (astate);
13199 // FIXME: allow suffixes?
13200 if (!astate->inflated_assembly) {
13201 const char* inflate = strstr (aot_options, "dedup-inflate");
13202 if (!inflate)
13203 return 0;
13204 else
13205 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
13208 // Switch modes
13209 astate->emit_inflated_methods = TRUE;
13211 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
13213 *aot_state = NULL;
13214 free_aot_state (astate);
13216 return res;
13219 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13220 static MonoMethodSignature * const * const interp_in_static_sigs [] = {
13221 &mono_icall_sig_bool_ptr_int32_ptrref,
13222 &mono_icall_sig_bool_ptr_ptrref,
13223 &mono_icall_sig_int32_int32_ptrref,
13224 &mono_icall_sig_int32_int32_ptr_ptrref,
13225 &mono_icall_sig_int32_ptr_int32_ptr,
13226 &mono_icall_sig_int32_ptr_int32_ptrref,
13227 &mono_icall_sig_int32_ptr_ptrref,
13228 &mono_icall_sig_object_object_ptr_ptr_ptr,
13229 &mono_icall_sig_object,
13230 &mono_icall_sig_ptr_int32_ptrref,
13231 &mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
13232 &mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
13233 &mono_icall_sig_ptr_ptr_int32_ptrref,
13234 &mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
13235 &mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
13236 &mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
13237 &mono_icall_sig_ptr_ptr_ptr_ptrref,
13238 &mono_icall_sig_ptr_ptr_ptrref,
13239 &mono_icall_sig_ptr_ptr_uint32_ptrref,
13240 &mono_icall_sig_ptr_uint32_ptrref,
13241 &mono_icall_sig_void_object_ptr_ptr_ptr,
13242 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
13243 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
13244 &mono_icall_sig_void_ptr_ptr_ptrref,
13245 &mono_icall_sig_void_ptr_ptrref,
13246 &mono_icall_sig_void_ptr,
13247 &mono_icall_sig_void_int32_ptrref,
13248 &mono_icall_sig_void_uint32_ptrref,
13249 &mono_icall_sig_void,
13251 #endif
13254 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
13256 MonoImage *image = ass->image;
13257 int res;
13258 MonoAotCompile *acfg;
13259 char *p;
13260 TV_DECLARE (atv);
13261 TV_DECLARE (btv);
13263 acfg = acfg_create (ass, opts);
13265 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
13266 acfg->aot_opts.write_symbols = TRUE;
13267 acfg->aot_opts.ntrampolines = 4096;
13268 acfg->aot_opts.nrgctx_trampolines = 4096;
13269 acfg->aot_opts.nimt_trampolines = 512;
13270 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
13271 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
13272 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13273 acfg->aot_opts.nftnptr_arg_trampolines = 128;
13274 #endif
13275 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
13276 if (!acfg->aot_opts.llvm_path)
13277 acfg->aot_opts.llvm_path = g_strdup ("");
13278 acfg->aot_opts.temp_path = g_strdup ("");
13279 #ifdef MONOTOUCH
13280 acfg->aot_opts.use_trampolines_page = TRUE;
13281 #endif
13282 acfg->aot_opts.clangxx = g_strdup ("clang++");
13284 mono_aot_parse_options (aot_options, &acfg->aot_opts);
13286 // start dedup
13287 MonoAotState *astate = NULL;
13288 gboolean is_dedup_dummy = FALSE;
13289 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
13291 // Process later
13292 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
13293 return 0;
13295 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13296 acfg->dedup_collect_only = TRUE;
13297 // end dedup
13299 if (acfg->aot_opts.logfile) {
13300 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
13303 if (acfg->aot_opts.data_outfile) {
13304 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
13305 if (!acfg->data_outfile) {
13306 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
13307 return 1;
13309 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
13312 //acfg->aot_opts.print_skipped_methods = TRUE;
13314 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
13315 if (acfg->opts & MONO_OPT_GSHAREDVT) {
13316 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
13317 return 1;
13319 if (acfg->aot_opts.llvm_only) {
13320 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
13321 return 1;
13323 #else
13324 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13325 acfg->opts |= MONO_OPT_GSHAREDVT;
13326 #endif
13328 #if !defined(ENABLE_LLVM)
13329 if (acfg->aot_opts.llvm_only) {
13330 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
13331 return 1;
13333 #endif
13335 if (acfg->opts & MONO_OPT_GSHAREDVT)
13336 mono_set_generic_sharing_vt_supported (TRUE);
13338 if (!acfg->dedup_collect_only)
13339 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
13341 if (!acfg->aot_opts.deterministic)
13342 generate_aotid ((guint8*) &acfg->image->aotid);
13344 char *aotid = mono_guid_to_string (acfg->image->aotid);
13345 if (!acfg->dedup_collect_only)
13346 aot_printf (acfg, "AOTID %s\n", aotid);
13347 g_free (aotid);
13349 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
13350 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13351 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
13352 return 1;
13354 #endif
13356 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
13357 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
13358 return 1;
13361 if (acfg->aot_opts.static_link)
13362 acfg->aot_opts.asm_writer = TRUE;
13364 if (acfg->aot_opts.soft_debug) {
13365 MonoDebugOptions *opt = mini_get_debug_options ();
13367 opt->mdb_optimizations = TRUE;
13368 opt->gen_sdb_seq_points = TRUE;
13370 if (!mono_debug_enabled ()) {
13371 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
13372 return 1;
13374 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
13377 if (acfg->aot_opts.try_llvm)
13378 acfg->aot_opts.llvm = mini_llvm_init ();
13380 if (mono_use_llvm || acfg->aot_opts.llvm) {
13381 acfg->llvm = TRUE;
13382 acfg->aot_opts.asm_writer = TRUE;
13383 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
13385 if (acfg->aot_opts.soft_debug) {
13386 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
13387 return 1;
13390 mini_llvm_init ();
13392 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
13393 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
13394 return 1;
13398 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13399 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
13400 acfg->is_full_aot = TRUE;
13403 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13404 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
13405 acfg->is_full_aot = TRUE;
13408 if (mini_safepoints_enabled ())
13409 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
13411 // The methods in dedup-emit amodules must be available on runtime startup
13412 // Note: Only one such amodule can have this attribute
13413 if (astate && astate->emit_inflated_methods)
13414 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
13417 if (acfg->aot_opts.instances_logfile_path) {
13418 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
13419 if (!acfg->instances_logfile) {
13420 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
13421 return 1;
13425 if (acfg->aot_opts.profile_files) {
13426 GList *l;
13428 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
13429 load_profile_file (acfg, (char*)l->data);
13433 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13434 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
13435 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
13438 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
13439 #ifdef MONO_ARCH_GSHARED_SUPPORTED
13440 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
13441 #endif
13442 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
13443 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
13444 if (acfg->opts & MONO_OPT_GSHAREDVT)
13445 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
13446 #endif
13447 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13448 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
13449 #endif
13450 acfg->num_trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = mono_aot_mode_is_interp (&acfg->aot_opts) && mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nunbox_arbitrary_trampolines : 0;
13452 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
13454 arch_init (acfg);
13456 if (mono_use_llvm || acfg->aot_opts.llvm) {
13458 * Emit all LLVM code into a separate assembly/object file and link with it
13459 * normally.
13461 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13462 acfg->llvm_owriter = TRUE;
13463 } else if (acfg->aot_opts.llvm_outfile) {
13464 int len = strlen (acfg->aot_opts.llvm_outfile);
13466 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13467 acfg->llvm_owriter = TRUE;
13471 if (acfg->llvm && acfg->thumb_mixed)
13472 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13473 if (acfg->aot_opts.llvm_only)
13474 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13476 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13477 /* Get rid of characters which cannot occur in symbols */
13478 for (p = acfg->assembly_name_sym; *p; ++p) {
13479 if (!(isalnum (*p) || *p == '_'))
13480 *p = '_';
13483 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13484 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13485 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13486 if (acfg->llvm) {
13487 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13488 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13491 acfg->method_index = 1;
13493 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13494 mono_set_partial_sharing_supported (TRUE);
13496 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13497 res = collect_methods (acfg);
13498 if (!res)
13499 return 1;
13502 // If we're emitting all of the inflated methods into a dummy
13503 // Assembly, then after extra_methods is set up, we're done
13504 // in this function.
13505 if (astate && astate->emit_inflated_methods)
13506 mono_add_deferred_extra_methods (acfg, astate);
13509 GList *l;
13511 for (l = acfg->profile_data; l; l = l->next)
13512 resolve_profile_data (acfg, (ProfileData*)l->data, ass);
13513 for (l = acfg->profile_data; l; l = l->next)
13514 add_profile_instances (acfg, (ProfileData*)l->data);
13517 acfg->cfgs_size = acfg->methods->len + 32;
13518 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13520 /* PLT offset 0 is reserved for the PLT trampoline */
13521 acfg->plt_offset = 1;
13522 add_preinit_got_slots (acfg);
13524 #ifdef ENABLE_LLVM
13525 if (acfg->llvm) {
13526 llvm_acfg = acfg;
13527 LLVMModuleFlags flags = 0;
13528 #ifdef EMIT_DWARF_INFO
13529 flags = LLVM_MODULE_FLAG_DWARF;
13530 #endif
13531 #ifdef EMIT_WIN32_CODEVIEW_INFO
13532 flags = LLVM_MODULE_FLAG_CODEVIEW;
13533 #endif
13534 if (acfg->aot_opts.static_link)
13535 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
13536 if (acfg->aot_opts.llvm_only)
13537 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
13538 if (acfg->aot_opts.interp)
13539 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
13540 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
13542 add_lazy_init_wrappers (acfg);
13544 #endif
13546 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
13547 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
13548 add_method (acfg, wrapper);
13550 wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
13551 add_method (acfg, wrapper);
13553 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13554 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++) {
13555 MonoMethodSignature *sig = *interp_in_static_sigs [i];
13556 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13557 sig->pinvoke = FALSE;
13558 wrapper = mini_get_interp_in_wrapper (sig);
13559 add_method (acfg, wrapper);
13561 #endif
13563 /* required for mixed mode */
13564 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
13565 add_gc_wrappers (acfg);
13567 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
13568 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
13572 TV_GETTIME (atv);
13574 compile_methods (acfg);
13576 TV_GETTIME (btv);
13578 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13580 dedup_skip_methods (acfg);
13582 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13583 /* We only collected methods from this assembly */
13584 return 0;
13586 return emit_aot_image (acfg);
13589 static void
13590 print_stats (MonoAotCompile *acfg)
13592 int i;
13593 gint64 all_sizes;
13594 char llvm_stats_msg [256];
13596 if (acfg->llvm && !acfg->aot_opts.llvm_only)
13597 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13598 else
13599 strcpy (llvm_stats_msg, "");
13601 all_sizes = acfg->stats.code_size + acfg->stats.method_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;
13603 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, BLOB: %d\n",
13604 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13605 (int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
13606 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13607 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13608 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13609 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,
13610 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13611 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13612 (int)(acfg->got_offset * sizeof (target_mgreg_t)),
13613 (int)acfg->stats.blob_size);
13614 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13615 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13616 llvm_stats_msg,
13617 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13618 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13619 if (acfg->stats.genericcount)
13620 aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13621 if (acfg->stats.abscount)
13622 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13623 if (acfg->stats.lmfcount)
13624 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13625 if (acfg->stats.ocount)
13626 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13628 aot_printf (acfg, "GOT slot distribution:\n");
13629 int nslots = 0;
13630 int size = 0;
13631 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
13632 nslots += acfg->stats.got_slot_types [i];
13633 size += acfg->stats.got_slot_info_sizes [i];
13634 if (acfg->stats.got_slot_types [i])
13635 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]);
13637 aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
13639 aot_printf (acfg, "\nEncoding stats:\n");
13640 aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
13641 aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
13642 aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
13644 aot_printf (acfg, "\nMethod stats:\n");
13645 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13646 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13647 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13648 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13650 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13651 mono_dedup_log_stats (acfg);
13654 static void
13655 create_depfile (MonoAotCompile *acfg)
13657 FILE *depfile;
13659 // FIXME: Support other configurations
13660 g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
13662 depfile = fopen (acfg->aot_opts.depfile, "w");
13663 g_assert (depfile);
13665 int ntargets = 1;
13666 char **targets = g_new0 (char*, ntargets);
13667 targets [0] = acfg->aot_opts.llvm_outfile;
13668 for (int tindex = 0; tindex < ntargets; ++tindex) {
13669 fprintf (depfile, "%s: ", targets [tindex]);
13670 for (int i = 0; i < acfg->image_table->len; i++) {
13671 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
13672 fprintf (depfile, " %s", image->filename);
13674 fprintf (depfile, "\n");
13676 g_free (targets);
13677 fclose (depfile);
13680 static int
13681 emit_aot_image (MonoAotCompile *acfg)
13683 int i, res;
13684 TV_DECLARE (atv);
13685 TV_DECLARE (btv);
13687 TV_GETTIME (atv);
13689 #ifdef ENABLE_LLVM
13690 if (acfg->llvm) {
13691 if (acfg->aot_opts.asm_only) {
13692 if (acfg->aot_opts.outfile) {
13693 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13694 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13695 } else {
13696 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13697 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13699 g_assert (acfg->aot_opts.llvm_outfile);
13700 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13701 if (acfg->llvm_owriter)
13702 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13703 else
13704 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13705 } else {
13706 gchar *temp_path;
13707 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13708 temp_path = g_strdup (acfg->aot_opts.temp_path);
13709 } else {
13710 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13711 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13712 acfg->temp_dir_to_delete = g_strdup (temp_path);
13715 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
13716 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13717 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13718 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13720 g_free (temp_path);
13723 #endif
13725 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13726 if (acfg->aot_opts.outfile)
13727 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13728 else
13729 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13730 acfg->fp = fopen (acfg->tmpfname, "w+");
13731 } else {
13732 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13733 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13734 acfg->fp = fdopen (i, "w+");
13735 } else {
13736 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
13737 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13738 acfg->fp = fopen (acfg->tmpfname, "w+");
13741 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13742 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13743 return 1;
13745 if (acfg->fp)
13746 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13748 /* Compute symbols for methods */
13749 for (i = 0; i < acfg->nmethods; ++i) {
13750 if (acfg->cfgs [i]) {
13751 MonoCompile *cfg = acfg->cfgs [i];
13752 int method_index = get_method_index (acfg, cfg->orig_method);
13754 if (cfg->asm_symbol) {
13755 // Set by method emitter in backend
13756 if (acfg->llvm_label_prefix) {
13757 char *old_symbol = cfg->asm_symbol;
13758 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
13759 g_free (old_symbol);
13761 } else if (COMPILE_LLVM (cfg)) {
13762 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13763 } else if (acfg->global_symbols || acfg->llvm) {
13764 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13765 } else {
13766 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13768 cfg->asm_debug_symbol = cfg->asm_symbol;
13772 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13774 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13776 acfg->gas_line_numbers = TRUE;
13779 #ifdef EMIT_DWARF_INFO
13780 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13781 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13782 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13783 return 1;
13785 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13787 #endif /* EMIT_DWARF_INFO */
13789 if (acfg->w)
13790 mono_img_writer_emit_start (acfg->w);
13792 if (acfg->dwarf)
13793 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13795 if (acfg->aot_opts.dedup)
13796 mono_flush_method_cache (acfg);
13798 emit_code (acfg);
13800 emit_info (acfg);
13802 emit_extra_methods (acfg);
13804 emit_trampolines (acfg);
13806 emit_class_name_table (acfg);
13808 emit_got_info (acfg, FALSE);
13809 if (acfg->llvm)
13810 emit_got_info (acfg, TRUE);
13812 emit_exception_info (acfg);
13814 emit_unwind_info (acfg);
13816 emit_class_info (acfg);
13818 emit_plt (acfg);
13820 emit_image_table (acfg);
13822 emit_weak_field_indexes (acfg);
13824 emit_got (acfg);
13828 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13829 * in another.
13831 const char *gc_name = mono_gc_get_gc_name ();
13832 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13835 emit_blob (acfg);
13837 emit_objc_selectors (acfg);
13839 emit_globals (acfg);
13841 emit_file_info (acfg);
13843 if (acfg->dwarf) {
13844 emit_dwarf_info (acfg);
13845 mono_dwarf_writer_close (acfg->dwarf);
13846 } else {
13847 if (!acfg->aot_opts.nodebug)
13848 emit_codeview_info (acfg);
13851 emit_mem_end (acfg);
13853 if (acfg->need_pt_gnu_stack) {
13854 /* This is required so the .so doesn't have an executable stack */
13855 /* The bin writer already emits this */
13856 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13859 if (acfg->aot_opts.data_outfile)
13860 fclose (acfg->data_outfile);
13862 #ifdef ENABLE_LLVM
13863 if (acfg->llvm) {
13864 gboolean res;
13866 res = emit_llvm_file (acfg);
13867 if (!res)
13868 return 1;
13870 #endif
13872 emit_library_info (acfg);
13874 TV_GETTIME (btv);
13876 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13878 if (!acfg->aot_opts.stats)
13879 aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
13881 TV_GETTIME (atv);
13882 if (acfg->w) {
13883 res = mono_img_writer_emit_writeout (acfg->w);
13884 if (res != 0) {
13885 acfg_free (acfg);
13886 return res;
13888 res = compile_asm (acfg);
13889 if (res != 0) {
13890 acfg_free (acfg);
13891 return res;
13894 TV_GETTIME (btv);
13895 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13897 if (acfg->aot_opts.stats)
13898 print_stats (acfg);
13900 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);
13902 if (acfg->aot_opts.depfile)
13903 create_depfile (acfg);
13905 if (acfg->aot_opts.dump_json)
13906 aot_dump (acfg);
13908 if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
13909 char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
13910 execute_system (command);
13911 g_free (command);
13914 acfg_free (acfg);
13916 return 0;
13919 #else
13921 /* AOT disabled */
13923 void*
13924 mono_aot_readonly_field_override (MonoClassField *field)
13926 return NULL;
13930 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13932 return 0;
13935 gboolean
13936 mono_aot_is_shared_got_offset (int offset)
13938 return FALSE;
13942 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13944 g_assert_not_reached ();
13945 return 0;
13948 gboolean
13949 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
13951 g_assert_not_reached ();
13952 return 0;
13955 #endif