[interp] add another signature for interp_in wrappers
[mono-project.git] / mono / mini / aot-compiler.c
blobdab123f4b7d8b0126f745de495f51e80654c7908
1 /**
2 * \file
3 * mono Ahead of Time compiler
5 * Author:
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
8 * Johan Lorensson (lateralusx.github@gmail.com)
10 * (C) 2002 Ximian, Inc.
11 * Copyright 2003-2011 Novell, Inc
12 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include "config.h"
17 #include <sys/types.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_STDINT_H
22 #include <stdint.h>
23 #endif
24 #include <fcntl.h>
25 #include <ctype.h>
26 #include <string.h>
27 #ifndef HOST_WIN32
28 #include <sys/time.h>
29 #else
30 #include <winsock2.h>
31 #include <windows.h>
32 #endif
34 #include <errno.h>
35 #include <sys/stat.h>
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/metadata/custom-attrs-internals.h>
53 #include <mono/utils/mono-logger-internals.h>
54 #include <mono/utils/mono-compiler.h>
55 #include <mono/utils/mono-time.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-rand.h>
58 #include <mono/utils/json.h>
59 #include <mono/utils/mono-threads-coop.h>
60 #include <mono/profiler/aot.h>
61 #include <mono/utils/w32api.h>
63 #include "aot-compiler.h"
64 #include "aot-runtime.h"
65 #include "seq-points.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68 #include "mini-gc.h"
69 #include "mini-llvm.h"
70 #include "mini-runtime.h"
72 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
74 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
75 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
76 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
77 #define TARGET_X86_64_WIN32_MSVC
78 #endif
80 #if defined(TARGET_X86_64_WIN32_MSVC)
81 #define TARGET_WIN32_MSVC
82 #endif
84 // Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
85 // works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
86 // compiling for AMD64 (Windows x64 platforms).
87 #if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
88 #define EMIT_WIN32_UNWIND_INFO
89 #endif
91 #if defined(__linux__)
92 #define RODATA_SECT ".rodata"
93 #elif defined(TARGET_MACH)
94 #define RODATA_SECT ".section __TEXT, __const"
95 #elif defined(TARGET_WIN32_MSVC)
96 #define RODATA_SECT ".rdata"
97 #else
98 #define RODATA_SECT ".text"
99 #endif
101 #define TV_DECLARE(name) gint64 name
102 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
103 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
105 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
107 typedef struct {
108 char *name;
109 MonoImage *image;
110 } ImageProfileData;
112 typedef struct ClassProfileData ClassProfileData;
114 typedef struct {
115 int argc;
116 ClassProfileData **argv;
117 MonoGenericInst *inst;
118 } GInstProfileData;
120 struct ClassProfileData {
121 ImageProfileData *image;
122 char *ns, *name;
123 GInstProfileData *inst;
124 MonoClass *klass;
127 typedef struct {
128 ClassProfileData *klass;
129 int id;
130 char *name;
131 int param_count;
132 char *signature;
133 GInstProfileData *inst;
134 MonoMethod *method;
135 } MethodProfileData;
137 typedef struct {
138 GHashTable *images, *classes, *ginsts, *methods;
139 } ProfileData;
141 /* predefined values for static readonly fields without needed to run the .cctor */
142 typedef struct _ReadOnlyValue ReadOnlyValue;
143 struct _ReadOnlyValue {
144 ReadOnlyValue *next;
145 char *name;
146 int type; /* to be used later for typechecking to prevent user errors */
147 union {
148 guint8 i1;
149 guint16 i2;
150 guint32 i4;
151 guint64 i8;
152 gpointer ptr;
153 } value;
155 static ReadOnlyValue *readonly_values;
157 typedef struct MonoAotOptions {
158 char *outfile;
159 char *llvm_outfile;
160 char *data_outfile;
161 GList *profile_files;
162 gboolean save_temps;
163 gboolean write_symbols;
164 gboolean metadata_only;
165 gboolean bind_to_runtime_version;
166 MonoAotMode mode;
167 gboolean no_dlsym;
168 gboolean static_link;
169 gboolean asm_only;
170 gboolean asm_writer;
171 gboolean nodebug;
172 gboolean dwarf_debug;
173 gboolean soft_debug;
174 gboolean log_generics;
175 gboolean log_instances;
176 gboolean gen_msym_dir;
177 char *gen_msym_dir_path;
178 gboolean direct_pinvoke;
179 gboolean direct_icalls;
180 gboolean no_direct_calls;
181 gboolean use_trampolines_page;
182 gboolean no_instances;
183 // We are collecting inflated methods and emitting non-inflated
184 gboolean dedup;
185 // The name of the assembly for which the AOT module is going to have all deduped methods moved to.
186 // When set, we are emitting inflated methods only
187 char *dedup_include;
188 gboolean gnu_asm;
189 gboolean llvm;
190 gboolean llvm_only;
191 int nthreads;
192 int ntrampolines;
193 int nrgctx_trampolines;
194 int nimt_trampolines;
195 int ngsharedvt_arg_trampolines;
196 int nrgctx_fetch_trampolines;
197 gboolean print_skipped_methods;
198 gboolean stats;
199 gboolean verbose;
200 char *tool_prefix;
201 char *ld_flags;
202 char *mtriple;
203 char *llvm_path;
204 char *temp_path;
205 char *instances_logfile_path;
206 char *logfile;
207 gboolean dump_json;
208 gboolean profile_only;
209 } MonoAotOptions;
211 typedef enum {
212 METHOD_CAT_NORMAL,
213 METHOD_CAT_GSHAREDVT,
214 METHOD_CAT_INST,
215 METHOD_CAT_WRAPPER,
216 METHOD_CAT_NUM
217 } MethodCategory;
219 typedef struct MonoAotStats {
220 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
221 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
222 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
223 int got_slots, offsets_size;
224 int method_categories [METHOD_CAT_NUM];
225 int got_slot_types [MONO_PATCH_INFO_NUM];
226 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
227 int jit_time, gen_time, link_time;
228 } MonoAotStats;
230 typedef struct GotInfo {
231 GHashTable *patch_to_got_offset;
232 GHashTable **patch_to_got_offset_by_type;
233 GPtrArray *got_patches;
234 } GotInfo;
236 #ifdef EMIT_WIN32_UNWIND_INFO
237 typedef struct _UnwindInfoSectionCacheItem {
238 char *xdata_section_label;
239 PUNWIND_INFO unwind_info;
240 gboolean xdata_section_emitted;
241 } UnwindInfoSectionCacheItem;
242 #endif
244 typedef struct MonoAotCompile {
245 MonoImage *image;
246 GPtrArray *methods;
247 GHashTable *method_indexes;
248 GHashTable *method_depth;
249 MonoCompile **cfgs;
250 int cfgs_size;
251 GHashTable **patch_to_plt_entry;
252 GHashTable *plt_offset_to_entry;
253 //GHashTable *patch_to_got_offset;
254 //GHashTable **patch_to_got_offset_by_type;
255 //GPtrArray *got_patches;
256 GotInfo got_info, llvm_got_info;
257 GHashTable *image_hash;
258 GHashTable *method_to_cfg;
259 GHashTable *token_info_hash;
260 GHashTable *method_to_pinvoke_import;
261 GPtrArray *extra_methods;
262 GPtrArray *image_table;
263 GPtrArray *globals;
264 GPtrArray *method_order;
265 GHashTable *dedup_stats;
266 GHashTable *dedup_cache;
267 gboolean dedup_cache_changed;
268 GHashTable *export_names;
269 /* Maps MonoClass* -> blob offset */
270 GHashTable *klass_blob_hash;
271 /* Maps MonoMethod* -> blob offset */
272 GHashTable *method_blob_hash;
273 GHashTable *gsharedvt_in_signatures;
274 GHashTable *gsharedvt_out_signatures;
275 guint32 *plt_got_info_offsets;
276 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
277 /* Number of GOT entries reserved for trampolines */
278 guint32 num_trampoline_got_entries;
279 guint32 tramp_page_size;
281 guint32 table_offsets [MONO_AOT_TABLE_NUM];
282 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
283 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
284 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
285 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
287 MonoAotOptions aot_opts;
288 guint32 nmethods;
289 guint32 opts;
290 guint32 simd_opts;
291 MonoMemPool *mempool;
292 MonoAotStats stats;
293 int method_index;
294 char *static_linking_symbol;
295 mono_mutex_t mutex;
296 gboolean gas_line_numbers;
297 /* Whenever to emit an object file directly from llc */
298 gboolean llvm_owriter;
299 gboolean llvm_owriter_supported;
300 MonoImageWriter *w;
301 MonoDwarfWriter *dwarf;
302 FILE *fp;
303 char *tmpbasename;
304 char *tmpfname;
305 char *llvm_sfile;
306 char *llvm_ofile;
307 GSList *cie_program;
308 GHashTable *unwind_info_offsets;
309 GPtrArray *unwind_ops;
310 guint32 unwind_info_offset;
311 char *global_prefix;
312 char *got_symbol;
313 char *llvm_got_symbol;
314 char *plt_symbol;
315 char *llvm_eh_frame_symbol;
316 GHashTable *method_label_hash;
317 const char *temp_prefix;
318 const char *user_symbol_prefix;
319 const char *llvm_label_prefix;
320 const char *inst_directive;
321 int align_pad_value;
322 guint32 label_generator;
323 gboolean llvm;
324 gboolean has_jitted_code;
325 gboolean is_full_aot;
326 MonoAotFileFlags flags;
327 MonoDynamicStream blob;
328 gboolean blob_closed;
329 GHashTable *typespec_classes;
330 GString *llc_args;
331 GString *as_args;
332 char *assembly_name_sym;
333 GHashTable *plt_entry_debug_sym_cache;
334 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
335 GHashTable *ginst_hash;
336 GHashTable *dwarf_ln_filenames;
337 gboolean global_symbols;
338 int objc_selector_index, objc_selector_index_2;
339 GPtrArray *objc_selectors;
340 GHashTable *objc_selector_to_index;
341 GList *profile_data;
342 GHashTable *profile_methods;
343 #ifdef EMIT_WIN32_UNWIND_INFO
344 GList *unwind_info_section_cache;
345 #endif
346 FILE *logfile;
347 FILE *instances_logfile;
348 FILE *data_outfile;
349 int datafile_offset;
350 int gc_name_offset;
351 // In this mode, we are emitting dedupable methods that we encounter
352 gboolean dedup_emit_mode;
353 } MonoAotCompile;
355 typedef struct {
356 int plt_offset;
357 char *symbol, *llvm_symbol, *debug_sym;
358 MonoJumpInfo *ji;
359 gboolean jit_used, llvm_used;
360 } MonoPltEntry;
362 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
363 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
365 /* This points to the current acfg in LLVM mode */
366 static MonoAotCompile *llvm_acfg;
368 #ifdef HAVE_ARRAY_ELEM_INIT
369 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
370 #define MSGSTRFIELD1(line) str##line
371 static const struct msgstr_t {
372 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
373 #include "patch-info.h"
374 #undef PATCH_INFO
375 } opstr = {
376 #define PATCH_INFO(a,b) b,
377 #include "patch-info.h"
378 #undef PATCH_INFO
380 static const gint16 opidx [] = {
381 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
382 #include "patch-info.h"
383 #undef PATCH_INFO
386 static G_GNUC_UNUSED const char*
387 get_patch_name (int info)
389 return (const char*)&opstr + opidx [info];
392 #else
393 #define PATCH_INFO(a,b) b,
394 static const char* const
395 patch_types [MONO_PATCH_INFO_NUM + 1] = {
396 #include "patch-info.h"
397 NULL
400 static G_GNUC_UNUSED const char*
401 get_patch_name (int info)
403 return patch_types [info];
406 #endif
408 static void
409 mono_flush_method_cache (MonoAotCompile *acfg);
411 static void
412 mono_read_method_cache (MonoAotCompile *acfg);
414 static guint32
415 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
417 static char*
418 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
420 static void
421 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
423 static void
424 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
426 static inline gboolean
427 ignore_cfg (MonoCompile *cfg)
429 return !cfg || cfg->skip;
432 static void
433 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
435 FILE *output;
436 va_list args;
438 if (acfg->logfile)
439 output = acfg->logfile;
440 else
441 output = stdout;
443 va_start (args, format);
444 vfprintf (output, format, args);
445 va_end (args);
448 static void
449 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
451 FILE *output;
452 va_list args;
454 if (acfg->logfile)
455 output = acfg->logfile;
456 else
457 output = stderr;
459 va_start (args, format);
460 vfprintf (output, format, args);
461 va_end (args);
464 static void
465 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
467 FILE *output;
468 va_list args;
470 if (mono_error_ok (error))
471 return;
473 if (acfg->logfile)
474 output = acfg->logfile;
475 else
476 output = stderr;
478 va_start (args, format);
479 vfprintf (output, format, args);
480 va_end (args);
481 mono_error_cleanup (error);
483 if (acfg->is_full_aot && fatal) {
484 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
485 exit (1);
489 /* Wrappers around the image writer functions */
491 #define MAX_SYMBOL_SIZE 256
493 static inline const char *
494 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
496 gsize needed_size = length;
498 g_assert (NULL != symbol);
499 g_assert (NULL != mangled_symbol);
500 g_assert (0 != length);
502 #if defined(TARGET_WIN32) && defined(TARGET_X86)
503 if (symbol && '_' != symbol [0]) {
504 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
505 } else {
506 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
508 #else
509 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
510 #endif
512 g_assert (0 <= needed_size && needed_size < length);
513 return mangled_symbol;
516 static inline char *
517 mangle_symbol_alloc (const char * symbol)
519 g_assert (NULL != symbol);
521 #if defined(TARGET_WIN32) && defined(TARGET_X86)
522 if (symbol && '_' != symbol [0]) {
523 return g_strdup_printf ("_%s", symbol);
525 else {
526 return g_strdup_printf ("%s", symbol);
528 #else
529 return g_strdup_printf ("%s", symbol);
530 #endif
533 static inline void
534 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
536 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
539 #if defined(TARGET_WIN32) && defined(TARGET_X86)
541 static inline void
542 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
544 const char * mangled_symbol_name = name;
545 char * mangled_symbol_name_alloc = NULL;
547 if (TRUE == func) {
548 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
549 mangled_symbol_name = mangled_symbol_name_alloc;
552 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
553 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
555 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
557 if (NULL != mangled_symbol_name_alloc) {
558 g_free (mangled_symbol_name_alloc);
562 #else
564 static inline void
565 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
567 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
570 #endif
572 static inline void
573 emit_label (MonoAotCompile *acfg, const char *name)
575 mono_img_writer_emit_label (acfg->w, name);
578 static inline void
579 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
581 mono_img_writer_emit_bytes (acfg->w, buf, size);
584 static inline void
585 emit_string (MonoAotCompile *acfg, const char *value)
587 mono_img_writer_emit_string (acfg->w, value);
590 static inline void
591 emit_line (MonoAotCompile *acfg)
593 mono_img_writer_emit_line (acfg->w);
596 static inline void
597 emit_alignment (MonoAotCompile *acfg, int size)
599 mono_img_writer_emit_alignment (acfg->w, size);
602 static inline void
603 emit_alignment_code (MonoAotCompile *acfg, int size)
605 if (acfg->align_pad_value)
606 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
607 else
608 mono_img_writer_emit_alignment (acfg->w, size);
611 static inline void
612 emit_padding (MonoAotCompile *acfg, int size)
614 int i;
615 guint8 buf [16];
617 if (acfg->align_pad_value) {
618 for (i = 0; i < 16; ++i)
619 buf [i] = acfg->align_pad_value;
620 } else {
621 memset (buf, 0, sizeof (buf));
624 for (i = 0; i < size; i += 16) {
625 if (size - i < 16)
626 emit_bytes (acfg, buf, size - i);
627 else
628 emit_bytes (acfg, buf, 16);
632 static inline void
633 emit_pointer (MonoAotCompile *acfg, const char *target)
635 mono_img_writer_emit_pointer (acfg->w, target);
638 static inline void
639 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
641 if (prefix [0] != '\0') {
642 char *s = g_strdup_printf ("%s%s", prefix, target);
643 mono_img_writer_emit_pointer (acfg->w, s);
644 g_free (s);
645 } else {
646 mono_img_writer_emit_pointer (acfg->w, target);
650 static inline void
651 emit_int16 (MonoAotCompile *acfg, int value)
653 mono_img_writer_emit_int16 (acfg->w, value);
656 static inline void
657 emit_int32 (MonoAotCompile *acfg, int value)
659 mono_img_writer_emit_int32 (acfg->w, value);
662 static inline void
663 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
665 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
668 static inline void
669 emit_zero_bytes (MonoAotCompile *acfg, int num)
671 mono_img_writer_emit_zero_bytes (acfg->w, num);
674 static inline void
675 emit_byte (MonoAotCompile *acfg, guint8 val)
677 mono_img_writer_emit_byte (acfg->w, val);
680 #if defined(TARGET_WIN32) && defined(TARGET_X86)
682 static G_GNUC_UNUSED void
683 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
685 const char * mangled_symbol_name = name;
686 char * mangled_symbol_name_alloc = NULL;
688 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
689 mangled_symbol_name = mangled_symbol_name_alloc;
691 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
692 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
694 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
696 if (NULL != mangled_symbol_name_alloc) {
697 g_free (mangled_symbol_name_alloc);
701 #else
703 static G_GNUC_UNUSED void
704 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
706 mono_img_writer_emit_global (acfg->w, name, func);
709 #endif
711 static inline gboolean
712 link_shared_library (MonoAotCompile *acfg)
714 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
717 static inline gboolean
718 add_to_global_symbol_table (MonoAotCompile *acfg)
720 #ifdef TARGET_WIN32_MSVC
721 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
722 #else
723 return acfg->aot_opts.no_dlsym;
724 #endif
727 static void
728 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
730 if (add_to_global_symbol_table (acfg))
731 g_ptr_array_add (acfg->globals, g_strdup (name));
733 if (acfg->aot_opts.no_dlsym) {
734 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
735 } else {
736 emit_global_inner (acfg, name, func);
740 static void
741 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
743 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
746 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
747 static void
748 emit_info_symbol (MonoAotCompile *acfg, const char *name)
750 char symbol [MAX_SYMBOL_SIZE];
752 if (acfg->llvm) {
753 emit_label (acfg, name);
754 /* LLVM generated code references this */
755 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
756 emit_label (acfg, symbol);
757 emit_global_inner (acfg, symbol, FALSE);
758 } else {
759 emit_label (acfg, name);
763 static void
764 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
766 if (acfg->llvm) {
767 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
768 return;
771 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
772 #ifdef TARGET_MACH
773 /* On apple, all symbols need to be aligned to avoid warnings from ld */
774 emit_alignment (acfg, 4);
775 #endif
776 mono_img_writer_emit_label (acfg->w, name);
777 mono_img_writer_emit_string (acfg->w, value);
780 static G_GNUC_UNUSED void
781 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
783 do {
784 guint8 b = value & 0x7f;
785 value >>= 7;
786 if (value != 0) /* more bytes to come */
787 b |= 0x80;
788 emit_byte (acfg, b);
789 } while (value);
792 static G_GNUC_UNUSED void
793 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
795 gboolean more = 1;
796 gboolean negative = (value < 0);
797 guint32 size = 64;
798 guint8 byte;
800 while (more) {
801 byte = value & 0x7f;
802 value >>= 7;
803 /* the following is unnecessary if the
804 * implementation of >>= uses an arithmetic rather
805 * than logical shift for a signed left operand
807 if (negative)
808 /* sign extend */
809 value |= - ((gint64)1 <<(size - 7));
810 /* sign bit of byte is second high order bit (0x40) */
811 if ((value == 0 && !(byte & 0x40)) ||
812 (value == -1 && (byte & 0x40)))
813 more = 0;
814 else
815 byte |= 0x80;
816 emit_byte (acfg, byte);
820 static G_GNUC_UNUSED void
821 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
823 guint8 *p = buf;
825 do {
826 guint8 b = value & 0x7f;
827 value >>= 7;
828 if (value != 0) /* more bytes to come */
829 b |= 0x80;
830 *p ++ = b;
831 } while (value);
833 *endbuf = p;
836 static G_GNUC_UNUSED void
837 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
839 gboolean more = 1;
840 gboolean negative = (value < 0);
841 guint32 size = 32;
842 guint8 byte;
843 guint8 *p = buf;
845 while (more) {
846 byte = value & 0x7f;
847 value >>= 7;
848 /* the following is unnecessary if the
849 * implementation of >>= uses an arithmetic rather
850 * than logical shift for a signed left operand
852 if (negative)
853 /* sign extend */
854 value |= - (1 <<(size - 7));
855 /* sign bit of byte is second high order bit (0x40) */
856 if ((value == 0 && !(byte & 0x40)) ||
857 (value == -1 && (byte & 0x40)))
858 more = 0;
859 else
860 byte |= 0x80;
861 *p ++= byte;
864 *endbuf = p;
867 static void
868 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
870 // FIXME: Big-endian
871 buf [0] = (val >> 0) & 0xff;
872 buf [1] = (val >> 8) & 0xff;
873 buf [2] = (val >> 16) & 0xff;
874 buf [3] = (val >> 24) & 0xff;
876 *endbuf = buf + 4;
879 static void
880 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
882 buf [0] = (val >> 0) & 0xff;
883 buf [1] = (val >> 8) & 0xff;
885 *endbuf = buf + 2;
888 static void
889 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
891 int len = strlen (s);
893 memcpy (buf, s, len + 1);
894 *endbuf = buf + len + 1;
897 static void
898 emit_unset_mode (MonoAotCompile *acfg)
900 mono_img_writer_emit_unset_mode (acfg->w);
903 static G_GNUC_UNUSED void
904 emit_set_thumb_mode (MonoAotCompile *acfg)
906 emit_unset_mode (acfg);
907 fprintf (acfg->fp, ".code 16\n");
910 static G_GNUC_UNUSED void
911 emit_set_arm_mode (MonoAotCompile *acfg)
913 emit_unset_mode (acfg);
914 fprintf (acfg->fp, ".code 32\n");
917 static inline void
918 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
920 #ifdef TARGET_ARM64
921 int i;
923 g_assert (size % 4 == 0);
924 emit_unset_mode (acfg);
925 for (i = 0; i < size; i += 4)
926 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
927 #else
928 emit_bytes (acfg, buf, size);
929 #endif
932 /* ARCHITECTURE SPECIFIC CODE */
934 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
935 #define EMIT_DWARF_INFO 1
936 #endif
938 #ifdef TARGET_WIN32_MSVC
939 #undef EMIT_DWARF_INFO
940 #define EMIT_WIN32_CODEVIEW_INFO
941 #endif
943 #ifdef EMIT_WIN32_UNWIND_INFO
944 static UnwindInfoSectionCacheItem *
945 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
947 static void
948 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
950 static void
951 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
953 static void
954 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
955 #endif
957 static void
958 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
960 #ifdef EMIT_WIN32_UNWIND_INFO
961 free_unwind_info_section_cache_win32 (acfg);
962 #endif
965 static void
966 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
968 #ifdef EMIT_WIN32_UNWIND_INFO
969 gboolean own_unwind_ops = FALSE;
970 if (!unwind_ops) {
971 unwind_ops = mono_unwind_get_cie_program ();
972 own_unwind_ops = TRUE;
975 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
977 if (own_unwind_ops)
978 mono_free_unwind_info (unwind_ops);
979 #endif
982 #if defined(TARGET_ARM)
983 #define AOT_FUNC_ALIGNMENT 4
984 #else
985 #define AOT_FUNC_ALIGNMENT 16
986 #endif
988 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
989 #define PPC_LD_OP "ld"
990 #define PPC_LDX_OP "ldx"
991 #else
992 #define PPC_LD_OP "lwz"
993 #define PPC_LDX_OP "lwzx"
994 #endif
996 #ifdef TARGET_X86_64_WIN32_MSVC
997 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
998 #elif TARGET_AMD64
999 #define AOT_TARGET_STR "AMD64"
1000 #endif
1002 #ifdef TARGET_ARM
1003 #ifdef TARGET_MACH
1004 #define AOT_TARGET_STR "ARM (MACH)"
1005 #else
1006 #define AOT_TARGET_STR "ARM (!MACH)"
1007 #endif
1008 #endif
1010 #ifdef TARGET_ARM64
1011 #ifdef TARGET_MACH
1012 #define AOT_TARGET_STR "ARM64 (MACH)"
1013 #else
1014 #define AOT_TARGET_STR "ARM64 (!MACH)"
1015 #endif
1016 #endif
1018 #ifdef TARGET_POWERPC64
1019 #ifdef __mono_ilp32__
1020 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1021 #else
1022 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1023 #endif
1024 #else
1025 #ifdef TARGET_POWERPC
1026 #ifdef __mono_ilp32__
1027 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1028 #else
1029 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1030 #endif
1031 #endif
1032 #endif
1034 #ifdef TARGET_X86
1035 #ifdef TARGET_WIN32
1036 #define AOT_TARGET_STR "X86 (WIN32)"
1037 #else
1038 #define AOT_TARGET_STR "X86"
1039 #endif
1040 #endif
1042 #ifndef AOT_TARGET_STR
1043 #define AOT_TARGET_STR ""
1044 #endif
1046 static void
1047 arch_init (MonoAotCompile *acfg)
1049 acfg->llc_args = g_string_new ("");
1050 acfg->as_args = g_string_new ("");
1051 acfg->llvm_owriter_supported = TRUE;
1054 * The prefix LLVM likes to put in front of symbol names on darwin.
1055 * The mach-os specs require this for globals, but LLVM puts them in front of all
1056 * symbols. We need to handle this, since we need to refer to LLVM generated
1057 * symbols.
1059 acfg->llvm_label_prefix = "";
1060 acfg->user_symbol_prefix = "";
1062 #if defined(TARGET_X86)
1063 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
1064 #endif
1066 #if defined(TARGET_AMD64)
1067 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
1068 /* NOP */
1069 acfg->align_pad_value = 0x90;
1070 #endif
1072 #ifdef TARGET_ARM
1073 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1074 g_string_append (acfg->llc_args, "-mattr=+v6");
1075 } else {
1076 #if defined(ARM_FPU_VFP_HARD)
1077 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1078 g_string_append (acfg->as_args, " -mfpu=vfp3");
1079 #elif defined(ARM_FPU_VFP)
1080 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1081 g_string_append (acfg->as_args, " -mfpu=vfp3");
1082 #else
1083 g_string_append (acfg->llc_args, " -soft-float");
1084 #endif
1086 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1087 acfg->thumb_mixed = TRUE;
1089 if (acfg->aot_opts.mtriple)
1090 mono_arch_set_target (acfg->aot_opts.mtriple);
1091 #endif
1093 #ifdef TARGET_ARM64
1094 acfg->inst_directive = ".inst";
1095 if (acfg->aot_opts.mtriple)
1096 mono_arch_set_target (acfg->aot_opts.mtriple);
1097 #endif
1099 #ifdef TARGET_MACH
1100 acfg->user_symbol_prefix = "_";
1101 acfg->llvm_label_prefix = "_";
1102 acfg->inst_directive = ".word";
1103 acfg->need_no_dead_strip = TRUE;
1104 acfg->aot_opts.gnu_asm = TRUE;
1105 #endif
1107 #if defined(__linux__) && !defined(TARGET_ARM)
1108 acfg->need_pt_gnu_stack = TRUE;
1109 #endif
1111 #ifdef MONOTOUCH
1112 acfg->global_symbols = TRUE;
1113 #endif
1115 #ifdef TARGET_ANDROID
1116 acfg->llvm_owriter_supported = FALSE;
1117 #endif
1120 #ifdef TARGET_ARM64
1123 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1124 static void
1125 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1127 int offset;
1129 g_assert (acfg->fp);
1130 emit_unset_mode (acfg);
1131 /* r16==ip0 */
1132 offset = (int)(got_slot * sizeof (gpointer));
1133 #ifdef TARGET_MACH
1134 /* clang's integrated assembler */
1135 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1136 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1137 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1138 #else
1139 /* Linux GAS */
1140 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1141 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1142 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1143 #endif
1146 static void
1147 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1149 int reg;
1151 g_assert (acfg->fp);
1152 emit_unset_mode (acfg);
1154 /* ldr rt, target */
1155 reg = arm_get_ldr_lit_reg (code);
1157 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1158 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1159 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1161 *code_size = 12;
1164 static void
1165 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1167 g_assert (acfg->fp);
1168 emit_unset_mode (acfg);
1169 if (ji && ji->relocation == MONO_R_ARM64_B) {
1170 fprintf (acfg->fp, "b %s\n", target);
1171 } else {
1172 if (ji)
1173 g_assert (ji->relocation == MONO_R_ARM64_BL);
1174 fprintf (acfg->fp, "bl %s\n", target);
1176 *call_size = 4;
1179 static void
1180 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1182 int reg;
1184 /* ldr rt, target */
1185 reg = arm_get_ldr_lit_reg (code);
1186 arm64_emit_load_got_slot (acfg, reg, got_slot);
1187 *code_size = 12;
1190 static void
1191 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1193 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1194 fprintf (acfg->fp, "br x16\n");
1195 /* Used by mono_aot_get_plt_info_offset () */
1196 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1199 static void
1200 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1202 guint8 buf [256];
1203 guint8 *code;
1204 int imm;
1206 /* The common code */
1207 code = buf;
1208 imm = pagesize;
1209 /* The trampoline address is in IP0 */
1210 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1211 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1212 /* Compute the data slot address */
1213 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1214 /* Trampoline argument */
1215 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1216 /* Address */
1217 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1218 arm_brx (code, ARMREG_IP0);
1220 /* Emit it */
1221 emit_code_bytes (acfg, buf, code - buf);
1223 *size = code - buf;
1226 static void
1227 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1229 guint8 buf [256];
1230 guint8 *code;
1231 int i, count;
1233 count = (pagesize - common_tramp_size) / specific_tramp_size;
1234 for (i = 0; i < count; ++i) {
1235 code = buf;
1236 arm_adrx (code, ARMREG_IP0, code);
1237 /* Branch to the generic code */
1238 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1239 /* This has to be 2 pointers long */
1240 arm_nop (code);
1241 arm_nop (code);
1242 g_assert (code - buf == specific_tramp_size);
1243 emit_code_bytes (acfg, buf, code - buf);
1247 static void
1248 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1250 guint8 buf [128];
1251 guint8 *code;
1252 guint8 *labels [16];
1253 int common_tramp_size;
1254 int specific_tramp_size = 2 * 8;
1255 int imm, pagesize;
1256 char symbol [128];
1258 if (!acfg->aot_opts.use_trampolines_page)
1259 return;
1261 #ifdef TARGET_MACH
1262 /* Have to match the target pagesize */
1263 pagesize = 16384;
1264 #else
1265 pagesize = mono_pagesize ();
1266 #endif
1267 acfg->tramp_page_size = pagesize;
1269 /* The specific trampolines */
1270 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1271 emit_alignment (acfg, pagesize);
1272 emit_global (acfg, symbol, TRUE);
1273 emit_label (acfg, symbol);
1275 /* The common code */
1276 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1277 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1279 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1281 /* The rgctx trampolines */
1282 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1283 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1284 emit_alignment (acfg, pagesize);
1285 emit_global (acfg, symbol, TRUE);
1286 emit_label (acfg, symbol);
1288 /* The common code */
1289 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1290 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1292 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1294 /* The gsharedvt arg trampolines */
1295 /* These are the same as the specific trampolines */
1296 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1297 emit_alignment (acfg, pagesize);
1298 emit_global (acfg, symbol, TRUE);
1299 emit_label (acfg, symbol);
1301 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1302 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1304 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1306 /* The IMT trampolines */
1307 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1308 emit_alignment (acfg, pagesize);
1309 emit_global (acfg, symbol, TRUE);
1310 emit_label (acfg, symbol);
1312 code = buf;
1313 imm = pagesize;
1314 /* The trampoline address is in IP0 */
1315 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1316 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1317 /* Compute the data slot address */
1318 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1319 /* Trampoline argument */
1320 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1322 /* Same as arch_emit_imt_trampoline () */
1323 labels [0] = code;
1324 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1325 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1326 labels [1] = code;
1327 arm_bcc (code, ARMCOND_EQ, 0);
1329 /* End-of-loop check */
1330 labels [2] = code;
1331 arm_cbzx (code, ARMREG_IP0, 0);
1333 /* Loop footer */
1334 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1335 arm_b (code, labels [0]);
1337 /* Match */
1338 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1339 /* Load vtable slot addr */
1340 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1341 /* Load vtable slot */
1342 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1343 arm_brx (code, ARMREG_IP0);
1345 /* No match */
1346 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1347 /* Load fail addr */
1348 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1349 arm_brx (code, ARMREG_IP0);
1351 emit_code_bytes (acfg, buf, code - buf);
1353 common_tramp_size = code - buf;
1354 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1356 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1359 static void
1360 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1362 /* Load argument from second GOT slot */
1363 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1364 /* Load generic trampoline address from first GOT slot */
1365 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1366 fprintf (acfg->fp, "br x16\n");
1367 *tramp_size = 7 * 4;
1370 static void
1371 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1373 emit_unset_mode (acfg);
1374 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1375 fprintf (acfg->fp, "b %s\n", call_target);
1378 static void
1379 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1381 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1383 /* Load argument from first GOT slot */
1384 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1385 /* Load generic trampoline address from second GOT slot */
1386 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1387 fprintf (acfg->fp, "br x16\n");
1388 *tramp_size = 7 * 4;
1391 static void
1392 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1394 guint8 buf [128];
1395 guint8 *code, *labels [16];
1397 /* Load parameter from GOT slot into ip1 */
1398 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1400 code = buf;
1401 labels [0] = code;
1402 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1403 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1404 labels [1] = code;
1405 arm_bcc (code, ARMCOND_EQ, 0);
1407 /* End-of-loop check */
1408 labels [2] = code;
1409 arm_cbzx (code, ARMREG_IP0, 0);
1411 /* Loop footer */
1412 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1413 arm_b (code, labels [0]);
1415 /* Match */
1416 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1417 /* Load vtable slot addr */
1418 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1419 /* Load vtable slot */
1420 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1421 arm_brx (code, ARMREG_IP0);
1423 /* No match */
1424 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1425 /* Load fail addr */
1426 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1427 arm_brx (code, ARMREG_IP0);
1429 emit_code_bytes (acfg, buf, code - buf);
1431 *tramp_size = code - buf + (3 * 4);
1434 static void
1435 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1437 /* Similar to the specific trampolines, but the address is in the second slot */
1438 /* Load argument from first GOT slot */
1439 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1440 /* Load generic trampoline address from second GOT slot */
1441 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1442 fprintf (acfg->fp, "br x16\n");
1443 *tramp_size = 7 * 4;
1447 #endif
1449 #ifdef MONO_ARCH_AOT_SUPPORTED
1451 * arch_emit_direct_call:
1453 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1454 * calling code.
1456 static void
1457 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1459 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1460 /* Need to make sure this is exactly 5 bytes long */
1461 emit_unset_mode (acfg);
1462 fprintf (acfg->fp, "call %s\n", target);
1463 *call_size = 5;
1464 #elif defined(TARGET_ARM)
1465 emit_unset_mode (acfg);
1466 if (thumb)
1467 fprintf (acfg->fp, "blx %s\n", target);
1468 else
1469 fprintf (acfg->fp, "bl %s\n", target);
1470 *call_size = 4;
1471 #elif defined(TARGET_ARM64)
1472 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1473 #elif defined(TARGET_POWERPC)
1474 emit_unset_mode (acfg);
1475 fprintf (acfg->fp, "bl %s\n", target);
1476 *call_size = 4;
1477 #else
1478 g_assert_not_reached ();
1479 #endif
1481 #endif
1484 * PPC32 design:
1485 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1486 * the GOT pointer.
1487 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1488 * in in the 2. slot of every GOT, and require every method to place the GOT
1489 * address in r30, even when it doesn't access the GOT otherwise. This way,
1490 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1494 * PPC64 design:
1495 * PPC64 uses function descriptors which greatly complicate all code, since
1496 * these are used very inconsistently in the runtime. Some functions like
1497 * mono_compile_method () return ftn descriptors, while others like the
1498 * trampoline creation functions do not.
1499 * We assume that all GOT slots contain function descriptors, and create
1500 * descriptors in aot-runtime.c when needed.
1501 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1502 * from function descriptors, we could do the same, but it would require
1503 * rewriting all the ppc/aot code to handle function descriptors properly.
1504 * So instead, we use the same approach as on PPC32.
1505 * This is a horrible mess, but fixing it would probably lead to an even bigger
1506 * one.
1510 * X86 design:
1511 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1514 #ifdef MONO_ARCH_AOT_SUPPORTED
1516 * arch_emit_got_offset:
1518 * The memory pointed to by CODE should hold native code for computing the GOT
1519 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1520 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1522 static void
1523 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1525 #if defined(TARGET_POWERPC64)
1526 emit_unset_mode (acfg);
1528 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1529 * unsupported relocations. So we store the got address into the .Lgot_addr
1530 * symbol which is in the text segment, compute its address, and load it.
1532 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1533 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1534 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1535 fprintf (acfg->fp, "add 30, 30, 0\n");
1536 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1537 acfg->label_generator ++;
1538 *code_size = 16;
1539 #elif defined(TARGET_POWERPC)
1540 emit_unset_mode (acfg);
1541 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1542 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1543 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1544 acfg->label_generator ++;
1545 *code_size = 8;
1546 #else
1547 guint32 offset = mono_arch_get_patch_offset (code);
1548 emit_bytes (acfg, code, offset);
1549 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1551 *code_size = offset + 4;
1552 #endif
1556 * arch_emit_got_access:
1558 * The memory pointed to by CODE should hold native code for loading a GOT
1559 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1560 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1562 static void
1563 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1565 #ifdef TARGET_AMD64
1566 /* mov reg, got+offset(%rip) */
1567 if (acfg->llvm) {
1568 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1569 int dreg;
1570 int rex_r;
1572 /* Decode reg, see amd64_mov_reg_membase () */
1573 rex_r = code [0] & AMD64_REX_R;
1574 g_assert (code [0] == 0x49 + rex_r);
1575 g_assert (code [1] == 0x8b);
1576 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1578 emit_unset_mode (acfg);
1579 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1580 *code_size = 7;
1581 } else {
1582 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1583 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1584 *code_size = mono_arch_get_patch_offset (code) + 4;
1586 #elif defined(TARGET_X86)
1587 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1588 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1589 *code_size = mono_arch_get_patch_offset (code) + 4;
1590 #elif defined(TARGET_ARM)
1591 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1592 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1593 *code_size = mono_arch_get_patch_offset (code) + 4;
1594 #elif defined(TARGET_ARM64)
1595 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1596 arm64_emit_got_access (acfg, code, got_slot, code_size);
1597 #elif defined(TARGET_POWERPC)
1599 guint8 buf [32];
1601 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1602 code = buf;
1603 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1604 g_assert (code - buf == 8);
1605 emit_bytes (acfg, buf, code - buf);
1606 *code_size = code - buf;
1608 #else
1609 g_assert_not_reached ();
1610 #endif
1613 #endif
1615 #ifdef MONO_ARCH_AOT_SUPPORTED
1617 * arch_emit_objc_selector_ref:
1619 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1621 static void
1622 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1624 #if defined(TARGET_ARM)
1625 char symbol1 [MAX_SYMBOL_SIZE];
1626 char symbol2 [MAX_SYMBOL_SIZE];
1627 int lindex = acfg->objc_selector_index_2 ++;
1629 /* Emit ldr.imm/b */
1630 emit_bytes (acfg, code, 8);
1632 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1633 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1635 emit_label (acfg, symbol1);
1636 mono_img_writer_emit_unset_mode (acfg->w);
1637 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1639 *code_size = 12;
1640 #elif defined(TARGET_ARM64)
1641 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1642 #else
1643 g_assert_not_reached ();
1644 #endif
1646 #endif
1649 * arch_emit_plt_entry:
1651 * Emit code for the PLT entry.
1652 * The plt entry should look like this:
1653 * <indirect jump to GOT_SYMBOL + OFFSET>
1654 * <INFO_OFFSET embedded into the instruction stream>
1656 static void
1657 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1659 #if defined(TARGET_X86)
1660 /* jmp *<offset>(%ebx) */
1661 emit_byte (acfg, 0xff);
1662 emit_byte (acfg, 0xa3);
1663 emit_int32 (acfg, offset);
1664 /* Used by mono_aot_get_plt_info_offset */
1665 emit_int32 (acfg, info_offset);
1666 #elif defined(TARGET_AMD64)
1667 emit_unset_mode (acfg);
1668 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1669 /* Used by mono_aot_get_plt_info_offset */
1670 emit_int32 (acfg, info_offset);
1671 acfg->stats.plt_size += 10;
1672 #elif defined(TARGET_ARM)
1673 guint8 buf [256];
1674 guint8 *code;
1676 code = buf;
1677 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1678 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1679 emit_bytes (acfg, buf, code - buf);
1680 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1681 /* Used by mono_aot_get_plt_info_offset */
1682 emit_int32 (acfg, info_offset);
1683 #elif defined(TARGET_ARM64)
1684 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1685 #elif defined(TARGET_POWERPC)
1686 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1687 emit_unset_mode (acfg);
1688 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1689 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1690 fprintf (acfg->fp, "add 11, 11, 30\n");
1691 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1692 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1693 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1694 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1695 #endif
1696 fprintf (acfg->fp, "mtctr 11\n");
1697 fprintf (acfg->fp, "bctr\n");
1698 emit_int32 (acfg, info_offset);
1699 #else
1700 g_assert_not_reached ();
1701 #endif
1705 * arch_emit_llvm_plt_entry:
1707 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1708 * This is only needed on arm to handle thumb interop.
1710 static void
1711 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1713 #if defined(TARGET_ARM)
1714 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1715 /* The caller already transitioned to thumb */
1716 /* The code below should be 12 bytes long */
1717 /* clang has trouble encoding these instructions, so emit the binary */
1718 #if 0
1719 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1720 /* thumb can't encode ld pc, [pc, ip] */
1721 fprintf (acfg->fp, "add ip, pc, ip\n");
1722 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1723 fprintf (acfg->fp, "bx ip\n");
1724 #endif
1725 emit_set_thumb_mode (acfg);
1726 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1727 fprintf (acfg->fp, ".2byte 0x44fc\n");
1728 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1729 fprintf (acfg->fp, ".2byte 0x4760\n");
1730 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1731 emit_int32 (acfg, info_offset);
1732 emit_unset_mode (acfg);
1733 emit_set_arm_mode (acfg);
1734 #else
1735 g_assert_not_reached ();
1736 #endif
1739 /* Save unwind_info in the module and emit the offset to the information at symbol */
1740 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1742 guint32 uw_offset, encoded_len;
1743 guint8 *encoded;
1745 emit_section_change (acfg, RODATA_SECT, 0);
1746 emit_global (acfg, symbol, FALSE);
1747 emit_label (acfg, symbol);
1749 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1750 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1751 g_free (encoded);
1752 emit_int32 (acfg, uw_offset);
1756 * arch_emit_specific_trampoline_pages:
1758 * Emits a page full of trampolines: each trampoline uses its own address to
1759 * lookup both the generic trampoline code and the data argument.
1760 * This page can be remapped in process multiple times so we can get an
1761 * unlimited number of trampolines.
1762 * Specifically this implementation uses the following trick: two memory pages
1763 * are allocated, with the first containing the data and the second containing the trampolines.
1764 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1765 * implementation does all the lifting.
1766 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1767 * on the arm 32 bit system.
1769 static void
1770 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1772 #if defined(TARGET_ARM)
1773 guint8 buf [128];
1774 guint8 *code;
1775 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1776 int i;
1777 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1778 GSList *unwind_ops = NULL;
1779 #define COMMON_TRAMP_SIZE 16
1780 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1781 int imm8, rot_amount;
1782 char symbol [128];
1784 if (!acfg->aot_opts.use_trampolines_page)
1785 return;
1787 acfg->tramp_page_size = pagesize;
1789 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1790 emit_alignment (acfg, pagesize);
1791 emit_global (acfg, symbol, TRUE);
1792 emit_label (acfg, symbol);
1794 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1795 code = buf;
1796 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1797 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1798 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1799 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1800 ARM_NOP (code);
1801 g_assert (code - buf == COMMON_TRAMP_SIZE);
1803 /* Emit it */
1804 emit_bytes (acfg, buf, code - buf);
1806 for (i = 0; i < count; ++i) {
1807 code = buf;
1808 ARM_PUSH (code, 0x5fff);
1809 ARM_BL (code, 0);
1810 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1811 g_assert (code - buf == 8);
1812 emit_bytes (acfg, buf, code - buf);
1815 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1816 * the instruction pointer address, so the generic trampoline at the start of the page
1817 * subtracts 4096 to get to the data page and loads the values
1818 * We again fit the generic trampiline in 16 bytes.
1820 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1821 emit_global (acfg, symbol, TRUE);
1822 emit_label (acfg, symbol);
1823 code = buf;
1824 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1825 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1826 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1827 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1828 ARM_NOP (code);
1829 g_assert (code - buf == COMMON_TRAMP_SIZE);
1831 /* Emit it */
1832 emit_bytes (acfg, buf, code - buf);
1834 for (i = 0; i < count; ++i) {
1835 code = buf;
1836 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1837 ARM_B (code, 0);
1838 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1839 g_assert (code - buf == 8);
1840 emit_bytes (acfg, buf, code - buf);
1844 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1846 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1847 emit_global (acfg, symbol, TRUE);
1848 emit_label (acfg, symbol);
1849 code = buf;
1850 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1851 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1852 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1853 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1854 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1855 g_assert (code - buf == COMMON_TRAMP_SIZE);
1856 /* Emit it */
1857 emit_bytes (acfg, buf, code - buf);
1859 for (i = 0; i < count; ++i) {
1860 code = buf;
1861 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1862 ARM_B (code, 0);
1863 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1864 g_assert (code - buf == 8);
1865 emit_bytes (acfg, buf, code - buf);
1868 /* now the imt trampolines: each specific trampolines puts in the ip register
1869 * the instruction pointer address, so the generic trampoline at the start of the page
1870 * subtracts 4096 to get to the data page and loads the values
1872 #define IMT_TRAMP_SIZE 72
1873 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1874 emit_global (acfg, symbol, TRUE);
1875 emit_label (acfg, symbol);
1876 code = buf;
1877 /* Need at least two free registers, plus a slot for storing the pc */
1878 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1880 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1881 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1882 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1884 /* The IMT method is in v5, r0 has the imt array address */
1886 loop_start = code;
1887 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1888 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1889 imt_found_check = code;
1890 ARM_B_COND (code, ARMCOND_EQ, 0);
1892 /* End-of-loop check */
1893 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1894 loop_end_check = code;
1895 ARM_B_COND (code, ARMCOND_EQ, 0);
1897 /* Loop footer */
1898 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1899 loop_branch_back = code;
1900 ARM_B (code, 0);
1901 arm_patch (loop_branch_back, loop_start);
1903 /* Match */
1904 arm_patch (imt_found_check, code);
1905 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1906 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1907 /* Save it to the third stack slot */
1908 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1909 /* Restore the registers and branch */
1910 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1912 /* No match */
1913 arm_patch (loop_end_check, code);
1914 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1915 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1916 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1917 ARM_NOP (code);
1919 /* Emit it */
1920 g_assert (code - buf == IMT_TRAMP_SIZE);
1921 emit_bytes (acfg, buf, code - buf);
1923 for (i = 0; i < count; ++i) {
1924 code = buf;
1925 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1926 ARM_B (code, 0);
1927 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1928 g_assert (code - buf == 8);
1929 emit_bytes (acfg, buf, code - buf);
1932 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1933 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1934 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1935 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1937 /* Unwind info for specifc trampolines */
1938 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1939 /* We unwind to the original caller, from the stack, since lr is clobbered */
1940 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1941 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1942 save_unwind_info (acfg, symbol, unwind_ops);
1943 mono_free_unwind_info (unwind_ops);
1945 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1946 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1947 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1948 save_unwind_info (acfg, symbol, unwind_ops);
1949 mono_free_unwind_info (unwind_ops);
1951 /* Unwind info for rgctx trampolines */
1952 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1953 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1954 save_unwind_info (acfg, symbol, unwind_ops);
1956 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1957 save_unwind_info (acfg, symbol, unwind_ops);
1958 mono_free_unwind_info (unwind_ops);
1960 /* Unwind info for gsharedvt trampolines */
1961 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1962 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1963 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1964 save_unwind_info (acfg, symbol, unwind_ops);
1965 mono_free_unwind_info (unwind_ops);
1967 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1968 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1969 save_unwind_info (acfg, symbol, unwind_ops);
1970 mono_free_unwind_info (unwind_ops);
1972 /* Unwind info for imt trampolines */
1973 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1974 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1975 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1976 save_unwind_info (acfg, symbol, unwind_ops);
1977 mono_free_unwind_info (unwind_ops);
1979 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1980 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1981 save_unwind_info (acfg, symbol, unwind_ops);
1982 mono_free_unwind_info (unwind_ops);
1983 #elif defined(TARGET_ARM64)
1984 arm64_emit_specific_trampoline_pages (acfg);
1985 #endif
1989 * arch_emit_specific_trampoline:
1991 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1992 * two GOT slots which contain the generic trampoline address and the trampoline
1993 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1995 static void
1996 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1999 * The trampolines created here are variations of the specific
2000 * trampolines created in mono_arch_create_specific_trampoline (). The
2001 * differences are:
2002 * - the generic trampoline address is taken from a got slot.
2003 * - the offset of the got slot where the trampoline argument is stored
2004 * is embedded in the instruction stream, and the generic trampoline
2005 * can load the argument by loading the offset, adding it to the
2006 * address of the trampoline to get the address of the got slot, and
2007 * loading the argument from there.
2008 * - all the trampolines should be of the same length.
2010 #if defined(TARGET_AMD64)
2011 /* This should be exactly 8 bytes long */
2012 *tramp_size = 8;
2013 /* call *<offset>(%rip) */
2014 if (acfg->llvm) {
2015 emit_unset_mode (acfg);
2016 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2017 emit_zero_bytes (acfg, 2);
2018 } else {
2019 emit_byte (acfg, '\x41');
2020 emit_byte (acfg, '\xff');
2021 emit_byte (acfg, '\x15');
2022 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2023 emit_zero_bytes (acfg, 1);
2025 #elif defined(TARGET_ARM)
2026 guint8 buf [128];
2027 guint8 *code;
2029 /* This should be exactly 20 bytes long */
2030 *tramp_size = 20;
2031 code = buf;
2032 ARM_PUSH (code, 0x5fff);
2033 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2034 /* Load the value from the GOT */
2035 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2036 /* Branch to it */
2037 ARM_BLX_REG (code, ARMREG_R1);
2039 g_assert (code - buf == 16);
2041 /* Emit it */
2042 emit_bytes (acfg, buf, code - buf);
2044 * Only one offset is needed, since the second one would be equal to the
2045 * first one.
2047 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
2048 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
2049 #elif defined(TARGET_ARM64)
2050 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2051 #elif defined(TARGET_POWERPC)
2052 guint8 buf [128];
2053 guint8 *code;
2055 *tramp_size = 4;
2056 code = buf;
2059 * PPC has no ip relative addressing, so we need to compute the address
2060 * of the mscorlib got. That is slow and complex, so instead, we store it
2061 * in the second got slot of every aot image. The caller already computed
2062 * the address of its got and placed it into r30.
2064 emit_unset_mode (acfg);
2065 /* Load mscorlib got address */
2066 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2067 /* Load generic trampoline address */
2068 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2069 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2070 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2071 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2072 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2073 #endif
2074 fprintf (acfg->fp, "mtctr 11\n");
2075 /* Load trampoline argument */
2076 /* On ppc, we pass it normally to the generic trampoline */
2077 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2078 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2079 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2080 /* Branch to generic trampoline */
2081 fprintf (acfg->fp, "bctr\n");
2083 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2084 *tramp_size = 10 * 4;
2085 #else
2086 *tramp_size = 9 * 4;
2087 #endif
2088 #elif defined(TARGET_X86)
2089 guint8 buf [128];
2090 guint8 *code;
2092 /* Similar to the PPC code above */
2094 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2096 code = buf;
2097 /* Load mscorlib got address */
2098 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2099 /* Push trampoline argument */
2100 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2101 /* Load generic trampoline address */
2102 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2103 /* Branch to generic trampoline */
2104 x86_jump_reg (code, X86_ECX);
2106 emit_bytes (acfg, buf, code - buf);
2108 *tramp_size = 17;
2109 g_assert (code - buf == *tramp_size);
2110 #else
2111 g_assert_not_reached ();
2112 #endif
2116 * arch_emit_unbox_trampoline:
2118 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2119 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2121 static void
2122 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2124 #if defined(TARGET_AMD64)
2125 guint8 buf [32];
2126 guint8 *code;
2127 int this_reg;
2129 this_reg = mono_arch_get_this_arg_reg (NULL);
2130 code = buf;
2131 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2133 emit_bytes (acfg, buf, code - buf);
2134 /* jump <method> */
2135 if (acfg->llvm) {
2136 emit_unset_mode (acfg);
2137 fprintf (acfg->fp, "jmp %s\n", call_target);
2138 } else {
2139 emit_byte (acfg, '\xe9');
2140 emit_symbol_diff (acfg, call_target, ".", -4);
2142 #elif defined(TARGET_X86)
2143 guint8 buf [32];
2144 guint8 *code;
2145 int this_pos = 4;
2147 code = buf;
2149 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2151 emit_bytes (acfg, buf, code - buf);
2153 /* jump <method> */
2154 emit_byte (acfg, '\xe9');
2155 emit_symbol_diff (acfg, call_target, ".", -4);
2156 #elif defined(TARGET_ARM)
2157 guint8 buf [128];
2158 guint8 *code;
2160 if (acfg->thumb_mixed && cfg->compile_llvm) {
2161 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2162 fprintf (acfg->fp, "b %s\n", call_target);
2163 fprintf (acfg->fp, ".arm\n");
2164 fprintf (acfg->fp, ".align 2\n");
2165 return;
2168 code = buf;
2170 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2172 emit_bytes (acfg, buf, code - buf);
2173 /* jump to method */
2174 if (acfg->thumb_mixed && cfg->compile_llvm)
2175 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2176 else
2177 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2178 #elif defined(TARGET_ARM64)
2179 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2180 #elif defined(TARGET_POWERPC)
2181 int this_pos = 3;
2183 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2184 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2185 #else
2186 g_assert_not_reached ();
2187 #endif
2191 * arch_emit_static_rgctx_trampoline:
2193 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2194 * two GOT slots which contain the rgctx argument, and the method to jump to.
2195 * TRAMP_SIZE is set to the size of the emitted trampoline.
2196 * These kinds of trampolines cannot be enumerated statically, since there could
2197 * be one trampoline per method instantiation, so we emit the same code for all
2198 * trampolines, and parameterize them using two GOT slots.
2200 static void
2201 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2203 #if defined(TARGET_AMD64)
2204 /* This should be exactly 13 bytes long */
2205 *tramp_size = 13;
2207 if (acfg->llvm) {
2208 emit_unset_mode (acfg);
2209 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2210 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2211 } else {
2212 /* mov <OFFSET>(%rip), %r10 */
2213 emit_byte (acfg, '\x4d');
2214 emit_byte (acfg, '\x8b');
2215 emit_byte (acfg, '\x15');
2216 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2218 /* jmp *<offset>(%rip) */
2219 emit_byte (acfg, '\xff');
2220 emit_byte (acfg, '\x25');
2221 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2223 #elif defined(TARGET_ARM)
2224 guint8 buf [128];
2225 guint8 *code;
2227 /* This should be exactly 24 bytes long */
2228 *tramp_size = 24;
2229 code = buf;
2230 /* Load rgctx value */
2231 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2232 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2233 /* Load branch addr + branch */
2234 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2235 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2237 g_assert (code - buf == 16);
2239 /* Emit it */
2240 emit_bytes (acfg, buf, code - buf);
2241 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2242 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2243 #elif defined(TARGET_ARM64)
2244 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2245 #elif defined(TARGET_POWERPC)
2246 guint8 buf [128];
2247 guint8 *code;
2249 *tramp_size = 4;
2250 code = buf;
2253 * PPC has no ip relative addressing, so we need to compute the address
2254 * of the mscorlib got. That is slow and complex, so instead, we store it
2255 * in the second got slot of every aot image. The caller already computed
2256 * the address of its got and placed it into r30.
2258 emit_unset_mode (acfg);
2259 /* Load mscorlib got address */
2260 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2261 /* Load rgctx */
2262 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2263 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2264 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2265 /* Load target address */
2266 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2267 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2268 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2269 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2270 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2271 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2272 #endif
2273 fprintf (acfg->fp, "mtctr 11\n");
2274 /* Branch to the target address */
2275 fprintf (acfg->fp, "bctr\n");
2277 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2278 *tramp_size = 11 * 4;
2279 #else
2280 *tramp_size = 9 * 4;
2281 #endif
2283 #elif defined(TARGET_X86)
2284 guint8 buf [128];
2285 guint8 *code;
2287 /* Similar to the PPC code above */
2289 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2291 code = buf;
2292 /* Load mscorlib got address */
2293 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2294 /* Load arg */
2295 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2296 /* Branch to the target address */
2297 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2299 emit_bytes (acfg, buf, code - buf);
2301 *tramp_size = 15;
2302 g_assert (code - buf == *tramp_size);
2303 #else
2304 g_assert_not_reached ();
2305 #endif
2309 * arch_emit_imt_trampoline:
2311 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2312 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2313 * key is the IMT key, and ptr holds the address of a memory location holding
2314 * the address to branch to if the IMT arg matches the key. The array is
2315 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2316 * fail_tramp.
2317 * TRAMP_SIZE is set to the size of the emitted trampoline.
2319 static void
2320 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2322 #if defined(TARGET_AMD64)
2323 guint8 *buf, *code;
2324 guint8 *labels [16];
2325 guint8 mov_buf[3];
2326 guint8 *mov_buf_ptr = mov_buf;
2328 const int kSizeOfMove = 7;
2330 code = buf = (guint8 *)g_malloc (256);
2332 /* FIXME: Optimize this, i.e. use binary search etc. */
2333 /* Maybe move the body into a separate function (slower, but much smaller) */
2335 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2337 if (acfg->llvm) {
2338 emit_unset_mode (acfg);
2339 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2342 labels [0] = code;
2343 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2344 labels [1] = code;
2345 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2347 /* Check key */
2348 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2349 labels [2] = code;
2350 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2352 /* Loop footer */
2353 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2354 amd64_jump_code (code, labels [0]);
2356 /* Match */
2357 mono_amd64_patch (labels [2], code);
2358 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2359 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2361 /* No match */
2362 mono_amd64_patch (labels [1], code);
2363 /* Load fail tramp */
2364 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2365 /* Check if there is a fail tramp */
2366 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2367 labels [3] = code;
2368 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2369 /* Jump to fail tramp */
2370 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2372 /* Fail */
2373 mono_amd64_patch (labels [3], code);
2374 x86_breakpoint (code);
2376 if (!acfg->llvm) {
2377 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2378 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2379 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2380 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2381 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2382 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2384 emit_bytes (acfg, buf, code - buf);
2386 *tramp_size = code - buf + kSizeOfMove;
2388 g_free (buf);
2390 #elif defined(TARGET_X86)
2391 guint8 *buf, *code;
2392 guint8 *labels [16];
2394 code = buf = g_malloc (256);
2396 /* Allocate a temporary stack slot */
2397 x86_push_reg (code, X86_EAX);
2398 /* Save EAX */
2399 x86_push_reg (code, X86_EAX);
2401 /* Load mscorlib got address */
2402 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2403 /* Load arg */
2404 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2406 labels [0] = code;
2407 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2408 labels [1] = code;
2409 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2411 /* Check key */
2412 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2413 labels [2] = code;
2414 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2416 /* Loop footer */
2417 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2418 x86_jump_code (code, labels [0]);
2420 /* Match */
2421 mono_x86_patch (labels [2], code);
2422 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2423 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2424 /* Save the target address to the temporary stack location */
2425 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2426 /* Restore EAX */
2427 x86_pop_reg (code, X86_EAX);
2428 /* Jump to the target address */
2429 x86_ret (code);
2431 /* No match */
2432 mono_x86_patch (labels [1], code);
2433 /* Load fail tramp */
2434 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2435 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2436 labels [3] = code;
2437 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2438 /* Jump to fail tramp */
2439 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2440 x86_pop_reg (code, X86_EAX);
2441 x86_ret (code);
2443 /* Fail */
2444 mono_x86_patch (labels [3], code);
2445 x86_breakpoint (code);
2447 emit_bytes (acfg, buf, code - buf);
2449 *tramp_size = code - buf;
2451 g_free (buf);
2453 #elif defined(TARGET_ARM)
2454 guint8 buf [128];
2455 guint8 *code, *code2, *labels [16];
2457 code = buf;
2459 /* The IMT method is in v5 */
2461 /* Need at least two free registers, plus a slot for storing the pc */
2462 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2463 labels [0] = code;
2464 /* Load the parameter from the GOT */
2465 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2466 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2468 labels [1] = code;
2469 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2470 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2471 labels [2] = code;
2472 ARM_B_COND (code, ARMCOND_EQ, 0);
2474 /* End-of-loop check */
2475 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2476 labels [3] = code;
2477 ARM_B_COND (code, ARMCOND_EQ, 0);
2479 /* Loop footer */
2480 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2481 labels [4] = code;
2482 ARM_B (code, 0);
2483 arm_patch (labels [4], labels [1]);
2485 /* Match */
2486 arm_patch (labels [2], code);
2487 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2488 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2489 /* Save it to the third stack slot */
2490 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2491 /* Restore the registers and branch */
2492 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2494 /* No match */
2495 arm_patch (labels [3], code);
2496 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2497 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2498 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2500 /* Fixup offset */
2501 code2 = labels [0];
2502 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2504 emit_bytes (acfg, buf, code - buf);
2505 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2507 *tramp_size = code - buf + 4;
2508 #elif defined(TARGET_ARM64)
2509 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2510 #elif defined(TARGET_POWERPC)
2511 guint8 buf [128];
2512 guint8 *code, *labels [16];
2514 code = buf;
2516 /* Load the mscorlib got address */
2517 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2518 /* Load the parameter from the GOT */
2519 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2520 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2522 /* Load and check key */
2523 labels [1] = code;
2524 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2525 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2526 labels [2] = code;
2527 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2529 /* End-of-loop check */
2530 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2531 labels [3] = code;
2532 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2534 /* Loop footer */
2535 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2536 labels [4] = code;
2537 ppc_b (code, 0);
2538 mono_ppc_patch (labels [4], labels [1]);
2540 /* Match */
2541 mono_ppc_patch (labels [2], code);
2542 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2543 /* r12 now contains the value of the vtable slot */
2544 /* this is not a function descriptor on ppc64 */
2545 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2546 ppc_mtctr (code, ppc_r12);
2547 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2549 /* Fail */
2550 mono_ppc_patch (labels [3], code);
2551 /* FIXME: */
2552 ppc_break (code);
2554 *tramp_size = code - buf;
2556 emit_bytes (acfg, buf, code - buf);
2557 #else
2558 g_assert_not_reached ();
2559 #endif
2563 #if defined (TARGET_AMD64)
2565 static void
2566 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2569 g_assert (acfg->fp);
2570 emit_unset_mode (acfg);
2572 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2575 #endif
2579 * arch_emit_gsharedvt_arg_trampoline:
2581 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2582 * two GOT slots which contain the argument, and the code to jump to.
2583 * TRAMP_SIZE is set to the size of the emitted trampoline.
2584 * These kinds of trampolines cannot be enumerated statically, since there could
2585 * be one trampoline per method instantiation, so we emit the same code for all
2586 * trampolines, and parameterize them using two GOT slots.
2588 static void
2589 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2591 #if defined(TARGET_X86)
2592 guint8 buf [128];
2593 guint8 *code;
2595 /* Similar to the PPC code above */
2597 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2599 code = buf;
2600 /* Load mscorlib got address */
2601 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2602 /* Load arg */
2603 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2604 /* Branch to the target address */
2605 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2607 emit_bytes (acfg, buf, code - buf);
2609 *tramp_size = 15;
2610 g_assert (code - buf == *tramp_size);
2611 #elif defined(TARGET_ARM)
2612 guint8 buf [128];
2613 guint8 *code;
2615 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2616 /* Similar to arch_emit_specific_trampoline () */
2617 *tramp_size = 24;
2618 code = buf;
2619 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2620 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2621 /* Load the arg value from the GOT */
2622 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2623 /* Load the addr from the GOT */
2624 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2625 /* Branch to it */
2626 ARM_BX (code, ARMREG_R1);
2628 g_assert (code - buf == 20);
2630 /* Emit it */
2631 emit_bytes (acfg, buf, code - buf);
2632 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2633 #elif defined(TARGET_ARM64)
2634 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2635 #elif defined (TARGET_AMD64)
2637 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2638 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2639 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2640 fprintf (acfg->fp, "jmp *%%r11\n");
2642 *tramp_size = 0x11;
2643 #else
2644 g_assert_not_reached ();
2645 #endif
2648 /* END OF ARCH SPECIFIC CODE */
2650 static guint32
2651 mono_get_field_token (MonoClassField *field)
2653 MonoClass *klass = field->parent;
2654 int i;
2656 int fcount = mono_class_get_field_count (klass);
2657 for (i = 0; i < fcount; ++i) {
2658 if (field == &klass->fields [i])
2659 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2662 g_assert_not_reached ();
2663 return 0;
2666 static inline void
2667 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2669 guint8 *p = buf;
2671 //printf ("ENCODE: %d 0x%x.\n", value, value);
2674 * Same encoding as the one used in the metadata, extended to handle values
2675 * greater than 0x1fffffff.
2677 if ((value >= 0) && (value <= 127))
2678 *p++ = value;
2679 else if ((value >= 0) && (value <= 16383)) {
2680 p [0] = 0x80 | (value >> 8);
2681 p [1] = value & 0xff;
2682 p += 2;
2683 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2684 p [0] = (value >> 24) | 0xc0;
2685 p [1] = (value >> 16) & 0xff;
2686 p [2] = (value >> 8) & 0xff;
2687 p [3] = value & 0xff;
2688 p += 4;
2690 else {
2691 p [0] = 0xff;
2692 p [1] = (value >> 24) & 0xff;
2693 p [2] = (value >> 16) & 0xff;
2694 p [3] = (value >> 8) & 0xff;
2695 p [4] = value & 0xff;
2696 p += 5;
2698 if (endbuf)
2699 *endbuf = p;
2702 static void
2703 stream_init (MonoDynamicStream *sh)
2705 sh->index = 0;
2706 sh->alloc_size = 4096;
2707 sh->data = (char *)g_malloc (4096);
2709 /* So offsets are > 0 */
2710 sh->data [0] = 0;
2711 sh->index ++;
2714 static void
2715 make_room_in_stream (MonoDynamicStream *stream, int size)
2717 if (size <= stream->alloc_size)
2718 return;
2720 while (stream->alloc_size <= size) {
2721 if (stream->alloc_size < 4096)
2722 stream->alloc_size = 4096;
2723 else
2724 stream->alloc_size *= 2;
2727 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2730 static guint32
2731 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2733 guint32 idx;
2735 make_room_in_stream (stream, stream->index + len);
2736 memcpy (stream->data + stream->index, data, len);
2737 idx = stream->index;
2738 stream->index += len;
2739 return idx;
2743 * add_to_blob:
2745 * Add data to the binary blob inside the aot image. Returns the offset inside the
2746 * blob where the data was stored.
2748 static guint32
2749 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2751 g_assert (!acfg->blob_closed);
2753 if (acfg->blob.alloc_size == 0)
2754 stream_init (&acfg->blob);
2756 return add_stream_data (&acfg->blob, (char*)data, data_len);
2759 static guint32
2760 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2762 char buf [4] = {0};
2763 guint32 count;
2765 if (acfg->blob.alloc_size == 0)
2766 stream_init (&acfg->blob);
2768 count = acfg->blob.index % align;
2770 /* we assume the stream data will be aligned */
2771 if (count)
2772 add_stream_data (&acfg->blob, buf, 4 - count);
2774 return add_stream_data (&acfg->blob, (char*)data, data_len);
2777 /* Emit a table of data into the aot image */
2778 static void
2779 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2781 if (acfg->data_outfile) {
2782 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2783 fwrite (data,1, size, acfg->data_outfile);
2784 acfg->datafile_offset += size;
2785 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2786 int align = 8 - size % 8;
2787 acfg->datafile_offset += align;
2788 guint8 align_buf [16];
2789 memset (&align_buf, 0, sizeof (align_buf));
2790 fwrite (align_buf, align, 1, acfg->data_outfile);
2791 } else if (acfg->llvm) {
2792 mono_llvm_emit_aot_data (symbol, data, size);
2793 } else {
2794 emit_section_change (acfg, RODATA_SECT, 0);
2795 emit_alignment (acfg, 8);
2796 emit_label (acfg, symbol);
2797 emit_bytes (acfg, data, size);
2802 * emit_offset_table:
2804 * Emit a table of increasing offsets in a compact form using differential encoding.
2805 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2806 * group size, the more compact the table becomes, but the slower it becomes to compute
2807 * a given entry. Returns the size of the table.
2809 static guint32
2810 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2812 gint32 current_offset;
2813 int i, buf_size, ngroups, index_entry_size;
2814 guint8 *p, *buf;
2815 guint8 *data_p, *data_buf;
2816 guint32 *index_offsets;
2818 ngroups = (noffsets + (group_size - 1)) / group_size;
2820 index_offsets = g_new0 (guint32, ngroups);
2822 buf_size = noffsets * 4;
2823 p = buf = (guint8 *)g_malloc0 (buf_size);
2825 current_offset = 0;
2826 for (i = 0; i < noffsets; ++i) {
2827 //printf ("D: %d -> %d\n", i, offsets [i]);
2828 if ((i % group_size) == 0) {
2829 index_offsets [i / group_size] = p - buf;
2830 /* Emit the full value for these entries */
2831 encode_value (offsets [i], p, &p);
2832 } else {
2833 /* The offsets are allowed to be non-increasing */
2834 //g_assert (offsets [i] >= current_offset);
2835 encode_value (offsets [i] - current_offset, p, &p);
2837 current_offset = offsets [i];
2839 data_buf = buf;
2840 data_p = p;
2842 if (ngroups && index_offsets [ngroups - 1] < 65000)
2843 index_entry_size = 2;
2844 else
2845 index_entry_size = 4;
2847 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2848 p = buf = (guint8 *)g_malloc0 (buf_size);
2850 /* Emit the header */
2851 encode_int (noffsets, p, &p);
2852 encode_int (group_size, p, &p);
2853 encode_int (ngroups, p, &p);
2854 encode_int (index_entry_size, p, &p);
2856 /* Emit the index */
2857 for (i = 0; i < ngroups; ++i) {
2858 if (index_entry_size == 2)
2859 encode_int16 (index_offsets [i], p, &p);
2860 else
2861 encode_int (index_offsets [i], p, &p);
2863 /* Emit the data */
2864 memcpy (p, data_buf, data_p - data_buf);
2865 p += data_p - data_buf;
2867 g_assert (p - buf <= buf_size);
2869 emit_aot_data (acfg, table, symbol, buf, p - buf);
2871 g_free (buf);
2872 g_free (data_buf);
2874 return (int)(p - buf);
2877 static guint32
2878 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2880 guint32 index;
2882 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2883 if (index)
2884 return index - 1;
2885 else {
2886 index = g_hash_table_size (cfg->image_hash);
2887 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2888 g_ptr_array_add (cfg->image_table, image);
2889 return index;
2893 static guint32
2894 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2896 int i;
2897 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2899 /* FIXME: Search referenced images as well */
2900 if (!acfg->typespec_classes) {
2901 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2902 for (i = 0; i < len; i++) {
2903 ERROR_DECL (error);
2904 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2905 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
2906 if (!is_ok (error)) {
2907 mono_error_cleanup (error);
2908 continue;
2910 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2913 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2916 static void
2917 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2919 static void
2920 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2922 static void
2923 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2925 static void
2926 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2928 static void
2929 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2931 guint8 *p = buf;
2934 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2935 * information.
2938 if (mono_class_is_ginst (klass)) {
2939 guint32 token;
2940 g_assert (klass->type_token);
2942 /* Find a typespec for a class if possible */
2943 token = find_typespec_for_class (acfg, klass);
2944 if (token) {
2945 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2946 encode_value (token, p, &p);
2947 } else {
2948 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2949 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2950 static int count = 0;
2951 guint8 *p1 = p;
2953 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2954 encode_klass_ref (acfg, gclass, p, &p);
2955 encode_ginst (acfg, inst, p, &p);
2957 count += p - p1;
2959 } else if (klass->type_token) {
2960 int iindex = get_image_index (acfg, klass->image);
2962 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2963 if (iindex == 0) {
2964 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2965 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2966 } else {
2967 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2968 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2969 encode_value (get_image_index (acfg, klass->image), p, &p);
2971 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2972 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2973 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2975 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2977 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2978 if (par->gshared_constraint) {
2979 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2980 encode_type (acfg, par->gshared_constraint, p, &p);
2981 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
2982 } else {
2983 encode_value (klass->byval_arg.type, p, &p);
2984 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2986 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2988 if (!container->is_anonymous) {
2989 encode_value (container->is_method, p, &p);
2990 if (container->is_method)
2991 encode_method_ref (acfg, container->owner.method, p, &p);
2992 else
2993 encode_klass_ref (acfg, container->owner.klass, p, &p);
2996 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2997 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2998 encode_type (acfg, &klass->byval_arg, p, &p);
2999 } else {
3000 /* Array class */
3001 g_assert (klass->rank > 0);
3002 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3003 encode_value (klass->rank, p, &p);
3004 encode_klass_ref (acfg, klass->element_class, p, &p);
3006 *endbuf = p;
3010 * encode_klass_ref:
3012 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3013 * standard metadata encoding.
3015 static void
3016 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3018 gboolean shared = FALSE;
3021 * The encoding of generic instances is large so emit them only once.
3023 if (mono_class_is_ginst (klass)) {
3024 guint32 token;
3025 g_assert (klass->type_token);
3027 /* Find a typespec for a class if possible */
3028 token = find_typespec_for_class (acfg, klass);
3029 if (!token)
3030 shared = TRUE;
3031 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
3032 shared = TRUE;
3035 if (shared) {
3036 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3037 guint8 *buf2, *p;
3039 if (!offset) {
3040 buf2 = (guint8 *)g_malloc (1024);
3041 p = buf2;
3043 encode_klass_ref_inner (acfg, klass, p, &p);
3044 g_assert (p - buf2 < 1024);
3046 offset = add_to_blob (acfg, buf2, p - buf2);
3047 g_free (buf2);
3049 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3050 } else {
3051 offset --;
3054 p = buf;
3055 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3056 encode_value (offset, p, &p);
3057 *endbuf = p;
3058 return;
3061 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3064 static void
3065 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3067 guint32 token = mono_get_field_token (field);
3068 guint8 *p = buf;
3070 encode_klass_ref (cfg, field->parent, p, &p);
3071 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3072 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3073 *endbuf = p;
3076 static void
3077 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3079 guint8 *p = buf;
3080 int i;
3082 encode_value (inst->type_argc, p, &p);
3083 for (i = 0; i < inst->type_argc; ++i)
3084 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3085 *endbuf = p;
3088 static void
3089 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3091 guint8 *p = buf;
3092 MonoGenericInst *inst;
3094 inst = context->class_inst;
3095 if (inst) {
3096 g_assert (inst->type_argc);
3097 encode_ginst (acfg, inst, p, &p);
3098 } else {
3099 encode_value (0, p, &p);
3101 inst = context->method_inst;
3102 if (inst) {
3103 g_assert (inst->type_argc);
3104 encode_ginst (acfg, inst, p, &p);
3105 } else {
3106 encode_value (0, p, &p);
3108 *endbuf = p;
3111 static void
3112 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3114 guint8 *p = buf;
3116 g_assert (t->num_mods == 0);
3117 /* t->attrs can be ignored */
3118 //g_assert (t->attrs == 0);
3120 if (t->pinned) {
3121 *p = MONO_TYPE_PINNED;
3122 ++p;
3124 if (t->byref) {
3125 *p = MONO_TYPE_BYREF;
3126 ++p;
3129 *p = t->type;
3130 p ++;
3132 switch (t->type) {
3133 case MONO_TYPE_VOID:
3134 case MONO_TYPE_BOOLEAN:
3135 case MONO_TYPE_CHAR:
3136 case MONO_TYPE_I1:
3137 case MONO_TYPE_U1:
3138 case MONO_TYPE_I2:
3139 case MONO_TYPE_U2:
3140 case MONO_TYPE_I4:
3141 case MONO_TYPE_U4:
3142 case MONO_TYPE_I8:
3143 case MONO_TYPE_U8:
3144 case MONO_TYPE_R4:
3145 case MONO_TYPE_R8:
3146 case MONO_TYPE_I:
3147 case MONO_TYPE_U:
3148 case MONO_TYPE_STRING:
3149 case MONO_TYPE_OBJECT:
3150 case MONO_TYPE_TYPEDBYREF:
3151 break;
3152 case MONO_TYPE_VALUETYPE:
3153 case MONO_TYPE_CLASS:
3154 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3155 break;
3156 case MONO_TYPE_SZARRAY:
3157 encode_klass_ref (acfg, t->data.klass, p, &p);
3158 break;
3159 case MONO_TYPE_PTR:
3160 encode_type (acfg, t->data.type, p, &p);
3161 break;
3162 case MONO_TYPE_GENERICINST: {
3163 MonoClass *gclass = t->data.generic_class->container_class;
3164 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3166 encode_klass_ref (acfg, gclass, p, &p);
3167 encode_ginst (acfg, inst, p, &p);
3168 break;
3170 case MONO_TYPE_ARRAY: {
3171 MonoArrayType *array = t->data.array;
3172 int i;
3174 encode_klass_ref (acfg, array->eklass, p, &p);
3175 encode_value (array->rank, p, &p);
3176 encode_value (array->numsizes, p, &p);
3177 for (i = 0; i < array->numsizes; ++i)
3178 encode_value (array->sizes [i], p, &p);
3179 encode_value (array->numlobounds, p, &p);
3180 for (i = 0; i < array->numlobounds; ++i)
3181 encode_value (array->lobounds [i], p, &p);
3182 break;
3184 case MONO_TYPE_VAR:
3185 case MONO_TYPE_MVAR:
3186 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3187 break;
3188 default:
3189 g_assert_not_reached ();
3192 *endbuf = p;
3195 static void
3196 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3198 guint8 *p = buf;
3199 guint32 flags = 0;
3200 int i;
3202 /* Similar to the metadata encoding */
3203 if (sig->generic_param_count)
3204 flags |= 0x10;
3205 if (sig->hasthis)
3206 flags |= 0x20;
3207 if (sig->explicit_this)
3208 flags |= 0x40;
3209 flags |= (sig->call_convention & 0x0F);
3211 *p = flags;
3212 ++p;
3213 if (sig->generic_param_count)
3214 encode_value (sig->generic_param_count, p, &p);
3215 encode_value (sig->param_count, p, &p);
3217 encode_type (acfg, sig->ret, p, &p);
3218 for (i = 0; i < sig->param_count; ++i) {
3219 if (sig->sentinelpos == i) {
3220 *p = MONO_TYPE_SENTINEL;
3221 ++p;
3223 encode_type (acfg, sig->params [i], p, &p);
3226 *endbuf = p;
3229 #define MAX_IMAGE_INDEX 250
3231 static void
3232 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3234 guint32 image_index = get_image_index (acfg, method->klass->image);
3235 guint32 token = method->token;
3236 MonoJumpInfoToken *ji;
3237 guint8 *p = buf;
3240 * The encoding for most methods is as follows:
3241 * - image index encoded as a leb128
3242 * - token index encoded as a leb128
3243 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3244 * types of method encodings.
3247 /* Mark methods which can't use aot trampolines because they need the further
3248 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3250 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3251 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3252 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3254 if (method->wrapper_type) {
3255 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3257 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3259 encode_value (method->wrapper_type, p, &p);
3261 switch (method->wrapper_type) {
3262 case MONO_WRAPPER_REMOTING_INVOKE:
3263 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3264 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3265 MonoMethod *m;
3267 m = mono_marshal_method_from_wrapper (method);
3268 g_assert (m);
3269 encode_method_ref (acfg, m, p, &p);
3270 break;
3272 case MONO_WRAPPER_PROXY_ISINST:
3273 case MONO_WRAPPER_LDFLD:
3274 case MONO_WRAPPER_LDFLDA:
3275 case MONO_WRAPPER_STFLD: {
3276 g_assert (info);
3277 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3278 break;
3280 case MONO_WRAPPER_ALLOC: {
3281 /* The GC name is saved once in MonoAotFileInfo */
3282 g_assert (info->d.alloc.alloc_type != -1);
3283 encode_value (info->d.alloc.alloc_type, p, &p);
3284 break;
3286 case MONO_WRAPPER_WRITE_BARRIER: {
3287 g_assert (info);
3288 break;
3290 case MONO_WRAPPER_STELEMREF: {
3291 g_assert (info);
3292 encode_value (info->subtype, p, &p);
3293 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3294 encode_value (info->d.virtual_stelemref.kind, p, &p);
3295 break;
3297 case MONO_WRAPPER_UNKNOWN: {
3298 g_assert (info);
3299 encode_value (info->subtype, p, &p);
3300 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3301 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3302 encode_klass_ref (acfg, method->klass, p, &p);
3303 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3304 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3305 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3306 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3307 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3308 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3309 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3310 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3311 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3312 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3313 break;
3315 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3316 g_assert (info);
3317 encode_value (info->subtype, p, &p);
3318 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3319 strcpy ((char*)p, method->name);
3320 p += strlen (method->name) + 1;
3321 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3322 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3323 } else {
3324 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3325 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3327 break;
3329 case MONO_WRAPPER_SYNCHRONIZED: {
3330 MonoMethod *m;
3332 m = mono_marshal_method_from_wrapper (method);
3333 g_assert (m);
3334 g_assert (m != method);
3335 encode_method_ref (acfg, m, p, &p);
3336 break;
3338 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3339 g_assert (info);
3340 encode_value (info->subtype, p, &p);
3342 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3343 encode_value (info->d.element_addr.rank, p, &p);
3344 encode_value (info->d.element_addr.elem_size, p, &p);
3345 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3346 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3347 } else {
3348 g_assert_not_reached ();
3350 break;
3352 case MONO_WRAPPER_CASTCLASS: {
3353 g_assert (info);
3354 encode_value (info->subtype, p, &p);
3355 break;
3357 case MONO_WRAPPER_RUNTIME_INVOKE: {
3358 g_assert (info);
3359 encode_value (info->subtype, p, &p);
3360 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3361 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3362 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3363 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3364 break;
3366 case MONO_WRAPPER_DELEGATE_INVOKE:
3367 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3368 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3369 if (method->is_inflated) {
3370 /* These wrappers are identified by their class */
3371 encode_value (1, p, &p);
3372 encode_klass_ref (acfg, method->klass, p, &p);
3373 } else {
3374 MonoMethodSignature *sig = mono_method_signature (method);
3375 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3377 encode_value (0, p, &p);
3378 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3379 encode_value (info ? info->subtype : 0, p, &p);
3380 encode_signature (acfg, sig, p, &p);
3382 break;
3384 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3385 g_assert (info);
3386 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3387 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3388 break;
3390 default:
3391 g_assert_not_reached ();
3393 } else if (mono_method_signature (method)->is_inflated) {
3395 * This is a generic method, find the original token which referenced it and
3396 * encode that.
3397 * Obtain the token from information recorded by the JIT.
3399 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3400 if (ji) {
3401 image_index = get_image_index (acfg, ji->image);
3402 g_assert (image_index < MAX_IMAGE_INDEX);
3403 token = ji->token;
3405 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3406 encode_value (image_index, p, &p);
3407 encode_value (token, p, &p);
3408 } else {
3409 MonoMethod *declaring;
3410 MonoGenericContext *context = mono_method_get_context (method);
3412 g_assert (method->is_inflated);
3413 declaring = ((MonoMethodInflated*)method)->declaring;
3416 * This might be a non-generic method of a generic instance, which
3417 * doesn't have a token since the reference is generated by the JIT
3418 * like Nullable:Box/Unbox, or by generic sharing.
3420 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3421 /* Encode the klass */
3422 encode_klass_ref (acfg, method->klass, p, &p);
3423 /* Encode the method */
3424 image_index = get_image_index (acfg, method->klass->image);
3425 g_assert (image_index < MAX_IMAGE_INDEX);
3426 g_assert (declaring->token);
3427 token = declaring->token;
3428 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3429 encode_value (image_index, p, &p);
3430 encode_value (token, p, &p);
3431 encode_generic_context (acfg, context, p, &p);
3433 } else if (token == 0) {
3434 /* This might be a method of a constructed type like int[,].Set */
3435 /* Obtain the token from information recorded by the JIT */
3436 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3437 if (ji) {
3438 image_index = get_image_index (acfg, ji->image);
3439 g_assert (image_index < MAX_IMAGE_INDEX);
3440 token = ji->token;
3442 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3443 encode_value (image_index, p, &p);
3444 encode_value (token, p, &p);
3445 } else {
3446 /* Array methods */
3447 g_assert (method->klass->rank);
3449 /* Encode directly */
3450 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3451 encode_klass_ref (acfg, method->klass, p, &p);
3452 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3453 encode_value (0, p, &p);
3454 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3455 encode_value (1, p, &p);
3456 else if (!strcmp (method->name, "Get"))
3457 encode_value (2, p, &p);
3458 else if (!strcmp (method->name, "Address"))
3459 encode_value (3, p, &p);
3460 else if (!strcmp (method->name, "Set"))
3461 encode_value (4, p, &p);
3462 else
3463 g_assert_not_reached ();
3465 } else {
3466 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3468 if (image_index >= MONO_AOT_METHODREF_MIN) {
3469 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3470 encode_value (image_index, p, &p);
3471 encode_value (mono_metadata_token_index (token), p, &p);
3472 } else {
3473 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3476 *endbuf = p;
3479 static gint
3480 compare_patches (gconstpointer a, gconstpointer b)
3482 int i, j;
3484 i = (*(MonoJumpInfo**)a)->ip.i;
3485 j = (*(MonoJumpInfo**)b)->ip.i;
3487 if (i < j)
3488 return -1;
3489 else
3490 if (i > j)
3491 return 1;
3492 else
3493 return 0;
3496 static G_GNUC_UNUSED char*
3497 patch_to_string (MonoJumpInfo *patch_info)
3499 GString *str;
3501 str = g_string_new ("");
3503 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3505 switch (patch_info->type) {
3506 case MONO_PATCH_INFO_VTABLE:
3507 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3508 break;
3509 default:
3510 break;
3512 g_string_append_printf (str, ")");
3513 return g_string_free (str, FALSE);
3517 * is_plt_patch:
3519 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3520 * PLT entry.
3522 static inline gboolean
3523 is_plt_patch (MonoJumpInfo *patch_info)
3525 switch (patch_info->type) {
3526 case MONO_PATCH_INFO_METHOD:
3527 case MONO_PATCH_INFO_INTERNAL_METHOD:
3528 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3529 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3530 case MONO_PATCH_INFO_RGCTX_FETCH:
3531 return TRUE;
3532 default:
3533 return FALSE;
3538 * get_plt_symbol:
3540 * Return the symbol identifying the plt entry PLT_OFFSET.
3542 static char*
3543 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3545 #ifdef TARGET_MACH
3547 * The Apple linker reorganizes object files, so it doesn't like branches to local
3548 * labels, since those have no relocations.
3550 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3551 #else
3552 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3553 #endif
3557 * get_plt_entry:
3559 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3561 static MonoPltEntry*
3562 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3564 MonoPltEntry *res;
3565 gboolean synchronized = FALSE;
3566 static int synchronized_symbol_idx;
3568 if (!is_plt_patch (patch_info))
3569 return NULL;
3571 if (!acfg->patch_to_plt_entry [patch_info->type])
3572 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3573 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3575 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3577 * Allocate a separate PLT slot for each such patch, since some plt
3578 * entries will refer to the method itself, and some will refer to the
3579 * wrapper.
3581 res = NULL;
3582 synchronized = TRUE;
3585 if (!res) {
3586 MonoJumpInfo *new_ji;
3588 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3590 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3591 res->plt_offset = acfg->plt_offset;
3592 res->ji = new_ji;
3593 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3594 if (acfg->aot_opts.write_symbols)
3595 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3596 if (synchronized) {
3597 /* Avoid duplicate symbols because we don't cache */
3598 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3599 if (res->debug_sym)
3600 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3601 synchronized_symbol_idx ++;
3603 if (res->debug_sym)
3604 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3605 else
3606 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3608 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3610 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3612 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3613 //mono_print_ji (patch_info); printf ("\n");
3614 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3616 acfg->plt_offset ++;
3619 return res;
3623 * get_got_offset:
3625 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3626 * JI could be found if it exists, otherwise allocates a new one.
3628 static guint32
3629 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3631 guint32 got_offset;
3632 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3634 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3635 if (got_offset)
3636 return got_offset - 1;
3638 if (llvm) {
3639 got_offset = acfg->llvm_got_offset;
3640 acfg->llvm_got_offset ++;
3641 } else {
3642 got_offset = acfg->got_offset;
3643 acfg->got_offset ++;
3646 acfg->stats.got_slots ++;
3647 acfg->stats.got_slot_types [ji->type] ++;
3649 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3650 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3651 g_ptr_array_add (info->got_patches, ji);
3653 return got_offset;
3656 /* Add a method to the list of methods which need to be emitted */
3657 static void
3658 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3660 g_assert (method);
3661 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3662 g_ptr_array_add (acfg->methods, method);
3663 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3664 acfg->nmethods = acfg->methods->len + 1;
3667 if (method->wrapper_type || extra)
3668 g_ptr_array_add (acfg->extra_methods, method);
3671 static gboolean
3672 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3674 /* One instantiation with valuetypes is generated for each async method */
3675 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3676 return TRUE;
3677 else
3678 return FALSE;
3681 static guint32
3682 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3684 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3686 g_assert (index);
3688 return index - 1;
3691 static int
3692 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3694 int index;
3696 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3697 if (index)
3698 return index - 1;
3700 index = acfg->method_index;
3701 add_method_with_index (acfg, method, index, extra);
3703 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3705 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3707 acfg->method_index ++;
3709 return index;
3712 static int
3713 add_method (MonoAotCompile *acfg, MonoMethod *method)
3715 return add_method_full (acfg, method, FALSE, 0);
3718 static void
3719 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
3721 g_assert (acfg->dedup_stats);
3723 char *name = mono_aot_get_mangled_method_name (method);
3724 g_assert (name);
3726 // For stats
3727 char *stats_name = g_strdup (name);
3729 g_assert (acfg->dedup_cache);
3731 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
3732 // This AOTCompile owns this method
3733 // We do this to decide whether to write it to disk
3734 // during a dedup run (first phase, where we skip).
3736 // If never changed, then maybe can avoid a recompile
3737 // of the cache.
3739 // Files not read in during last phase.
3740 acfg->dedup_cache_changed = TRUE;
3742 // owns name
3743 g_hash_table_insert (acfg->dedup_cache, name, method);
3744 } else {
3745 // owns name
3746 g_free (name);
3749 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
3750 count++;
3751 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
3754 static void
3755 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3757 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3758 method = mini_get_shared_method (method);
3759 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3760 /* Use the gsharedvt version */
3761 method = mini_get_shared_method_full (method, TRUE, TRUE);
3763 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
3764 mono_dedup_cache_method (acfg, method);
3766 if (!acfg->dedup_emit_mode)
3767 return;
3770 if (acfg->aot_opts.log_generics)
3771 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3773 add_method_full (acfg, method, TRUE, depth);
3776 static void
3777 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3779 add_extra_method_with_depth (acfg, method, 0);
3782 static void
3783 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3785 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3786 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3787 MonoMethod *wrapper;
3788 char *name;
3790 if (!callinfo->sig)
3791 return;
3793 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3794 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3795 g_free (name);
3797 add_method (acfg, wrapper);
3800 static MonoMethod*
3801 get_runtime_invoke_sig (MonoMethodSignature *sig)
3803 MonoMethodBuilder *mb;
3804 MonoMethod *m;
3806 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3807 m = mono_mb_create_method (mb, sig, 16);
3808 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3809 mono_mb_free (mb);
3810 return invoke;
3813 static MonoMethod*
3814 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3816 return mono_marshal_get_runtime_invoke (method, virtual_);
3819 static gboolean
3820 can_marshal_struct (MonoClass *klass)
3822 MonoClassField *field;
3823 gboolean can_marshal = TRUE;
3824 gpointer iter = NULL;
3825 MonoMarshalType *info;
3826 int i;
3828 if (mono_class_is_auto_layout (klass))
3829 return FALSE;
3831 info = mono_marshal_load_type_info (klass);
3833 /* Only allow a few field types to avoid asserts in the marshalling code */
3834 while ((field = mono_class_get_fields (klass, &iter))) {
3835 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3836 continue;
3838 switch (field->type->type) {
3839 case MONO_TYPE_I4:
3840 case MONO_TYPE_U4:
3841 case MONO_TYPE_I1:
3842 case MONO_TYPE_U1:
3843 case MONO_TYPE_BOOLEAN:
3844 case MONO_TYPE_I2:
3845 case MONO_TYPE_U2:
3846 case MONO_TYPE_CHAR:
3847 case MONO_TYPE_I8:
3848 case MONO_TYPE_U8:
3849 case MONO_TYPE_I:
3850 case MONO_TYPE_U:
3851 case MONO_TYPE_PTR:
3852 case MONO_TYPE_R4:
3853 case MONO_TYPE_R8:
3854 case MONO_TYPE_STRING:
3855 break;
3856 case MONO_TYPE_VALUETYPE:
3857 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3858 can_marshal = FALSE;
3859 break;
3860 case MONO_TYPE_SZARRAY: {
3861 gboolean has_mspec = FALSE;
3863 if (info) {
3864 for (i = 0; i < info->num_fields; ++i) {
3865 if (info->fields [i].field == field && info->fields [i].mspec)
3866 has_mspec = TRUE;
3869 if (!has_mspec)
3870 can_marshal = FALSE;
3871 break;
3873 default:
3874 can_marshal = FALSE;
3875 break;
3879 /* Special cases */
3880 /* Its hard to compute whenever these can be marshalled or not */
3881 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3882 return TRUE;
3884 return can_marshal;
3887 static void
3888 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3890 /* Create a vtype instantiation */
3891 MonoGenericContext shared_context;
3892 MonoType **args;
3893 MonoGenericInst *inst;
3894 MonoGenericContainer *container;
3895 MonoClass **constraints;
3896 int i;
3898 memset (ctx, 0, sizeof (MonoGenericContext));
3900 if (mono_class_is_gtd (method->klass)) {
3901 shared_context = mono_class_get_generic_container (method->klass)->context;
3902 inst = shared_context.class_inst;
3904 args = g_new0 (MonoType*, inst->type_argc);
3905 for (i = 0; i < inst->type_argc; ++i) {
3906 args [i] = &mono_defaults.int_class->byval_arg;
3908 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3910 if (method->is_generic) {
3911 container = mono_method_get_generic_container (method);
3912 shared_context = container->context;
3913 inst = shared_context.method_inst;
3915 args = g_new0 (MonoType*, inst->type_argc);
3916 for (i = 0; i < container->type_argc; ++i) {
3917 MonoGenericParamInfo *info = &container->type_params [i].info;
3918 gboolean ref_only = FALSE;
3920 if (info && info->constraints) {
3921 constraints = info->constraints;
3923 while (*constraints) {
3924 MonoClass *cklass = *constraints;
3925 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3926 /* Inflaring the method with our vtype would not be valid */
3927 ref_only = TRUE;
3928 constraints ++;
3932 if (ref_only)
3933 args [i] = &mono_defaults.object_class->byval_arg;
3934 else
3935 args [i] = &mono_defaults.int_class->byval_arg;
3937 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3941 static void
3942 add_wrappers (MonoAotCompile *acfg)
3944 MonoMethod *method, *m;
3945 int i, j;
3946 MonoMethodSignature *sig, *csig;
3947 guint32 token;
3950 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3951 * so there is only one wrapper of a given type, or inlining their contents into their
3952 * callers.
3954 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3955 ERROR_DECL (error);
3956 MonoMethod *method;
3957 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3958 gboolean skip = FALSE;
3960 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
3961 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
3963 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3964 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3965 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3966 skip = TRUE;
3968 /* Skip methods which can not be handled by get_runtime_invoke () */
3969 sig = mono_method_signature (method);
3970 if (!sig)
3971 continue;
3972 if ((sig->ret->type == MONO_TYPE_PTR) ||
3973 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3974 skip = TRUE;
3975 if (mono_class_is_open_constructed_type (sig->ret))
3976 skip = TRUE;
3978 for (j = 0; j < sig->param_count; j++) {
3979 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3980 skip = TRUE;
3981 if (mono_class_is_open_constructed_type (sig->params [j]))
3982 skip = TRUE;
3985 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3986 if (!mono_class_is_contextbound (method->klass)) {
3987 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3988 gboolean has_nullable = FALSE;
3990 for (j = 0; j < sig->param_count; j++) {
3991 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3992 has_nullable = TRUE;
3995 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3996 /* Supported by the dynamic runtime-invoke wrapper */
3997 skip = TRUE;
3999 if (info)
4000 mono_arch_dyn_call_free (info);
4002 #endif
4004 if (acfg->aot_opts.llvm_only)
4005 /* Supported by the gsharedvt based runtime-invoke wrapper */
4006 skip = TRUE;
4008 if (!skip) {
4009 //printf ("%s\n", mono_method_full_name (method, TRUE));
4010 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4014 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4015 int nallocators;
4017 /* Runtime invoke wrappers */
4019 /* void runtime-invoke () [.cctor] */
4020 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4021 csig->ret = &mono_defaults.void_class->byval_arg;
4022 add_method (acfg, get_runtime_invoke_sig (csig));
4024 /* void runtime-invoke () [Finalize] */
4025 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4026 csig->hasthis = 1;
4027 csig->ret = &mono_defaults.void_class->byval_arg;
4028 add_method (acfg, get_runtime_invoke_sig (csig));
4030 /* void runtime-invoke (string) [exception ctor] */
4031 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4032 csig->hasthis = 1;
4033 csig->ret = &mono_defaults.void_class->byval_arg;
4034 csig->params [0] = &mono_defaults.string_class->byval_arg;
4035 add_method (acfg, get_runtime_invoke_sig (csig));
4037 /* void runtime-invoke (string, string) [exception ctor] */
4038 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4039 csig->hasthis = 1;
4040 csig->ret = &mono_defaults.void_class->byval_arg;
4041 csig->params [0] = &mono_defaults.string_class->byval_arg;
4042 csig->params [1] = &mono_defaults.string_class->byval_arg;
4043 add_method (acfg, get_runtime_invoke_sig (csig));
4045 /* string runtime-invoke () [Exception.ToString ()] */
4046 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4047 csig->hasthis = 1;
4048 csig->ret = &mono_defaults.string_class->byval_arg;
4049 add_method (acfg, get_runtime_invoke_sig (csig));
4051 /* void runtime-invoke (string, Exception) [exception ctor] */
4052 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4053 csig->hasthis = 1;
4054 csig->ret = &mono_defaults.void_class->byval_arg;
4055 csig->params [0] = &mono_defaults.string_class->byval_arg;
4056 csig->params [1] = &mono_defaults.exception_class->byval_arg;
4057 add_method (acfg, get_runtime_invoke_sig (csig));
4059 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4060 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4061 csig->hasthis = 1;
4062 csig->ret = &(mono_class_load_from_name (
4063 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
4064 csig->params [0] = &mono_defaults.string_class->byval_arg;
4065 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
4066 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
4067 add_method (acfg, get_runtime_invoke_sig (csig));
4069 /* runtime-invoke used by finalizers */
4070 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4072 /* This is used by mono_runtime_capture_context () */
4073 method = mono_get_context_capture_method ();
4074 if (method)
4075 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4077 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4078 if (!acfg->aot_opts.llvm_only)
4079 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4080 #endif
4082 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4083 if (acfg->aot_opts.llvm_only) {
4084 int variants;
4086 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4087 for (variants = 0; variants < 4; ++variants) {
4088 for (i = 0; i < 16; ++i) {
4089 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4090 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4092 g_free (sig);
4097 /* stelemref */
4098 add_method (acfg, mono_marshal_get_stelemref ());
4100 /* Managed Allocators */
4101 nallocators = mono_gc_get_managed_allocator_types ();
4102 for (i = 0; i < nallocators; ++i) {
4103 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4104 add_method (acfg, m);
4105 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4106 add_method (acfg, m);
4107 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4108 add_method (acfg, m);
4111 /* write barriers */
4112 if (mono_gc_is_moving ()) {
4113 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4114 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4117 /* Stelemref wrappers */
4119 MonoMethod **wrappers;
4120 int nwrappers;
4122 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4123 for (i = 0; i < nwrappers; ++i)
4124 add_method (acfg, wrappers [i]);
4125 g_free (wrappers);
4128 /* castclass_with_check wrapper */
4129 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4130 /* isinst_with_check wrapper */
4131 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4133 /* JIT icall wrappers */
4134 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4135 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4139 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4140 * we use the original method instead at runtime.
4141 * Since full-aot doesn't support remoting, this is not a problem.
4143 #if 0
4144 /* remoting-invoke wrappers */
4145 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4146 ERROR_DECL (error);
4147 MonoMethodSignature *sig;
4149 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4150 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4151 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4153 sig = mono_method_signature (method);
4155 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4156 m = mono_marshal_get_remoting_invoke_with_check (method);
4158 add_method (acfg, m);
4161 #endif
4163 /* delegate-invoke wrappers */
4164 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4165 ERROR_DECL (error);
4166 MonoClass *klass;
4167 MonoCustomAttrInfo *cattr;
4169 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4170 klass = mono_class_get_checked (acfg->image, token, error);
4172 if (!klass) {
4173 mono_error_cleanup (error);
4174 continue;
4177 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4178 continue;
4180 if (!mono_class_is_gtd (klass)) {
4181 method = mono_get_delegate_invoke (klass);
4183 m = mono_marshal_get_delegate_invoke (method, NULL);
4185 add_method (acfg, m);
4187 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4188 if (method)
4189 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4191 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4192 if (method)
4193 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4195 cattr = mono_custom_attrs_from_class_checked (klass, error);
4196 if (!is_ok (error)) {
4197 mono_error_cleanup (error);
4198 continue;
4201 if (cattr) {
4202 int j;
4204 for (j = 0; j < cattr->num_attrs; ++j)
4205 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4206 break;
4207 if (j < cattr->num_attrs) {
4208 MonoMethod *invoke;
4209 MonoMethod *wrapper;
4210 MonoMethod *del_invoke;
4212 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4213 invoke = mono_get_delegate_invoke (klass);
4214 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4215 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4216 add_method (acfg, wrapper);
4217 add_method (acfg, del_invoke);
4220 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4221 ERROR_DECL (error);
4222 MonoGenericContext ctx;
4223 MonoMethod *inst, *gshared;
4226 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4228 /* Invoke */
4229 method = mono_get_delegate_invoke (klass);
4230 create_gsharedvt_inst (acfg, method, &ctx);
4232 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4233 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4235 m = mono_marshal_get_delegate_invoke (inst, NULL);
4236 g_assert (m->is_inflated);
4238 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4239 add_extra_method (acfg, gshared);
4241 /* begin-invoke */
4242 method = mono_get_delegate_begin_invoke (klass);
4243 if (method) {
4244 create_gsharedvt_inst (acfg, method, &ctx);
4246 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4247 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4249 m = mono_marshal_get_delegate_begin_invoke (inst);
4250 g_assert (m->is_inflated);
4252 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4253 add_extra_method (acfg, gshared);
4256 /* end-invoke */
4257 method = mono_get_delegate_end_invoke (klass);
4258 if (method) {
4259 create_gsharedvt_inst (acfg, method, &ctx);
4261 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4262 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4264 m = mono_marshal_get_delegate_end_invoke (inst);
4265 g_assert (m->is_inflated);
4267 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4268 add_extra_method (acfg, gshared);
4273 /* array access wrappers */
4274 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4275 ERROR_DECL (error);
4276 MonoClass *klass;
4278 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4279 klass = mono_class_get_checked (acfg->image, token, error);
4281 if (!klass) {
4282 mono_error_cleanup (error);
4283 continue;
4286 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4287 MonoMethod *m, *wrapper;
4289 /* Add runtime-invoke wrappers too */
4291 m = mono_class_get_method_from_name (klass, "Get", -1);
4292 g_assert (m);
4293 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4294 add_extra_method (acfg, wrapper);
4295 if (!acfg->aot_opts.llvm_only)
4296 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4298 m = mono_class_get_method_from_name (klass, "Set", -1);
4299 g_assert (m);
4300 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4301 add_extra_method (acfg, wrapper);
4302 if (!acfg->aot_opts.llvm_only)
4303 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4307 /* Synchronized wrappers */
4308 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4309 ERROR_DECL (error);
4310 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4311 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4312 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4314 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4315 if (method->is_generic) {
4316 // FIXME:
4317 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4318 ERROR_DECL (error);
4319 MonoGenericContext ctx;
4320 MonoMethod *inst, *gshared, *m;
4323 * Create a generic wrapper for a generic instance, and AOT that.
4325 create_gsharedvt_inst (acfg, method, &ctx);
4326 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4327 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4328 m = mono_marshal_get_synchronized_wrapper (inst);
4329 g_assert (m->is_inflated);
4330 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4331 add_method (acfg, gshared);
4332 } else {
4333 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4338 /* pinvoke wrappers */
4339 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4340 ERROR_DECL (error);
4341 MonoMethod *method;
4342 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4344 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4345 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4347 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4348 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4349 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4352 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4353 if (acfg->aot_opts.llvm_only) {
4354 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4355 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4360 /* native-to-managed wrappers */
4361 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4362 ERROR_DECL (error);
4363 MonoMethod *method;
4364 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4365 MonoCustomAttrInfo *cattr;
4366 int j;
4368 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4369 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4372 * Only generate native-to-managed wrappers for methods which have an
4373 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4374 * name to avoid defining a new assembly to contain it.
4376 cattr = mono_custom_attrs_from_method_checked (method, error);
4377 if (!is_ok (error)) {
4378 char *name = mono_method_get_full_name (method);
4379 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4380 g_free (name);
4383 if (cattr) {
4384 for (j = 0; j < cattr->num_attrs; ++j)
4385 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4386 break;
4387 if (j < cattr->num_attrs) {
4388 MonoCustomAttrEntry *e = &cattr->attrs [j];
4389 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4390 const char *p = (const char*)e->data;
4391 const char *named;
4392 int slen, num_named, named_type;
4393 char *n;
4394 MonoType *t;
4395 MonoClass *klass;
4396 char *export_name = NULL;
4397 MonoMethod *wrapper;
4399 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4400 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4401 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4402 mono_method_full_name (method, TRUE));
4403 exit (1);
4406 g_assert (sig->param_count == 1);
4407 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4410 * Decode the cattr manually since we can't create objects
4411 * during aot compilation.
4414 /* Skip prolog */
4415 p += 2;
4417 /* From load_cattr_value () in reflection.c */
4418 slen = mono_metadata_decode_value (p, &p);
4419 n = (char *)g_memdup (p, slen + 1);
4420 n [slen] = 0;
4421 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4422 g_assert (t);
4423 mono_error_assert_ok (error);
4424 g_free (n);
4426 klass = mono_class_from_mono_type (t);
4427 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4429 p += slen;
4431 num_named = read16 (p);
4432 p += 2;
4434 g_assert (num_named < 2);
4435 if (num_named == 1) {
4436 int name_len;
4437 char *name;
4439 /* parse ExportSymbol attribute */
4440 named = p;
4441 named_type = *named;
4442 named += 1;
4443 /* data_type = *named; */
4444 named += 1;
4446 name_len = mono_metadata_decode_blob_size (named, &named);
4447 name = (char *)g_malloc (name_len + 1);
4448 memcpy (name, named, name_len);
4449 name [name_len] = 0;
4450 named += name_len;
4452 g_assert (named_type == 0x54);
4453 g_assert (!strcmp (name, "ExportSymbol"));
4455 /* load_cattr_value (), string case */
4456 g_assert (*named != (char)0xff);
4457 slen = mono_metadata_decode_value (named, &named);
4458 export_name = (char *)g_malloc (slen + 1);
4459 memcpy (export_name, named, slen);
4460 export_name [slen] = 0;
4461 named += slen;
4464 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4465 mono_error_assert_ok (error);
4467 add_method (acfg, wrapper);
4468 if (export_name)
4469 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4471 g_free (cattr);
4474 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4475 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4476 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4480 /* StructureToPtr/PtrToStructure wrappers */
4481 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4482 ERROR_DECL (error);
4483 MonoClass *klass;
4485 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4486 klass = mono_class_get_checked (acfg->image, token, error);
4488 if (!klass) {
4489 mono_error_cleanup (error);
4490 continue;
4493 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4494 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4495 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4496 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4501 static gboolean
4502 has_type_vars (MonoClass *klass)
4504 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4505 return TRUE;
4506 if (klass->rank)
4507 return has_type_vars (klass->element_class);
4508 if (mono_class_is_ginst (klass)) {
4509 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4510 if (context->class_inst) {
4511 int i;
4513 for (i = 0; i < context->class_inst->type_argc; ++i)
4514 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4515 return TRUE;
4518 if (mono_class_is_gtd (klass))
4519 return TRUE;
4520 return FALSE;
4523 static gboolean
4524 is_vt_inst (MonoGenericInst *inst)
4526 int i;
4528 for (i = 0; i < inst->type_argc; ++i) {
4529 MonoType *t = inst->type_argv [i];
4530 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4531 return TRUE;
4533 return FALSE;
4536 static gboolean
4537 method_has_type_vars (MonoMethod *method)
4539 if (has_type_vars (method->klass))
4540 return TRUE;
4542 if (method->is_inflated) {
4543 MonoGenericContext *context = mono_method_get_context (method);
4544 if (context->method_inst) {
4545 int i;
4547 for (i = 0; i < context->method_inst->type_argc; ++i)
4548 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4549 return TRUE;
4552 return FALSE;
4555 static
4556 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4558 return opts->mode == MONO_AOT_MODE_FULL || opts->mode == MONO_AOT_MODE_INTERP;
4561 static
4562 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
4564 return opts->mode == MONO_AOT_MODE_INTERP;
4567 static
4568 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4570 return opts->mode == MONO_AOT_MODE_HYBRID;
4573 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4575 static void
4576 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4578 /* This might lead to a huge code blowup so only do it if neccesary */
4579 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4580 return;
4582 add_generic_class_with_depth (acfg, klass, 0, ref);
4585 static gboolean
4586 check_type_depth (MonoType *t, int depth)
4588 int i;
4590 if (depth > 8)
4591 return TRUE;
4593 switch (t->type) {
4594 case MONO_TYPE_GENERICINST: {
4595 MonoGenericClass *gklass = t->data.generic_class;
4596 MonoGenericInst *ginst = gklass->context.class_inst;
4598 if (ginst) {
4599 for (i = 0; i < ginst->type_argc; ++i) {
4600 if (check_type_depth (ginst->type_argv [i], depth + 1))
4601 return TRUE;
4604 break;
4606 default:
4607 break;
4610 return FALSE;
4613 static void
4614 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4617 * add_generic_class:
4619 * Add all methods of a generic class.
4621 static void
4622 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4624 MonoMethod *method;
4625 MonoClassField *field;
4626 gpointer iter;
4627 gboolean use_gsharedvt = FALSE;
4629 if (!acfg->ginst_hash)
4630 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4632 mono_class_init (klass);
4634 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4635 return;
4637 if (has_type_vars (klass))
4638 return;
4640 if (!mono_class_is_ginst (klass) && !klass->rank)
4641 return;
4643 if (mono_class_has_failure (klass))
4644 return;
4646 if (!acfg->ginst_hash)
4647 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4649 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4650 return;
4652 if (check_type_depth (&klass->byval_arg, 0))
4653 return;
4655 if (acfg->aot_opts.log_generics)
4656 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4658 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4661 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4662 * Enable this only for some classes since gsharedvt might not support all methods.
4664 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4665 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4666 use_gsharedvt = TRUE;
4668 iter = NULL;
4669 while ((method = mono_class_get_methods (klass, &iter))) {
4670 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4672 * This is partial sharing, and we can't handle it yet
4674 continue;
4677 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4678 /* Already added */
4679 add_types_from_method_header (acfg, method);
4680 continue;
4683 if (method->is_generic)
4684 /* FIXME: */
4685 continue;
4688 * FIXME: Instances which are referenced by these methods are not added,
4689 * for example Array.Resize<int> for List<int>.Add ().
4691 add_extra_method_with_depth (acfg, method, depth + 1);
4694 iter = NULL;
4695 while ((field = mono_class_get_fields (klass, &iter))) {
4696 if (field->type->type == MONO_TYPE_GENERICINST)
4697 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4700 if (klass->delegate) {
4701 method = mono_get_delegate_invoke (klass);
4703 method = mono_marshal_get_delegate_invoke (method, NULL);
4705 if (acfg->aot_opts.log_generics)
4706 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4708 add_method (acfg, method);
4711 /* Add superclasses */
4712 if (klass->parent)
4713 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4716 * For ICollection<T>, add instances of the helper methods
4717 * in Array, since a T[] could be cast to ICollection<T>.
4719 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4720 (!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"))) {
4721 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4722 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
4723 gpointer iter;
4724 char *name_prefix;
4726 if (!strcmp (klass->name, "IEnumerator`1"))
4727 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4728 else
4729 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4731 /* Add the T[]/InternalEnumerator class */
4732 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4733 ERROR_DECL (error);
4734 MonoClass *nclass;
4736 iter = NULL;
4737 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4738 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4739 break;
4741 g_assert (nclass);
4742 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
4743 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4744 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4747 iter = NULL;
4748 while ((method = mono_class_get_methods (array_class, &iter))) {
4749 if (strstr (method->name, name_prefix)) {
4750 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4752 add_extra_method_with_depth (acfg, m, depth);
4756 g_free (name_prefix);
4759 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4760 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4761 ERROR_DECL (error);
4762 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4763 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4764 MonoGenericContext ctx;
4765 MonoType *args [16];
4767 memset (&ctx, 0, sizeof (ctx));
4769 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4771 args [0] = &tclass->byval_arg;
4772 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4774 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
4775 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4777 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4778 MonoClass *gcomparer_inst;
4779 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4780 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
4781 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4783 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4787 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4788 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4789 ERROR_DECL (error);
4790 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4791 MonoClass *iface, *gcomparer, *iface_inst;
4792 MonoGenericContext ctx;
4793 MonoType *args [16];
4795 memset (&ctx, 0, sizeof (ctx));
4797 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4798 g_assert (iface);
4799 args [0] = &tclass->byval_arg;
4800 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4802 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
4803 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4805 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4806 MonoClass *gcomparer_inst;
4807 ERROR_DECL (error);
4809 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4810 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
4811 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4812 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4816 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4817 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4818 MonoClass *enum_comparer;
4819 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4820 MonoGenericContext ctx;
4821 MonoType *args [16];
4823 if (mono_class_is_enum (tclass)) {
4824 MonoClass *enum_comparer_inst;
4825 ERROR_DECL (error);
4827 memset (&ctx, 0, sizeof (ctx));
4828 args [0] = &tclass->byval_arg;
4829 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4831 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4832 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
4833 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4834 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4838 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4839 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4840 MonoClass *comparer;
4841 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4842 MonoGenericContext ctx;
4843 MonoType *args [16];
4845 if (mono_class_is_enum (tclass)) {
4846 MonoClass *comparer_inst;
4847 ERROR_DECL (error);
4849 memset (&ctx, 0, sizeof (ctx));
4850 args [0] = &tclass->byval_arg;
4851 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4853 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4854 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
4855 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4856 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4861 static void
4862 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4864 int i;
4865 MonoGenericContext ctx;
4866 MonoType *args [16];
4868 if (acfg->aot_opts.no_instances)
4869 return;
4871 memset (&ctx, 0, sizeof (ctx));
4873 for (i = 0; i < ninsts; ++i) {
4874 ERROR_DECL (error);
4875 MonoClass *generic_inst;
4876 args [0] = insts [i];
4877 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4878 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
4879 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4880 add_generic_class (acfg, generic_inst, force, "");
4884 static void
4885 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4887 ERROR_DECL (error);
4888 MonoMethodHeader *header;
4889 MonoMethodSignature *sig;
4890 int j, depth;
4892 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4894 sig = mono_method_signature (method);
4896 if (sig) {
4897 for (j = 0; j < sig->param_count; ++j)
4898 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4899 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4902 header = mono_method_get_header_checked (method, error);
4904 if (header) {
4905 for (j = 0; j < header->num_locals; ++j)
4906 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4907 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4908 mono_metadata_free_mh (header);
4909 } else {
4910 mono_error_cleanup (error); /* FIXME report the error */
4916 * add_generic_instances:
4918 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4920 static void
4921 add_generic_instances (MonoAotCompile *acfg)
4923 int i;
4924 guint32 token;
4925 MonoMethod *method;
4926 MonoGenericContext *context;
4928 if (acfg->aot_opts.no_instances)
4929 return;
4931 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4932 ERROR_DECL (error);
4933 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4934 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4936 if (!method) {
4937 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
4938 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4939 mono_error_cleanup (error);
4940 continue;
4943 if (method->klass->image != acfg->image)
4944 continue;
4946 context = mono_method_get_context (method);
4948 if (context && ((context->class_inst && context->class_inst->is_open)))
4949 continue;
4952 * For open methods, create an instantiation which can be passed to the JIT.
4953 * FIXME: Handle class_inst as well.
4955 if (context && context->method_inst && context->method_inst->is_open) {
4956 ERROR_DECL (error);
4957 MonoGenericContext shared_context;
4958 MonoGenericInst *inst;
4959 MonoType **type_argv;
4960 int i;
4961 MonoMethod *declaring_method;
4962 gboolean supported = TRUE;
4964 /* Check that the context doesn't contain open constructed types */
4965 if (context->class_inst) {
4966 inst = context->class_inst;
4967 for (i = 0; i < inst->type_argc; ++i) {
4968 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)
4969 continue;
4970 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4971 supported = FALSE;
4974 if (context->method_inst) {
4975 inst = context->method_inst;
4976 for (i = 0; i < inst->type_argc; ++i) {
4977 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)
4978 continue;
4979 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4980 supported = FALSE;
4984 if (!supported)
4985 continue;
4987 memset (&shared_context, 0, sizeof (MonoGenericContext));
4989 inst = context->class_inst;
4990 if (inst) {
4991 type_argv = g_new0 (MonoType*, inst->type_argc);
4992 for (i = 0; i < inst->type_argc; ++i) {
4993 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)
4994 type_argv [i] = &mono_defaults.object_class->byval_arg;
4995 else
4996 type_argv [i] = inst->type_argv [i];
4999 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5000 g_free (type_argv);
5003 inst = context->method_inst;
5004 if (inst) {
5005 type_argv = g_new0 (MonoType*, inst->type_argc);
5006 for (i = 0; i < inst->type_argc; ++i) {
5007 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)
5008 type_argv [i] = &mono_defaults.object_class->byval_arg;
5009 else
5010 type_argv [i] = inst->type_argv [i];
5013 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5014 g_free (type_argv);
5017 if (method->is_generic || mono_class_is_gtd (method->klass))
5018 declaring_method = method;
5019 else
5020 declaring_method = mono_method_get_declaring_generic_method (method);
5022 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5023 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5027 * If the method is fully sharable, it was already added in place of its
5028 * generic definition.
5030 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5031 continue;
5034 * FIXME: Partially shared methods are not shared here, so we end up with
5035 * many identical methods.
5037 add_extra_method (acfg, method);
5040 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5041 ERROR_DECL (error);
5042 MonoClass *klass;
5044 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5046 klass = mono_class_get_checked (acfg->image, token, error);
5047 if (!klass || klass->rank) {
5048 mono_error_cleanup (error);
5049 continue;
5052 add_generic_class (acfg, klass, FALSE, "typespec");
5055 /* Add types of args/locals */
5056 for (i = 0; i < acfg->methods->len; ++i) {
5057 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5058 add_types_from_method_header (acfg, method);
5061 if (acfg->image == mono_defaults.corlib) {
5062 MonoClass *klass;
5063 MonoType *insts [256];
5064 int ninsts = 0;
5066 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
5067 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
5068 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
5069 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
5070 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
5071 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
5072 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
5073 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
5074 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
5075 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
5076 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
5077 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
5079 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5080 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5081 if (klass)
5082 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5083 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5084 if (klass)
5085 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5087 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5089 MonoClass *enum_comparer;
5090 MonoType *insts [16];
5091 int ninsts;
5093 ninsts = 0;
5094 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
5095 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
5096 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
5097 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
5098 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5099 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5101 ninsts = 0;
5102 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
5103 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5104 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5106 ninsts = 0;
5107 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
5108 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5109 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5111 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5112 ninsts = 0;
5113 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
5114 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
5115 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5118 /* Add instances of the array generic interfaces for primitive types */
5119 /* This will add instances of the InternalArray_ helper methods in Array too */
5120 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5121 if (klass)
5122 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5124 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5125 if (klass)
5126 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5128 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5129 if (klass)
5130 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5133 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5134 * used for all instances of GetGenericValueImpl by the AOT runtime.
5137 MonoGenericContext ctx;
5138 MonoType *args [16];
5139 MonoMethod *get_method;
5140 MonoClass *array_klass = mono_class_create_array (mono_defaults.object_class, 1)->parent;
5142 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5144 if (get_method) {
5145 ERROR_DECL (error);
5146 memset (&ctx, 0, sizeof (ctx));
5147 args [0] = &mono_defaults.object_class->byval_arg;
5148 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5149 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5150 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5154 /* Same for CompareExchange<T>/Exchange<T> */
5156 MonoGenericContext ctx;
5157 MonoType *args [16];
5158 MonoMethod *m;
5159 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5160 gpointer iter = NULL;
5162 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5163 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5164 ERROR_DECL (error);
5165 memset (&ctx, 0, sizeof (ctx));
5166 args [0] = &mono_defaults.object_class->byval_arg;
5167 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5168 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5169 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5174 /* Same for Volatile.Read/Write<T> */
5176 MonoGenericContext ctx;
5177 MonoType *args [16];
5178 MonoMethod *m;
5179 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5180 gpointer iter = NULL;
5182 if (volatile_klass) {
5183 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5184 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5185 ERROR_DECL (error);
5186 memset (&ctx, 0, sizeof (ctx));
5187 args [0] = &mono_defaults.object_class->byval_arg;
5188 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5189 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5190 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5196 /* object[] accessor wrappers. */
5197 for (i = 1; i < 4; ++i) {
5198 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5199 MonoMethod *m;
5201 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5202 g_assert (m);
5204 m = mono_marshal_get_array_accessor_wrapper (m);
5205 add_extra_method (acfg, m);
5207 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5208 g_assert (m);
5210 m = mono_marshal_get_array_accessor_wrapper (m);
5211 add_extra_method (acfg, m);
5213 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5214 g_assert (m);
5216 m = mono_marshal_get_array_accessor_wrapper (m);
5217 add_extra_method (acfg, m);
5223 * is_direct_callable:
5225 * Return whenever the method identified by JI is directly callable without
5226 * going through the PLT.
5228 static gboolean
5229 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5231 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5232 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5233 if (callee_cfg) {
5234 gboolean direct_callable = TRUE;
5236 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5237 direct_callable = FALSE;
5239 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5240 direct_callable = FALSE;
5241 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5242 // FIXME: Maybe call the wrapper directly ?
5243 direct_callable = FALSE;
5245 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5246 /* Disable this so all calls go through load_method (), see the
5247 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5248 * mono_debugger_agent_init ().
5250 direct_callable = FALSE;
5253 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5254 /* sgen does some initialization when the allocator method is created */
5255 direct_callable = FALSE;
5256 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5257 /* we don't know at compile time whether sgen is concurrent or not */
5258 direct_callable = FALSE;
5260 if (direct_callable)
5261 return TRUE;
5263 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5264 if (acfg->aot_opts.direct_pinvoke)
5265 return TRUE;
5266 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5267 if (acfg->aot_opts.direct_icalls)
5268 return TRUE;
5269 return FALSE;
5272 return FALSE;
5275 #ifdef MONO_ARCH_AOT_SUPPORTED
5276 static const char *
5277 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5279 MonoImage *image = method->klass->image;
5280 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5281 MonoTableInfo *tables = image->tables;
5282 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5283 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5284 guint32 im_cols [MONO_IMPLMAP_SIZE];
5285 char *import;
5287 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5288 if (import != NULL)
5289 return import;
5291 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5292 return NULL;
5294 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5296 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5297 return NULL;
5299 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5301 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5303 return import;
5305 #else
5306 static const char *
5307 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5309 return NULL;
5311 #endif
5313 static gint
5314 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5316 if (a->native_offset == b->native_offset)
5317 return a->il_offset - b->il_offset;
5318 else
5319 return a->native_offset - b->native_offset;
5323 * compute_line_numbers:
5325 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5326 * entry.
5328 static MonoDebugSourceLocation**
5329 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5331 MonoDebugMethodInfo *minfo;
5332 MonoDebugLineNumberEntry *ln_array;
5333 MonoDebugSourceLocation *loc;
5334 int i, prev_line, prev_il_offset;
5335 int *native_to_il_offset = NULL;
5336 MonoDebugSourceLocation **res;
5337 gboolean first;
5339 minfo = mono_debug_lookup_method (method);
5340 if (!minfo)
5341 return NULL;
5342 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5343 if (debug_info->code_size != code_size)
5344 return NULL;
5346 g_assert (code_size);
5348 /* Compute the native->IL offset mapping */
5350 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5351 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5353 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5355 native_to_il_offset = g_new0 (int, code_size + 1);
5357 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5358 int j;
5359 MonoDebugLineNumberEntry *lne = &ln_array [i];
5361 if (i == 0) {
5362 for (j = 0; j < lne->native_offset; ++j)
5363 native_to_il_offset [j] = -1;
5366 if (i < debug_info->num_line_numbers - 1) {
5367 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5369 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5370 native_to_il_offset [j] = lne->il_offset;
5371 } else {
5372 for (j = lne->native_offset; j < code_size; ++j)
5373 native_to_il_offset [j] = lne->il_offset;
5376 g_free (ln_array);
5378 /* Compute the native->line number mapping */
5379 res = g_new0 (MonoDebugSourceLocation*, code_size);
5380 prev_il_offset = -1;
5381 prev_line = -1;
5382 first = TRUE;
5383 for (i = 0; i < code_size; ++i) {
5384 int il_offset = native_to_il_offset [i];
5386 if (il_offset == -1 || il_offset == prev_il_offset)
5387 continue;
5388 prev_il_offset = il_offset;
5389 loc = mono_debug_method_lookup_location (minfo, il_offset);
5390 if (!(loc && loc->source_file))
5391 continue;
5392 if (loc->row == prev_line) {
5393 mono_debug_free_source_location (loc);
5394 continue;
5396 prev_line = loc->row;
5397 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5398 if (first)
5399 /* This will cover the prolog too */
5400 res [0] = loc;
5401 else
5402 res [i] = loc;
5403 first = FALSE;
5405 return res;
5408 static int
5409 get_file_index (MonoAotCompile *acfg, const char *source_file)
5411 int findex;
5413 // FIXME: Free these
5414 if (!acfg->dwarf_ln_filenames)
5415 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5416 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5417 if (!findex) {
5418 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5419 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5420 emit_unset_mode (acfg);
5421 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5423 return findex;
5426 #ifdef TARGET_ARM64
5427 #define INST_LEN 4
5428 #else
5429 #define INST_LEN 1
5430 #endif
5433 * emit_and_reloc_code:
5435 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5436 * is true, calls are made through the GOT too. This is used for emitting trampolines
5437 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5438 * since trampolines are needed to make PTL work.
5440 static void
5441 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5443 int i, pindex, start_index;
5444 GPtrArray *patches;
5445 MonoJumpInfo *patch_info;
5446 MonoDebugSourceLocation **locs = NULL;
5447 gboolean skip, prologue_end = FALSE;
5448 #ifdef MONO_ARCH_AOT_SUPPORTED
5449 gboolean direct_call, external_call;
5450 guint32 got_slot;
5451 const char *direct_call_target = 0;
5452 const char *direct_pinvoke;
5453 #endif
5455 if (acfg->gas_line_numbers && method && debug_info) {
5456 locs = compute_line_numbers (method, code_len, debug_info);
5457 if (!locs) {
5458 int findex = get_file_index (acfg, "<unknown>");
5459 emit_unset_mode (acfg);
5460 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5464 /* Collect and sort relocations */
5465 patches = g_ptr_array_new ();
5466 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5467 g_ptr_array_add (patches, patch_info);
5468 g_ptr_array_sort (patches, compare_patches);
5470 start_index = 0;
5471 for (i = 0; i < code_len; i += INST_LEN) {
5472 patch_info = NULL;
5473 for (pindex = start_index; pindex < patches->len; ++pindex) {
5474 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5475 if (patch_info->ip.i >= i)
5476 break;
5479 if (locs && locs [i]) {
5480 MonoDebugSourceLocation *loc = locs [i];
5481 int findex;
5482 const char *options;
5484 findex = get_file_index (acfg, loc->source_file);
5485 emit_unset_mode (acfg);
5486 if (!prologue_end)
5487 options = " prologue_end";
5488 else
5489 options = "";
5490 prologue_end = TRUE;
5491 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5492 mono_debug_free_source_location (loc);
5495 skip = FALSE;
5496 #ifdef MONO_ARCH_AOT_SUPPORTED
5497 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5498 start_index = pindex;
5500 switch (patch_info->type) {
5501 case MONO_PATCH_INFO_NONE:
5502 break;
5503 case MONO_PATCH_INFO_GOT_OFFSET: {
5504 int code_size;
5506 arch_emit_got_offset (acfg, code + i, &code_size);
5507 i += code_size - INST_LEN;
5508 skip = TRUE;
5509 patch_info->type = MONO_PATCH_INFO_NONE;
5510 break;
5512 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5513 int code_size, index;
5514 char *selector = (char *)patch_info->data.target;
5516 if (!acfg->objc_selector_to_index)
5517 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5518 if (!acfg->objc_selectors)
5519 acfg->objc_selectors = g_ptr_array_new ();
5520 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5521 if (index)
5522 index --;
5523 else {
5524 index = acfg->objc_selector_index;
5525 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5526 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5527 acfg->objc_selector_index ++;
5530 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5531 i += code_size - INST_LEN;
5532 skip = TRUE;
5533 patch_info->type = MONO_PATCH_INFO_NONE;
5534 break;
5536 default: {
5538 * If this patch is a call, try emitting a direct call instead of
5539 * through a PLT entry. This is possible if the called method is in
5540 * the same assembly and requires no initialization.
5542 direct_call = FALSE;
5543 external_call = FALSE;
5544 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5545 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5546 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5548 // Don't compile inflated methods if we're doing dedup
5549 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
5550 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
5551 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
5552 g_free (name);
5554 direct_call = TRUE;
5555 direct_call_target = callee_cfg->asm_symbol;
5556 patch_info->type = MONO_PATCH_INFO_NONE;
5557 acfg->stats.direct_calls ++;
5561 acfg->stats.all_calls ++;
5562 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5563 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5564 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5565 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5566 else
5567 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5568 if (direct_pinvoke) {
5569 direct_call = TRUE;
5570 g_assert (strlen (direct_pinvoke) < 1000);
5571 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5574 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5575 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5576 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5577 /* Call to a C function implementing a jit icall */
5578 direct_call = TRUE;
5579 external_call = TRUE;
5580 g_assert (strlen (sym) < 1000);
5581 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5583 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5584 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5585 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5586 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5587 /* Call to a jit icall without a wrapper */
5588 direct_call = TRUE;
5589 external_call = TRUE;
5590 g_assert (strlen (sym) < 1000);
5591 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5595 if (direct_call) {
5596 patch_info->type = MONO_PATCH_INFO_NONE;
5597 acfg->stats.direct_calls ++;
5600 if (!got_only && !direct_call) {
5601 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5602 if (plt_entry) {
5603 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5604 direct_call = TRUE;
5605 direct_call_target = plt_entry->symbol;
5607 /* Nullify the patch */
5608 patch_info->type = MONO_PATCH_INFO_NONE;
5609 plt_entry->jit_used = TRUE;
5613 if (direct_call) {
5614 int call_size;
5616 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5617 i += call_size - INST_LEN;
5618 } else {
5619 int code_size;
5621 got_slot = get_got_offset (acfg, FALSE, patch_info);
5623 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5624 i += code_size - INST_LEN;
5626 skip = TRUE;
5630 #endif /* MONO_ARCH_AOT_SUPPORTED */
5632 if (!skip) {
5633 /* Find next patch */
5634 patch_info = NULL;
5635 for (pindex = start_index; pindex < patches->len; ++pindex) {
5636 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5637 if (patch_info->ip.i >= i)
5638 break;
5641 /* Try to emit multiple bytes at once */
5642 if (pindex < patches->len && patch_info->ip.i > i) {
5643 int limit;
5645 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5646 if (locs && locs [limit])
5647 break;
5650 emit_code_bytes (acfg, code + i, limit - i);
5651 i = limit - INST_LEN;
5652 } else {
5653 emit_code_bytes (acfg, code + i, INST_LEN);
5658 g_ptr_array_free (patches, TRUE);
5659 g_free (locs);
5663 * sanitize_symbol:
5665 * Return a modified version of S which only includes characters permissible in symbols.
5667 static char*
5668 sanitize_symbol (MonoAotCompile *acfg, char *s)
5670 gboolean process = FALSE;
5671 int i, len;
5672 GString *gs;
5673 char *res;
5675 if (!s)
5676 return s;
5678 len = strlen (s);
5679 for (i = 0; i < len; ++i)
5680 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5681 process = TRUE;
5682 if (!process)
5683 return s;
5685 gs = g_string_sized_new (len);
5686 for (i = 0; i < len; ++i) {
5687 guint8 c = s [i];
5688 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5689 g_string_append_c (gs, c);
5690 } else if (c > 0x7f) {
5691 /* multi-byte utf8 */
5692 g_string_append_printf (gs, "_0x%x", c);
5693 i ++;
5694 c = s [i];
5695 while (c >> 6 == 0x2) {
5696 g_string_append_printf (gs, "%x", c);
5697 i ++;
5698 c = s [i];
5700 g_string_append_printf (gs, "_");
5701 i --;
5702 } else {
5703 g_string_append_c (gs, '_');
5707 res = mono_mempool_strdup (acfg->mempool, gs->str);
5708 g_string_free (gs, TRUE);
5709 return res;
5712 static char*
5713 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5715 char *name1, *name2, *cached;
5716 int i, j, len, count;
5717 MonoMethod *cached_method;
5719 name1 = mono_method_full_name (method, TRUE);
5721 #ifdef TARGET_MACH
5722 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5723 if ((!prefix || !*prefix) && name1 [0] == 'L')
5724 prefix = "_";
5725 #endif
5727 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5728 char adjustedPrefix [MAX_SYMBOL_SIZE];
5729 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5730 #endif
5732 len = strlen (name1);
5733 name2 = (char *)malloc (strlen (prefix) + len + 16);
5734 memcpy (name2, prefix, strlen (prefix));
5735 j = strlen (prefix);
5736 for (i = 0; i < len; ++i) {
5737 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5738 name2 [j ++] = '_';
5739 } else if (isalnum (name1 [i])) {
5740 name2 [j ++] = name1 [i];
5741 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5742 i += 2;
5743 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5744 name2 [j ++] = '_';
5745 i++;
5746 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5747 } else
5748 name2 [j ++] = '_';
5750 name2 [j] = '\0';
5752 g_free (name1);
5754 count = 0;
5755 while (TRUE) {
5756 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5757 if (!(cached_method && cached_method != method))
5758 break;
5759 sprintf (name2 + j, "_%d", count);
5760 count ++;
5763 cached = g_strdup (name2);
5764 g_hash_table_insert (cache, cached, method);
5766 return name2;
5769 static void
5770 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5772 MonoMethod *method;
5773 int method_index;
5774 guint8 *code;
5775 char *debug_sym = NULL;
5776 char *symbol = NULL;
5777 int func_alignment = AOT_FUNC_ALIGNMENT;
5778 char *export_name;
5780 g_assert (!ignore_cfg (cfg));
5782 method = cfg->orig_method;
5783 code = cfg->native_code;
5785 method_index = get_method_index (acfg, method);
5786 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5788 /* Make the labels local */
5789 emit_section_change (acfg, ".text", 0);
5790 emit_alignment_code (acfg, func_alignment);
5792 if (acfg->global_symbols && acfg->need_no_dead_strip)
5793 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5795 emit_label (acfg, cfg->asm_symbol);
5797 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5799 * Write a C style symbol for every method, this has two uses:
5800 * - it works on platforms where the dwarf debugging info is not
5801 * yet supported.
5802 * - it allows the setting of breakpoints of aot-ed methods.
5805 // Comment out to force dedup to link these symbols and forbid compiling
5806 // in duplicated code. This is an "assert when linking if broken" trick.
5807 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
5808 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
5809 /*else*/
5810 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5812 cfg->asm_debug_symbol = g_strdup (debug_sym);
5814 if (acfg->need_no_dead_strip)
5815 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5817 // Comment out to force dedup to link these symbols and forbid compiling
5818 // in duplicated code. This is an "assert when linking if broken" trick.
5819 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
5820 /*emit_global_inner (acfg, debug_sym, TRUE);*/
5821 /*else*/
5822 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5824 emit_label (acfg, debug_sym);
5827 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5828 if (export_name) {
5829 /* Emit a global symbol for the method */
5830 emit_global_inner (acfg, export_name, TRUE);
5831 emit_label (acfg, export_name);
5834 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
5835 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5837 acfg->stats.code_size += cfg->code_len;
5839 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5841 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 ()));
5843 emit_line (acfg);
5845 if (acfg->aot_opts.write_symbols) {
5846 if (debug_sym)
5847 emit_symbol_size (acfg, debug_sym, ".");
5848 else
5849 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5850 g_free (debug_sym);
5853 emit_label (acfg, symbol);
5855 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
5857 g_free (symbol);
5861 * encode_patch:
5863 * Encode PATCH_INFO into its disk representation.
5865 static void
5866 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5868 guint8 *p = buf;
5870 switch (patch_info->type) {
5871 case MONO_PATCH_INFO_NONE:
5872 break;
5873 case MONO_PATCH_INFO_IMAGE:
5874 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5875 break;
5876 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5877 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5878 case MONO_PATCH_INFO_GC_NURSERY_START:
5879 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5880 break;
5881 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5882 encode_value (patch_info->data.index, p, &p);
5883 break;
5884 case MONO_PATCH_INFO_METHOD_REL:
5885 encode_value ((gint)patch_info->data.offset, p, &p);
5886 break;
5887 case MONO_PATCH_INFO_SWITCH: {
5888 gpointer *table = (gpointer *)patch_info->data.table->table;
5889 int k;
5891 encode_value (patch_info->data.table->table_size, p, &p);
5892 for (k = 0; k < patch_info->data.table->table_size; k++)
5893 encode_value ((int)(gssize)table [k], p, &p);
5894 break;
5896 case MONO_PATCH_INFO_METHODCONST:
5897 case MONO_PATCH_INFO_METHOD:
5898 case MONO_PATCH_INFO_METHOD_JUMP:
5899 case MONO_PATCH_INFO_ICALL_ADDR:
5900 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5901 case MONO_PATCH_INFO_METHOD_RGCTX:
5902 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5903 encode_method_ref (acfg, patch_info->data.method, p, &p);
5904 break;
5905 case MONO_PATCH_INFO_AOT_JIT_INFO:
5906 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5907 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5908 encode_value (patch_info->data.index, p, &p);
5909 break;
5910 case MONO_PATCH_INFO_INTERNAL_METHOD:
5911 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5912 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
5913 guint32 len = strlen (patch_info->data.name);
5915 encode_value (len, p, &p);
5917 memcpy (p, patch_info->data.name, len);
5918 p += len;
5919 *p++ = '\0';
5920 break;
5922 case MONO_PATCH_INFO_LDSTR: {
5923 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5924 guint32 token = patch_info->data.token->token;
5925 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5926 encode_value (image_index, p, &p);
5927 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5928 break;
5930 case MONO_PATCH_INFO_RVA:
5931 case MONO_PATCH_INFO_DECLSEC:
5932 case MONO_PATCH_INFO_LDTOKEN:
5933 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5934 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5935 encode_value (patch_info->data.token->token, p, &p);
5936 encode_value (patch_info->data.token->has_context, p, &p);
5937 if (patch_info->data.token->has_context)
5938 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5939 break;
5940 case MONO_PATCH_INFO_EXC_NAME: {
5941 MonoClass *ex_class;
5943 ex_class =
5944 mono_class_load_from_name (mono_defaults.exception_class->image,
5945 "System", (const char *)patch_info->data.target);
5946 encode_klass_ref (acfg, ex_class, p, &p);
5947 break;
5949 case MONO_PATCH_INFO_R4:
5950 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5951 break;
5952 case MONO_PATCH_INFO_R8:
5953 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5954 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5955 break;
5956 case MONO_PATCH_INFO_VTABLE:
5957 case MONO_PATCH_INFO_CLASS:
5958 case MONO_PATCH_INFO_IID:
5959 case MONO_PATCH_INFO_ADJUSTED_IID:
5960 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5961 break;
5962 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5963 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5964 if (patch_info->data.del_tramp->method) {
5965 encode_value (1, p, &p);
5966 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5967 } else {
5968 encode_value (0, p, &p);
5970 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5971 break;
5972 case MONO_PATCH_INFO_FIELD:
5973 case MONO_PATCH_INFO_SFLDA:
5974 encode_field_info (acfg, patch_info->data.field, p, &p);
5975 break;
5976 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5977 break;
5978 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
5979 break;
5980 case MONO_PATCH_INFO_RGCTX_FETCH:
5981 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5982 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5983 guint32 offset;
5984 guint8 *buf2, *p2;
5987 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5988 * reference the same method, so encode the method only once.
5990 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5991 if (!offset) {
5992 buf2 = (guint8 *)g_malloc (1024);
5993 p2 = buf2;
5995 encode_method_ref (acfg, entry->method, p2, &p2);
5996 g_assert (p2 - buf2 < 1024);
5998 offset = add_to_blob (acfg, buf2, p2 - buf2);
5999 g_free (buf2);
6001 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
6002 } else {
6003 offset --;
6006 encode_value (offset, p, &p);
6007 g_assert ((int)entry->info_type < 256);
6008 g_assert (entry->data->type < 256);
6009 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6010 encode_patch (acfg, entry->data, p, &p);
6011 break;
6013 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6014 case MONO_PATCH_INFO_AOT_MODULE:
6015 break;
6016 case MONO_PATCH_INFO_SIGNATURE:
6017 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6018 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6019 break;
6020 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6021 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6022 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6023 break;
6024 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6025 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6026 int i;
6028 encode_method_ref (acfg, info->method, p, &p);
6029 encode_value (info->num_entries, p, &p);
6030 for (i = 0; i < info->num_entries; ++i) {
6031 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6033 encode_value (template_->info_type, p, &p);
6034 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6035 case MONO_PATCH_INFO_CLASS:
6036 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
6037 break;
6038 case MONO_PATCH_INFO_FIELD:
6039 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6040 break;
6041 default:
6042 g_assert_not_reached ();
6043 break;
6046 break;
6048 case MONO_PATCH_INFO_LDSTR_LIT: {
6049 const char *s = (const char *)patch_info->data.target;
6050 int len = strlen (s);
6052 encode_value (len, p, &p);
6053 memcpy (p, s, len + 1);
6054 p += len + 1;
6055 break;
6057 case MONO_PATCH_INFO_VIRT_METHOD:
6058 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6059 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6060 break;
6061 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6062 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
6063 break;
6064 default:
6065 g_warning ("unable to handle jump info %d", patch_info->type);
6066 g_assert_not_reached ();
6069 *endbuf = p;
6072 static void
6073 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
6075 guint8 *p = buf;
6076 guint32 pindex, offset;
6077 MonoJumpInfo *patch_info;
6079 encode_value (n_patches, p, &p);
6081 for (pindex = 0; pindex < patches->len; ++pindex) {
6082 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6084 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6085 /* Nothing to do */
6086 continue;
6088 offset = get_got_offset (acfg, llvm, patch_info);
6089 encode_value (offset, p, &p);
6092 *endbuf = p;
6095 static void
6096 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6098 MonoMethod *method;
6099 int pindex, buf_size, n_patches;
6100 GPtrArray *patches;
6101 MonoJumpInfo *patch_info;
6102 guint32 method_index;
6103 guint8 *p, *buf;
6104 guint32 first_got_offset;
6106 method = cfg->orig_method;
6108 method_index = get_method_index (acfg, method);
6110 /* Sort relocations */
6111 patches = g_ptr_array_new ();
6112 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6113 g_ptr_array_add (patches, patch_info);
6114 g_ptr_array_sort (patches, compare_patches);
6116 first_got_offset = acfg->cfgs [method_index]->got_offset;
6118 /**********************/
6119 /* Encode method info */
6120 /**********************/
6122 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6123 p = buf = (guint8 *)g_malloc (buf_size);
6125 if (mono_class_get_cctor (method->klass)) {
6126 encode_value (1, p, &p);
6127 encode_klass_ref (acfg, method->klass, p, &p);
6128 } else {
6129 /* Not needed when loading the method */
6130 encode_value (0, p, &p);
6133 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6135 n_patches = 0;
6136 for (pindex = 0; pindex < patches->len; ++pindex) {
6137 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6139 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6140 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6141 patch_info->type = MONO_PATCH_INFO_NONE;
6142 /* Nothing to do */
6143 continue;
6146 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6147 /* Stored in a GOT slot initialized at module load time */
6148 patch_info->type = MONO_PATCH_INFO_NONE;
6149 continue;
6152 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6153 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6154 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6155 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6156 /* Stored in a GOT slot initialized at module load time */
6157 patch_info->type = MONO_PATCH_INFO_NONE;
6158 continue;
6161 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6162 /* Calls are made through the PLT */
6163 patch_info->type = MONO_PATCH_INFO_NONE;
6164 continue;
6167 n_patches ++;
6170 if (n_patches)
6171 g_assert (cfg->has_got_slots);
6173 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6175 g_ptr_array_free (patches, TRUE);
6177 acfg->stats.info_size += p - buf;
6179 g_assert (p - buf < buf_size);
6181 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6182 g_free (buf);
6185 static guint32
6186 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6188 guint32 cache_index;
6189 guint32 offset;
6191 /* Reuse the unwind module to canonize and store unwind info entries */
6192 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6194 /* Use +/- 1 to distinguish 0s from missing entries */
6195 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6196 if (offset)
6197 return offset - 1;
6198 else {
6199 guint8 buf [16];
6200 guint8 *p;
6203 * It would be easier to use assembler symbols, but the caller needs an
6204 * offset now.
6206 offset = acfg->unwind_info_offset;
6207 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6208 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6210 p = buf;
6211 encode_value (encoded_len, p, &p);
6213 acfg->unwind_info_offset += encoded_len + (p - buf);
6214 return offset;
6218 static void
6219 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6221 int i, k, buf_size;
6222 guint32 debug_info_size, seq_points_size;
6223 guint8 *code;
6224 MonoMethodHeader *header;
6225 guint8 *p, *buf, *debug_info;
6226 MonoJitInfo *jinfo = cfg->jit_info;
6227 guint32 flags;
6228 gboolean use_unwind_ops = FALSE;
6229 MonoSeqPointInfo *seq_points;
6231 code = cfg->native_code;
6232 header = cfg->header;
6234 if (!acfg->aot_opts.nodebug) {
6235 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6236 } else {
6237 debug_info = NULL;
6238 debug_info_size = 0;
6241 seq_points = cfg->seq_point_info;
6242 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6244 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6246 p = buf = (guint8 *)g_malloc (buf_size);
6248 use_unwind_ops = cfg->unwind_ops != NULL;
6250 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);
6252 encode_value (flags, p, &p);
6254 if (use_unwind_ops) {
6255 guint32 encoded_len;
6256 guint8 *encoded;
6257 guint32 unwind_desc;
6259 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6261 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6262 encode_value (unwind_desc, p, &p);
6264 g_free (encoded);
6265 } else {
6266 encode_value (jinfo->unwind_info, p, &p);
6269 /*Encode the number of holes before the number of clauses to make decoding easier*/
6270 if (jinfo->has_try_block_holes) {
6271 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6272 encode_value (table->num_holes, p, &p);
6275 if (jinfo->has_arch_eh_info) {
6277 * In AOT mode, the code length is calculated from the address of the previous method,
6278 * which could include alignment padding, so calculating the start of the epilog as
6279 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6281 encode_value (jinfo->code_size, p, &p);
6284 /* Exception table */
6285 if (cfg->compile_llvm) {
6287 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6288 * since the information is only available to llc. Instead, we let llc save the data
6289 * into the LSDA, and read it from there at runtime.
6291 /* The assembly might be CIL stripped so emit the data ourselves */
6292 if (header->num_clauses)
6293 encode_value (header->num_clauses, p, &p);
6295 for (k = 0; k < header->num_clauses; ++k) {
6296 MonoExceptionClause *clause;
6298 clause = &header->clauses [k];
6300 encode_value (clause->flags, p, &p);
6301 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6302 if (clause->data.catch_class) {
6303 guint8 *buf2, *p2;
6304 int len;
6306 buf2 = (guint8 *)g_malloc (4096);
6307 p2 = buf2;
6308 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6309 len = p2 - buf2;
6310 g_assert (len < 4096);
6311 encode_value (len, p, &p);
6312 memcpy (p, buf2, len);
6313 p += p2 - buf2;
6314 g_free (buf2);
6315 } else {
6316 encode_value (0, p, &p);
6320 /* Emit the IL ranges too, since they might not be available at runtime */
6321 encode_value (clause->try_offset, p, &p);
6322 encode_value (clause->try_len, p, &p);
6323 encode_value (clause->handler_offset, p, &p);
6324 encode_value (clause->handler_len, p, &p);
6326 /* Emit a list of nesting clauses */
6327 for (i = 0; i < header->num_clauses; ++i) {
6328 gint32 cindex1 = k;
6329 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6330 gint32 cindex2 = i;
6331 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6333 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6334 encode_value (i, p, &p);
6336 encode_value (-1, p, &p);
6338 } else {
6339 if (jinfo->num_clauses)
6340 encode_value (jinfo->num_clauses, p, &p);
6342 for (k = 0; k < jinfo->num_clauses; ++k) {
6343 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6345 encode_value (ei->flags, p, &p);
6346 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6347 /* Not used for catch clauses */
6348 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6349 encode_value (ei->exvar_offset, p, &p);
6350 #else
6351 encode_value (ei->exvar_offset, p, &p);
6352 #endif
6354 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6355 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6356 else {
6357 if (ei->data.catch_class) {
6358 guint8 *buf2, *p2;
6359 int len;
6361 buf2 = (guint8 *)g_malloc (4096);
6362 p2 = buf2;
6363 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6364 len = p2 - buf2;
6365 g_assert (len < 4096);
6366 encode_value (len, p, &p);
6367 memcpy (p, buf2, len);
6368 p += p2 - buf2;
6369 g_free (buf2);
6370 } else {
6371 encode_value (0, p, &p);
6375 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6376 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6377 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6381 if (jinfo->has_try_block_holes) {
6382 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6383 for (i = 0; i < table->num_holes; ++i) {
6384 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6385 encode_value (hole->clause, p, &p);
6386 encode_value (hole->length, p, &p);
6387 encode_value (hole->offset, p, &p);
6391 if (jinfo->has_arch_eh_info) {
6392 MonoArchEHJitInfo *eh_info;
6394 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6395 encode_value (eh_info->stack_size, p, &p);
6396 encode_value (eh_info->epilog_size, p, &p);
6399 if (jinfo->has_generic_jit_info) {
6400 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6401 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6402 guint8 *buf2, *p2;
6403 int len;
6405 encode_value (gi->nlocs, p, &p);
6406 if (gi->nlocs) {
6407 for (i = 0; i < gi->nlocs; ++i) {
6408 MonoDwarfLocListEntry *entry = &gi->locations [i];
6410 encode_value (entry->is_reg ? 1 : 0, p, &p);
6411 encode_value (entry->reg, p, &p);
6412 if (!entry->is_reg)
6413 encode_value (entry->offset, p, &p);
6414 if (i == 0)
6415 g_assert (entry->from == 0);
6416 else
6417 encode_value (entry->from, p, &p);
6418 encode_value (entry->to, p, &p);
6420 } else {
6421 if (!cfg->compile_llvm) {
6422 encode_value (gi->has_this ? 1 : 0, p, &p);
6423 encode_value (gi->this_reg, p, &p);
6424 encode_value (gi->this_offset, p, &p);
6429 * Need to encode jinfo->method too, since it is not equal to 'method'
6430 * when using generic sharing.
6432 buf2 = (guint8 *)g_malloc (4096);
6433 p2 = buf2;
6434 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6435 len = p2 - buf2;
6436 g_assert (len < 4096);
6437 encode_value (len, p, &p);
6438 memcpy (p, buf2, len);
6439 p += p2 - buf2;
6440 g_free (buf2);
6442 if (gsctx && gsctx->is_gsharedvt) {
6443 encode_value (1, p, &p);
6444 } else {
6445 encode_value (0, p, &p);
6449 if (seq_points_size)
6450 p += mono_seq_point_info_write (seq_points, p);
6452 g_assert (debug_info_size < buf_size);
6454 encode_value (debug_info_size, p, &p);
6455 if (debug_info_size) {
6456 memcpy (p, debug_info, debug_info_size);
6457 p += debug_info_size;
6458 g_free (debug_info);
6461 /* GC Map */
6462 if (cfg->gc_map) {
6463 encode_value (cfg->gc_map_size, p, &p);
6464 /* The GC map requires 4 bytes of alignment */
6465 while ((gsize)p % 4)
6466 p ++;
6467 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6468 p += cfg->gc_map_size;
6471 acfg->stats.ex_info_size += p - buf;
6473 g_assert (p - buf < buf_size);
6475 /* Emit info */
6476 /* The GC Map requires 4 byte alignment */
6477 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6478 g_free (buf);
6481 static guint32
6482 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6484 ERROR_DECL (error);
6485 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
6486 guint8 *p, *buf;
6487 int i, buf_size, res;
6488 gboolean no_special_static, cant_encode;
6489 gpointer iter = NULL;
6491 if (!klass) {
6492 mono_error_cleanup (error);
6494 buf_size = 16;
6496 p = buf = (guint8 *)g_malloc (buf_size);
6498 /* Mark as unusable */
6499 encode_value (-1, p, &p);
6501 res = add_to_blob (acfg, buf, p - buf);
6502 g_free (buf);
6504 return res;
6507 buf_size = 10240 + (klass->vtable_size * 16);
6508 p = buf = (guint8 *)g_malloc (buf_size);
6510 g_assert (klass);
6512 mono_class_init (klass);
6514 mono_class_get_nested_types (klass, &iter);
6515 g_assert (klass->nested_classes_inited);
6517 mono_class_setup_vtable (klass);
6520 * Emit all the information which is required for creating vtables so
6521 * the runtime does not need to create the MonoMethod structures which
6522 * take up a lot of space.
6525 no_special_static = !mono_class_has_special_static_fields (klass);
6527 /* Check whenever we have enough info to encode the vtable */
6528 cant_encode = FALSE;
6529 for (i = 0; i < klass->vtable_size; ++i) {
6530 MonoMethod *cm = klass->vtable [i];
6532 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6533 cant_encode = TRUE;
6536 mono_class_has_finalizer (klass);
6537 if (mono_class_has_failure (klass))
6538 cant_encode = TRUE;
6540 if (mono_class_is_gtd (klass) || cant_encode) {
6541 encode_value (-1, p, &p);
6542 } else {
6543 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6544 encode_value (klass->vtable_size, p, &p);
6545 encode_value ((klass->has_weak_fields << 9) | (mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (has_nested ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6546 if (klass->has_cctor)
6547 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6548 if (klass->has_finalize)
6549 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6551 encode_value (klass->instance_size, p, &p);
6552 encode_value (mono_class_data_size (klass), p, &p);
6553 encode_value (klass->packing_size, p, &p);
6554 encode_value (klass->min_align, p, &p);
6556 for (i = 0; i < klass->vtable_size; ++i) {
6557 MonoMethod *cm = klass->vtable [i];
6559 if (cm)
6560 encode_method_ref (acfg, cm, p, &p);
6561 else
6562 encode_value (0, p, &p);
6566 acfg->stats.class_info_size += p - buf;
6568 g_assert (p - buf < buf_size);
6569 res = add_to_blob (acfg, buf, p - buf);
6570 g_free (buf);
6572 return res;
6575 static char*
6576 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6578 char *debug_sym = NULL;
6579 char *prefix;
6581 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6582 /* Need to add a prefix to create unique symbols */
6583 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6584 } else {
6585 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6586 prefix = mangle_symbol_alloc ("plt_");
6587 #else
6588 prefix = g_strdup ("plt_");
6589 #endif
6592 switch (ji->type) {
6593 case MONO_PATCH_INFO_METHOD:
6594 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6595 break;
6596 case MONO_PATCH_INFO_INTERNAL_METHOD:
6597 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6598 break;
6599 case MONO_PATCH_INFO_RGCTX_FETCH:
6600 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6601 break;
6602 case MONO_PATCH_INFO_ICALL_ADDR:
6603 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6604 char *s = get_debug_sym (ji->data.method, "", cache);
6606 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6607 g_free (s);
6608 break;
6610 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6611 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6612 break;
6613 default:
6614 break;
6617 g_free (prefix);
6619 return sanitize_symbol (acfg, debug_sym);
6623 * Calls made from AOTed code are routed through a table of jumps similar to the
6624 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6625 * control to the AOT runtime through a trampoline.
6627 static void
6628 emit_plt (MonoAotCompile *acfg)
6630 int i;
6632 if (acfg->aot_opts.llvm_only) {
6633 g_assert (acfg->plt_offset == 1);
6634 return;
6637 emit_line (acfg);
6639 emit_section_change (acfg, ".text", 0);
6640 emit_alignment_code (acfg, 16);
6641 emit_info_symbol (acfg, "plt");
6642 emit_label (acfg, acfg->plt_symbol);
6644 for (i = 0; i < acfg->plt_offset; ++i) {
6645 char *debug_sym = NULL;
6646 MonoPltEntry *plt_entry = NULL;
6648 if (i == 0)
6650 * The first plt entry is unused.
6652 continue;
6654 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6656 debug_sym = plt_entry->debug_sym;
6658 if (acfg->thumb_mixed && !plt_entry->jit_used)
6659 /* Emit only a thumb version */
6660 continue;
6662 /* Skip plt entries not actually called */
6663 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6664 continue;
6666 if (acfg->llvm && !acfg->thumb_mixed) {
6667 emit_label (acfg, plt_entry->llvm_symbol);
6668 if (acfg->llvm) {
6669 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6670 #if defined(TARGET_MACH)
6671 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6672 #endif
6676 if (debug_sym) {
6677 if (acfg->need_no_dead_strip) {
6678 emit_unset_mode (acfg);
6679 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6681 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6682 emit_label (acfg, debug_sym);
6685 emit_label (acfg, plt_entry->symbol);
6687 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6689 if (debug_sym)
6690 emit_symbol_size (acfg, debug_sym, ".");
6693 if (acfg->thumb_mixed) {
6694 /* Make sure the ARM symbols don't alias the thumb ones */
6695 emit_zero_bytes (acfg, 16);
6698 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6699 * code.
6701 for (i = 0; i < acfg->plt_offset; ++i) {
6702 char *debug_sym = NULL;
6703 MonoPltEntry *plt_entry = NULL;
6705 if (i == 0)
6706 continue;
6708 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6710 /* Skip plt entries not actually called by LLVM code */
6711 if (!plt_entry->llvm_used)
6712 continue;
6714 if (acfg->aot_opts.write_symbols) {
6715 if (plt_entry->debug_sym)
6716 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6719 if (debug_sym) {
6720 #if defined(TARGET_MACH)
6721 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6722 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6723 #endif
6724 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6725 emit_label (acfg, debug_sym);
6727 fprintf (acfg->fp, "\n.thumb_func\n");
6729 emit_label (acfg, plt_entry->llvm_symbol);
6731 if (acfg->llvm)
6732 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6734 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6736 if (debug_sym) {
6737 emit_symbol_size (acfg, debug_sym, ".");
6738 g_free (debug_sym);
6743 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6745 emit_info_symbol (acfg, "plt_end");
6747 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
6751 * emit_trampoline_full:
6753 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6754 * create_jit_info_for_trampoline ().
6756 static G_GNUC_UNUSED void
6757 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6759 char start_symbol [MAX_SYMBOL_SIZE];
6760 char end_symbol [MAX_SYMBOL_SIZE];
6761 char symbol [MAX_SYMBOL_SIZE];
6762 guint32 buf_size, info_offset;
6763 MonoJumpInfo *patch_info;
6764 guint8 *buf, *p;
6765 GPtrArray *patches;
6766 char *name;
6767 guint8 *code;
6768 guint32 code_size;
6769 MonoJumpInfo *ji;
6770 GSList *unwind_ops;
6772 g_assert (info);
6774 name = info->name;
6775 code = info->code;
6776 code_size = info->code_size;
6777 ji = info->ji;
6778 unwind_ops = info->unwind_ops;
6780 /* Emit code */
6782 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6784 emit_section_change (acfg, ".text", 0);
6785 emit_global (acfg, start_symbol, TRUE);
6786 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6787 emit_label (acfg, start_symbol);
6789 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6790 emit_label (acfg, symbol);
6793 * The code should access everything through the GOT, so we pass
6794 * TRUE here.
6796 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6798 emit_symbol_size (acfg, start_symbol, ".");
6800 if (emit_tinfo) {
6801 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6802 emit_label (acfg, end_symbol);
6805 /* Emit info */
6807 /* Sort relocations */
6808 patches = g_ptr_array_new ();
6809 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6810 if (patch_info->type != MONO_PATCH_INFO_NONE)
6811 g_ptr_array_add (patches, patch_info);
6812 g_ptr_array_sort (patches, compare_patches);
6814 buf_size = patches->len * 128 + 128;
6815 buf = (guint8 *)g_malloc (buf_size);
6816 p = buf;
6818 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6819 g_assert (p - buf < buf_size);
6820 g_ptr_array_free (patches, TRUE);
6822 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6824 info_offset = add_to_blob (acfg, buf, p - buf);
6826 emit_section_change (acfg, RODATA_SECT, 0);
6827 emit_global (acfg, symbol, FALSE);
6828 emit_label (acfg, symbol);
6830 emit_int32 (acfg, info_offset);
6832 if (emit_tinfo) {
6833 guint8 *encoded;
6834 guint32 encoded_len;
6835 guint32 uw_offset;
6838 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6840 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6841 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6842 g_free (encoded);
6844 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6845 emit_int32 (acfg, uw_offset);
6848 /* Emit debug info */
6849 if (unwind_ops) {
6850 char symbol2 [MAX_SYMBOL_SIZE];
6852 sprintf (symbol, "%s", name);
6853 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6855 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
6857 if (acfg->dwarf)
6858 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6861 g_free (buf);
6864 static G_GNUC_UNUSED void
6865 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6867 emit_trampoline_full (acfg, got_offset, info, TRUE);
6870 static void
6871 emit_trampolines (MonoAotCompile *acfg)
6873 char symbol [MAX_SYMBOL_SIZE];
6874 char end_symbol [MAX_SYMBOL_SIZE];
6875 int i, tramp_got_offset;
6876 int ntype;
6877 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6878 int tramp_type;
6879 #endif
6881 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6882 return;
6884 g_assert (acfg->image->assembly);
6886 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6887 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6888 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6889 MonoTrampInfo *info;
6892 * Emit the generic trampolines.
6894 * We could save some code by treating the generic trampolines as a wrapper
6895 * method, but that approach has its own complexities, so we choose the simpler
6896 * method.
6898 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6899 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6900 #ifdef DISABLE_REMOTING
6901 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6902 continue;
6903 #endif
6904 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6905 emit_trampoline (acfg, acfg->got_offset, info);
6906 mono_tramp_info_free (info);
6909 /* Emit the exception related code pieces */
6910 mono_arch_get_restore_context (&info, TRUE);
6911 emit_trampoline (acfg, acfg->got_offset, info);
6912 mono_tramp_info_free (info);
6914 mono_arch_get_call_filter (&info, TRUE);
6915 emit_trampoline (acfg, acfg->got_offset, info);
6916 mono_tramp_info_free (info);
6918 mono_arch_get_throw_exception (&info, TRUE);
6919 emit_trampoline (acfg, acfg->got_offset, info);
6920 mono_tramp_info_free (info);
6922 mono_arch_get_rethrow_exception (&info, TRUE);
6923 emit_trampoline (acfg, acfg->got_offset, info);
6924 mono_tramp_info_free (info);
6926 mono_arch_get_throw_corlib_exception (&info, TRUE);
6927 emit_trampoline (acfg, acfg->got_offset, info);
6928 mono_tramp_info_free (info);
6930 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6931 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6932 emit_trampoline (acfg, acfg->got_offset, info);
6933 mono_tramp_info_free (info);
6935 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6936 emit_trampoline (acfg, acfg->got_offset, info);
6937 mono_tramp_info_free (info);
6938 #endif
6940 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6941 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6942 if (info) {
6943 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6945 /* Create a separate out trampoline for more information in stack traces */
6946 info->name = g_strdup ("gsharedvt_out_trampoline");
6947 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6948 mono_tramp_info_free (info);
6950 #endif
6952 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6954 GSList *l = mono_arch_get_trampolines (TRUE);
6956 while (l) {
6957 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6959 emit_trampoline (acfg, acfg->got_offset, info);
6960 l = l->next;
6963 #endif
6965 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6966 int offset;
6968 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6969 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6970 emit_trampoline (acfg, acfg->got_offset, info);
6971 mono_tramp_info_free (info);
6973 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6974 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6975 emit_trampoline (acfg, acfg->got_offset, info);
6976 mono_tramp_info_free (info);
6979 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6980 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6981 emit_trampoline (acfg, acfg->got_offset, info);
6982 mono_tramp_info_free (info);
6983 #endif
6986 GSList *l;
6988 /* delegate_invoke_impl trampolines */
6989 l = mono_arch_get_delegate_invoke_impls ();
6990 while (l) {
6991 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6993 emit_trampoline (acfg, acfg->got_offset, info);
6994 l = l->next;
6998 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
6999 mono_arch_get_interp_to_native_trampoline (&info);
7000 emit_trampoline (acfg, acfg->got_offset, info);
7003 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7005 /* Emit trampolines which are numerous */
7008 * These include the following:
7009 * - specific trampolines
7010 * - static rgctx invoke trampolines
7011 * - imt trampolines
7012 * These trampolines have the same code, they are parameterized by GOT
7013 * slots.
7014 * They are defined in this file, in the arch_... routines instead of
7015 * in tramp-<ARCH>.c, since it is easier to do it this way.
7019 * When running in aot-only mode, we can't create specific trampolines at
7020 * runtime, so we create a few, and save them in the AOT file.
7021 * Normal trampolines embed their argument as a literal inside the
7022 * trampoline code, we can't do that here, so instead we embed an offset
7023 * which needs to be added to the trampoline address to get the address of
7024 * the GOT slot which contains the argument value.
7025 * The generated trampolines jump to the generic trampolines using another
7026 * GOT slot, which will be setup by the AOT loader to point to the
7027 * generic trampoline code of the given type.
7031 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7032 * each class).
7035 emit_section_change (acfg, ".text", 0);
7037 tramp_got_offset = acfg->got_offset;
7039 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7040 switch (ntype) {
7041 case MONO_AOT_TRAMP_SPECIFIC:
7042 sprintf (symbol, "specific_trampolines");
7043 break;
7044 case MONO_AOT_TRAMP_STATIC_RGCTX:
7045 sprintf (symbol, "static_rgctx_trampolines");
7046 break;
7047 case MONO_AOT_TRAMP_IMT:
7048 sprintf (symbol, "imt_trampolines");
7049 break;
7050 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7051 sprintf (symbol, "gsharedvt_arg_trampolines");
7052 break;
7053 default:
7054 g_assert_not_reached ();
7057 sprintf (end_symbol, "%s_e", symbol);
7059 if (acfg->aot_opts.write_symbols)
7060 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7062 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7063 emit_info_symbol (acfg, symbol);
7065 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7067 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7068 int tramp_size = 0;
7070 switch (ntype) {
7071 case MONO_AOT_TRAMP_SPECIFIC:
7072 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7073 tramp_got_offset += 2;
7074 break;
7075 case MONO_AOT_TRAMP_STATIC_RGCTX:
7076 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7077 tramp_got_offset += 2;
7078 break;
7079 case MONO_AOT_TRAMP_IMT:
7080 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7081 tramp_got_offset += 1;
7082 break;
7083 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7084 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7085 tramp_got_offset += 2;
7086 break;
7087 default:
7088 g_assert_not_reached ();
7090 if (!acfg->trampoline_size [ntype]) {
7091 g_assert (tramp_size);
7092 acfg->trampoline_size [ntype] = tramp_size;
7096 emit_label (acfg, end_symbol);
7097 emit_int32 (acfg, 0);
7100 arch_emit_specific_trampoline_pages (acfg);
7102 /* Reserve some entries at the end of the GOT for our use */
7103 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7106 acfg->got_offset += acfg->num_trampoline_got_entries;
7109 static gboolean
7110 str_begins_with (const char *str1, const char *str2)
7112 int len = strlen (str2);
7113 return strncmp (str1, str2, len) == 0;
7116 void*
7117 mono_aot_readonly_field_override (MonoClassField *field)
7119 ReadOnlyValue *rdv;
7120 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7121 char *p = rdv->name;
7122 int len;
7123 len = strlen (field->parent->name_space);
7124 if (strncmp (p, field->parent->name_space, len))
7125 continue;
7126 p += len;
7127 if (*p++ != '.')
7128 continue;
7129 len = strlen (field->parent->name);
7130 if (strncmp (p, field->parent->name, len))
7131 continue;
7132 p += len;
7133 if (*p++ != '.')
7134 continue;
7135 if (strcmp (p, field->name))
7136 continue;
7137 switch (rdv->type) {
7138 case MONO_TYPE_I1:
7139 return &rdv->value.i1;
7140 case MONO_TYPE_I2:
7141 return &rdv->value.i2;
7142 case MONO_TYPE_I4:
7143 return &rdv->value.i4;
7144 default:
7145 break;
7148 return NULL;
7151 static void
7152 add_readonly_value (MonoAotOptions *opts, const char *val)
7154 ReadOnlyValue *rdv;
7155 const char *fval;
7156 const char *tval;
7157 /* the format of val is:
7158 * namespace.typename.fieldname=type/value
7159 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7161 fval = strrchr (val, '/');
7162 if (!fval) {
7163 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7164 exit (1);
7166 tval = strrchr (val, '=');
7167 if (!tval) {
7168 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7169 exit (1);
7171 rdv = g_new0 (ReadOnlyValue, 1);
7172 rdv->name = (char *)g_malloc0 (tval - val + 1);
7173 memcpy (rdv->name, val, tval - val);
7174 tval++;
7175 fval++;
7176 if (strncmp (tval, "i1", 2) == 0) {
7177 rdv->value.i1 = atoi (fval);
7178 rdv->type = MONO_TYPE_I1;
7179 } else if (strncmp (tval, "i2", 2) == 0) {
7180 rdv->value.i2 = atoi (fval);
7181 rdv->type = MONO_TYPE_I2;
7182 } else if (strncmp (tval, "i4", 2) == 0) {
7183 rdv->value.i4 = atoi (fval);
7184 rdv->type = MONO_TYPE_I4;
7185 } else {
7186 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7187 exit (1);
7189 rdv->next = readonly_values;
7190 readonly_values = rdv;
7193 static gchar *
7194 clean_path (gchar * path)
7196 if (!path)
7197 return NULL;
7199 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7200 return path;
7202 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7203 g_free (path);
7205 return clean;
7208 static gchar *
7209 wrap_path (gchar * path)
7211 int len;
7212 if (!path)
7213 return NULL;
7215 // If the string contains no spaces, just return the original string.
7216 if (strstr (path, " ") == NULL)
7217 return path;
7219 // If the string is already wrapped in quotes, return it.
7220 len = strlen (path);
7221 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7222 return path;
7224 // If the string contains spaces, then wrap it in quotes.
7225 gchar *clean = g_strdup_printf ("\"%s\"", path);
7227 return clean;
7230 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7231 static void
7232 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7234 ptrdiff_t len = end-start;
7235 if (len > 0)
7236 g_ptr_array_add (args, g_strndup (start, len));
7239 static GPtrArray *
7240 mono_aot_split_options (const char *aot_options)
7242 enum MonoAotOptionState {
7243 MONO_AOT_OPTION_STATE_DEFAULT,
7244 MONO_AOT_OPTION_STATE_STRING,
7245 MONO_AOT_OPTION_STATE_ESCAPE,
7248 GPtrArray *args = g_ptr_array_new ();
7249 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7250 gchar const *opt_start = aot_options;
7251 gboolean end_of_string = FALSE;
7252 gchar cur;
7254 g_return_val_if_fail (aot_options != NULL, NULL);
7256 while ((cur = *aot_options) != '\0') {
7257 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7258 goto next;
7260 switch (cur) {
7261 case '"':
7262 // If we find a quote, then if we're in the default case then
7263 // it means we've found the start of a string, if not then it
7264 // means we've found the end of the string and should switch
7265 // back to the default case.
7266 switch (state) {
7267 case MONO_AOT_OPTION_STATE_DEFAULT:
7268 state = MONO_AOT_OPTION_STATE_STRING;
7269 break;
7270 case MONO_AOT_OPTION_STATE_STRING:
7271 state = MONO_AOT_OPTION_STATE_DEFAULT;
7272 break;
7273 case MONO_AOT_OPTION_STATE_ESCAPE:
7274 g_assert_not_reached ();
7275 break;
7277 break;
7278 case '\\':
7279 // If we've found an escaping operator, then this means we
7280 // should not process the next character if inside a string.
7281 if (state == MONO_AOT_OPTION_STATE_STRING)
7282 state = MONO_AOT_OPTION_STATE_ESCAPE;
7283 break;
7284 case ',':
7285 // If we're in the default state then this means we've found
7286 // an option, store it for later processing.
7287 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7288 goto new_opt;
7289 break;
7292 next:
7293 aot_options++;
7294 restart:
7295 // If the next character is end of string, then process the last option.
7296 if (*(aot_options) == '\0') {
7297 end_of_string = TRUE;
7298 goto new_opt;
7300 continue;
7302 new_opt:
7303 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7304 opt_start = ++aot_options;
7305 if (end_of_string)
7306 break;
7307 goto restart; // Check for null and continue loop
7310 return args;
7313 static void
7314 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7316 GPtrArray* args;
7318 args = mono_aot_split_options (aot_options ? aot_options : "");
7319 for (int i = 0; i < args->len; ++i) {
7320 const char *arg = (const char *)g_ptr_array_index (args, i);
7322 if (str_begins_with (arg, "outfile=")) {
7323 opts->outfile = g_strdup (arg + strlen ("outfile="));
7324 } else if (str_begins_with (arg, "llvm-outfile=")) {
7325 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7326 } else if (str_begins_with (arg, "temp-path=")) {
7327 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7328 } else if (str_begins_with (arg, "save-temps")) {
7329 opts->save_temps = TRUE;
7330 } else if (str_begins_with (arg, "keep-temps")) {
7331 opts->save_temps = TRUE;
7332 } else if (str_begins_with (arg, "write-symbols")) {
7333 opts->write_symbols = TRUE;
7334 } else if (str_begins_with (arg, "no-write-symbols")) {
7335 opts->write_symbols = FALSE;
7336 // Intentionally undocumented -- one-off experiment
7337 } else if (str_begins_with (arg, "metadata-only")) {
7338 opts->metadata_only = TRUE;
7339 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7340 opts->bind_to_runtime_version = TRUE;
7341 } else if (str_begins_with (arg, "full")) {
7342 opts->mode = MONO_AOT_MODE_FULL;
7343 } else if (str_begins_with (arg, "hybrid")) {
7344 opts->mode = MONO_AOT_MODE_HYBRID;
7345 } else if (str_begins_with (arg, "interp")) {
7346 opts->mode = MONO_AOT_MODE_INTERP;
7347 } else if (str_begins_with (arg, "threads=")) {
7348 opts->nthreads = atoi (arg + strlen ("threads="));
7349 } else if (str_begins_with (arg, "static")) {
7350 opts->static_link = TRUE;
7351 opts->no_dlsym = TRUE;
7352 } else if (str_begins_with (arg, "asmonly")) {
7353 opts->asm_only = TRUE;
7354 } else if (str_begins_with (arg, "asmwriter")) {
7355 opts->asm_writer = TRUE;
7356 } else if (str_begins_with (arg, "nodebug")) {
7357 opts->nodebug = TRUE;
7358 } else if (str_begins_with (arg, "dwarfdebug")) {
7359 opts->dwarf_debug = TRUE;
7360 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7361 } else if (str_begins_with (arg, "nopagetrampolines")) {
7362 opts->use_trampolines_page = FALSE;
7363 } else if (str_begins_with (arg, "ntrampolines=")) {
7364 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7365 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7366 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7367 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7368 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7369 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7370 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7371 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7372 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7373 } else if (str_begins_with (arg, "tool-prefix=")) {
7374 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7375 } else if (str_begins_with (arg, "ld-flags=")) {
7376 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7377 } else if (str_begins_with (arg, "soft-debug")) {
7378 opts->soft_debug = TRUE;
7379 // Intentionally undocumented x2-- deprecated
7380 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7381 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7382 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7383 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7384 } else if (str_begins_with (arg, "msym-dir=")) {
7385 debug_options.no_seq_points_compact_data = FALSE;
7386 opts->gen_msym_dir = TRUE;
7387 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7388 } else if (str_begins_with (arg, "direct-pinvoke")) {
7389 opts->direct_pinvoke = TRUE;
7390 } else if (str_begins_with (arg, "direct-icalls")) {
7391 opts->direct_icalls = TRUE;
7392 } else if (str_begins_with (arg, "no-direct-calls")) {
7393 opts->no_direct_calls = TRUE;
7394 } else if (str_begins_with (arg, "print-skipped")) {
7395 opts->print_skipped_methods = TRUE;
7396 } else if (str_begins_with (arg, "stats")) {
7397 opts->stats = TRUE;
7398 // Intentionally undocumented-- has no known function other than to debug the compiler
7399 } else if (str_begins_with (arg, "no-instances")) {
7400 opts->no_instances = TRUE;
7401 // Intentionally undocumented x4-- Used for internal debugging of compiler
7402 } else if (str_begins_with (arg, "log-generics")) {
7403 opts->log_generics = TRUE;
7404 } else if (str_begins_with (arg, "log-instances=")) {
7405 opts->log_instances = TRUE;
7406 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7407 } else if (str_begins_with (arg, "log-instances")) {
7408 opts->log_instances = TRUE;
7409 } else if (str_begins_with (arg, "internal-logfile=")) {
7410 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7411 } else if (str_begins_with (arg, "dedup-skip")) {
7412 opts->dedup = TRUE;
7413 } else if (str_begins_with (arg, "dedup-include=")) {
7414 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
7415 } else if (str_begins_with (arg, "mtriple=")) {
7416 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7417 } else if (str_begins_with (arg, "llvm-path=")) {
7418 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7419 } else if (!strcmp (arg, "llvm")) {
7420 opts->llvm = TRUE;
7421 } else if (str_begins_with (arg, "readonly-value=")) {
7422 add_readonly_value (opts, arg + strlen ("readonly-value="));
7423 } else if (str_begins_with (arg, "info")) {
7424 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7425 exit (0);
7426 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7427 } else if (str_begins_with (arg, "gc-maps")) {
7428 mini_gc_enable_gc_maps_for_aot ();
7429 // Intentionally undocumented: Used for internal debugging
7430 } else if (str_begins_with (arg, "dump")) {
7431 opts->dump_json = TRUE;
7432 } else if (str_begins_with (arg, "llvmonly")) {
7433 opts->mode = MONO_AOT_MODE_FULL;
7434 opts->llvm = TRUE;
7435 opts->llvm_only = TRUE;
7436 } else if (str_begins_with (arg, "data-outfile=")) {
7437 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7438 } else if (str_begins_with (arg, "profile=")) {
7439 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7440 } else if (!strcmp (arg, "profile-only")) {
7441 opts->profile_only = TRUE;
7442 } else if (!strcmp (arg, "verbose")) {
7443 opts->verbose = TRUE;
7444 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7445 printf ("Supported options for --aot:\n");
7446 printf (" asmonly\n");
7447 printf (" bind-to-runtime-version\n");
7448 printf (" bitcode\n");
7449 printf (" data-outfile=\n");
7450 printf (" direct-icalls\n");
7451 printf (" direct-pinvoke\n");
7452 printf (" dwarfdebug\n");
7453 printf (" full\n");
7454 printf (" hybrid\n");
7455 printf (" info\n");
7456 printf (" keep-temps\n");
7457 printf (" llvm\n");
7458 printf (" llvmonly\n");
7459 printf (" llvm-outfile=\n");
7460 printf (" llvm-path=\n");
7461 printf (" msym-dir=\n");
7462 printf (" mtriple\n");
7463 printf (" nimt-trampolines=\n");
7464 printf (" nodebug\n");
7465 printf (" no-direct-calls\n");
7466 printf (" no-write-symbols\n");
7467 printf (" nrgctx-trampolines=\n");
7468 printf (" nrgctx-fetch-trampolines=\n");
7469 printf (" ngsharedvt-trampolines=\n");
7470 printf (" ntrampolines=\n");
7471 printf (" outfile=\n");
7472 printf (" profile=\n");
7473 printf (" profile-only\n");
7474 printf (" print-skipped-methods\n");
7475 printf (" readonly-value=\n");
7476 printf (" save-temps\n");
7477 printf (" soft-debug\n");
7478 printf (" static\n");
7479 printf (" stats\n");
7480 printf (" temp-path=\n");
7481 printf (" tool-prefix=\n");
7482 printf (" threads=\n");
7483 printf (" write-symbols\n");
7484 printf (" verbose\n");
7485 printf (" help/?\n");
7486 exit (0);
7487 } else {
7488 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7489 exit (1);
7492 g_free ((gpointer) arg);
7495 if (opts->use_trampolines_page) {
7496 opts->ntrampolines = 0;
7497 opts->nrgctx_trampolines = 0;
7498 opts->nimt_trampolines = 0;
7499 opts->ngsharedvt_arg_trampolines = 0;
7502 g_ptr_array_free (args, /*free_seg=*/TRUE);
7505 static void
7506 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7508 MonoMethod *method = (MonoMethod*)key;
7509 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7510 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7511 MonoJumpInfoToken *new_ji;
7513 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7514 new_ji->image = ji->image;
7515 new_ji->token = ji->token;
7516 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7519 static gboolean
7520 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7522 if (klass->type_token)
7523 return TRUE;
7524 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7525 return TRUE;
7526 if (klass->rank)
7527 return can_encode_class (acfg, klass->element_class);
7528 return FALSE;
7531 static gboolean
7532 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7534 if (method->wrapper_type) {
7535 switch (method->wrapper_type) {
7536 case MONO_WRAPPER_NONE:
7537 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7538 case MONO_WRAPPER_XDOMAIN_INVOKE:
7539 case MONO_WRAPPER_STFLD:
7540 case MONO_WRAPPER_LDFLD:
7541 case MONO_WRAPPER_LDFLDA:
7542 case MONO_WRAPPER_STELEMREF:
7543 case MONO_WRAPPER_PROXY_ISINST:
7544 case MONO_WRAPPER_ALLOC:
7545 case MONO_WRAPPER_REMOTING_INVOKE:
7546 case MONO_WRAPPER_UNKNOWN:
7547 case MONO_WRAPPER_WRITE_BARRIER:
7548 case MONO_WRAPPER_DELEGATE_INVOKE:
7549 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7550 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7551 case MONO_WRAPPER_SYNCHRONIZED:
7552 break;
7553 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7554 case MONO_WRAPPER_CASTCLASS: {
7555 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7557 if (info)
7558 return TRUE;
7559 else
7560 return FALSE;
7561 break;
7563 default:
7564 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7565 return FALSE;
7567 } else {
7568 if (!method->token) {
7569 /* The method is part of a constructed type like Int[,].Set (). */
7570 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7571 if (method->klass->rank)
7572 return TRUE;
7573 return FALSE;
7577 return TRUE;
7580 static gboolean
7581 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7583 switch (patch_info->type) {
7584 case MONO_PATCH_INFO_METHOD:
7585 case MONO_PATCH_INFO_METHODCONST:
7586 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7587 MonoMethod *method = patch_info->data.method;
7589 return can_encode_method (acfg, method);
7591 case MONO_PATCH_INFO_VTABLE:
7592 case MONO_PATCH_INFO_CLASS:
7593 case MONO_PATCH_INFO_IID:
7594 case MONO_PATCH_INFO_ADJUSTED_IID:
7595 if (!can_encode_class (acfg, patch_info->data.klass)) {
7596 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7597 return FALSE;
7599 break;
7600 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7601 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7602 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7603 return FALSE;
7605 break;
7607 case MONO_PATCH_INFO_RGCTX_FETCH:
7608 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7609 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7611 if (!can_encode_method (acfg, entry->method))
7612 return FALSE;
7613 if (!can_encode_patch (acfg, entry->data))
7614 return FALSE;
7615 break;
7617 default:
7618 break;
7621 return TRUE;
7624 static gboolean
7625 is_concrete_type (MonoType *t)
7627 MonoClass *klass;
7628 int i;
7630 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7631 return FALSE;
7632 if (t->type == MONO_TYPE_GENERICINST) {
7633 MonoGenericContext *orig_ctx;
7634 MonoGenericInst *inst;
7635 MonoType *arg;
7637 if (!MONO_TYPE_ISSTRUCT (t))
7638 return TRUE;
7639 klass = mono_class_from_mono_type (t);
7640 orig_ctx = &mono_class_get_generic_class (klass)->context;
7642 inst = orig_ctx->class_inst;
7643 if (inst) {
7644 for (i = 0; i < inst->type_argc; ++i) {
7645 arg = mini_get_underlying_type (inst->type_argv [i]);
7646 if (!is_concrete_type (arg))
7647 return FALSE;
7650 inst = orig_ctx->method_inst;
7651 if (inst) {
7652 for (i = 0; i < inst->type_argc; ++i) {
7653 arg = mini_get_underlying_type (inst->type_argv [i]);
7654 if (!is_concrete_type (arg))
7655 return FALSE;
7659 return TRUE;
7662 /* LOCKING: Assumes the loader lock is held */
7663 static void
7664 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7666 MonoMethod *wrapper;
7667 gboolean concrete = TRUE;
7668 gboolean add_in = gsharedvt_in;
7669 gboolean add_out = gsharedvt_out;
7671 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7672 add_in = FALSE;
7673 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7674 add_out = FALSE;
7676 if (!add_in && !add_out)
7677 return;
7679 if (mini_is_gsharedvt_variable_signature (sig))
7680 return;
7682 if (add_in)
7683 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7684 if (add_out)
7685 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7687 if (!sig->has_type_parameters) {
7688 //printf ("%s\n", mono_signature_full_name (sig));
7690 if (gsharedvt_in) {
7691 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7692 add_extra_method (acfg, wrapper);
7694 if (gsharedvt_out) {
7695 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7696 add_extra_method (acfg, wrapper);
7698 } else {
7699 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7700 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7701 int i;
7703 //printf ("%s\n", mono_signature_full_name (sig));
7705 copy->ret = mini_get_underlying_type (sig->ret);
7706 if (!is_concrete_type (copy->ret))
7707 concrete = FALSE;
7708 for (i = 0; i < sig->param_count; ++i) {
7709 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7710 if (!is_concrete_type (copy->params [i]))
7711 concrete = FALSE;
7713 if (concrete) {
7714 copy->has_type_parameters = 0;
7716 if (gsharedvt_in) {
7717 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7718 add_extra_method (acfg, wrapper);
7721 if (gsharedvt_out) {
7722 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7723 add_extra_method (acfg, wrapper);
7726 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7732 * compile_method:
7734 * AOT compile a given method.
7735 * This function might be called by multiple threads, so it must be thread-safe.
7737 static void
7738 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7740 MonoCompile *cfg;
7741 MonoJumpInfo *patch_info;
7742 gboolean skip;
7743 int index, depth;
7744 MonoMethod *wrapped;
7745 GTimer *jit_timer;
7746 JitFlags flags;
7748 if (acfg->aot_opts.metadata_only)
7749 return;
7751 mono_acfg_lock (acfg);
7752 index = get_method_index (acfg, method);
7753 mono_acfg_unlock (acfg);
7755 /* fixme: maybe we can also precompile wrapper methods */
7756 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7757 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7758 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7759 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7760 return;
7763 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7764 return;
7766 wrapped = mono_marshal_method_from_wrapper (method);
7767 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7768 // FIXME: The wrapper should be generic too, but it is not
7769 return;
7771 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7772 return;
7774 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7775 return;
7777 mono_atomic_inc_i32 (&acfg->stats.mcount);
7779 #if 0
7780 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7781 mono_atomic_inc_i32 (&acfg->stats.genericcount);
7782 return;
7784 #endif
7786 //acfg->aot_opts.print_skipped_methods = TRUE;
7789 * Since these methods are the only ones which are compiled with
7790 * AOT support, and they are not used by runtime startup/shutdown code,
7791 * the runtime will not see AOT methods during AOT compilation,so it
7792 * does not need to support them by creating a fake GOT etc.
7794 flags = JIT_FLAG_AOT;
7795 if (mono_aot_mode_is_full (&acfg->aot_opts))
7796 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7797 if (acfg->llvm)
7798 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7799 if (acfg->aot_opts.llvm_only)
7800 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7801 if (acfg->aot_opts.no_direct_calls)
7802 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7803 if (acfg->aot_opts.direct_pinvoke)
7804 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7806 jit_timer = mono_time_track_start ();
7807 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7808 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7810 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7811 if (acfg->aot_opts.print_skipped_methods)
7812 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7813 mono_atomic_inc_i32 (&acfg->stats.genericcount);
7814 return;
7816 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7817 /* Some instances cannot be JITted due to constraints etc. */
7818 if (!method->is_inflated)
7819 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));
7820 /* Let the exception happen at runtime */
7821 return;
7824 if (cfg->disable_aot) {
7825 if (acfg->aot_opts.print_skipped_methods)
7826 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7827 mono_atomic_inc_i32 (&acfg->stats.ocount);
7828 return;
7830 cfg->method_index = index;
7832 /* Nullify patches which need no aot processing */
7833 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7834 switch (patch_info->type) {
7835 case MONO_PATCH_INFO_LABEL:
7836 case MONO_PATCH_INFO_BB:
7837 patch_info->type = MONO_PATCH_INFO_NONE;
7838 break;
7839 default:
7840 break;
7844 /* Collect method->token associations from the cfg */
7845 mono_acfg_lock (acfg);
7846 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7847 mono_acfg_unlock (acfg);
7848 g_hash_table_destroy (cfg->token_info_hash);
7849 cfg->token_info_hash = NULL;
7852 * Check for absolute addresses.
7854 skip = FALSE;
7855 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7856 switch (patch_info->type) {
7857 case MONO_PATCH_INFO_ABS:
7858 /* unable to handle this */
7859 skip = TRUE;
7860 break;
7861 default:
7862 break;
7866 if (skip) {
7867 if (acfg->aot_opts.print_skipped_methods)
7868 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7869 mono_atomic_inc_i32 (&acfg->stats.abscount);
7870 return;
7873 /* Lock for the rest of the code */
7874 mono_acfg_lock (acfg);
7876 if (cfg->gsharedvt)
7877 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7878 else if (cfg->gshared)
7879 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7880 else if (cfg->method->wrapper_type)
7881 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7882 else
7883 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7886 * Check for methods/klasses we can't encode.
7888 skip = FALSE;
7889 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7890 if (!can_encode_patch (acfg, patch_info))
7891 skip = TRUE;
7894 if (skip) {
7895 if (acfg->aot_opts.print_skipped_methods)
7896 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7897 acfg->stats.ocount++;
7898 mono_acfg_unlock (acfg);
7899 return;
7902 if (!cfg->compile_llvm)
7903 acfg->has_jitted_code = TRUE;
7905 if (method->is_inflated && acfg->aot_opts.log_instances) {
7906 if (acfg->instances_logfile)
7907 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7908 else
7909 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7912 /* Adds generic instances referenced by this method */
7914 * The depth is used to avoid infinite loops when generic virtual recursion is
7915 * encountered.
7917 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7918 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
7919 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7920 switch (patch_info->type) {
7921 case MONO_PATCH_INFO_RGCTX_FETCH:
7922 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7923 case MONO_PATCH_INFO_METHOD:
7924 case MONO_PATCH_INFO_METHOD_RGCTX: {
7925 MonoMethod *m = NULL;
7927 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7928 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7930 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7931 m = e->data->data.method;
7932 } else {
7933 m = patch_info->data.method;
7936 if (!m)
7937 break;
7938 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
7939 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7940 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7941 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7942 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7943 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7944 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7945 } else {
7946 add_extra_method_with_depth (acfg, m, depth + 1);
7947 add_types_from_method_header (acfg, m);
7950 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7952 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7953 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7955 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7956 add_extra_method_with_depth (acfg, m, depth + 1);
7958 break;
7960 case MONO_PATCH_INFO_VTABLE: {
7961 MonoClass *klass = patch_info->data.klass;
7963 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7964 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7965 break;
7967 case MONO_PATCH_INFO_SFLDA: {
7968 MonoClass *klass = patch_info->data.field->parent;
7970 /* The .cctor needs to run at runtime. */
7971 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))
7972 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7973 break;
7975 default:
7976 break;
7981 /* Determine whenever the method has GOT slots */
7982 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7983 switch (patch_info->type) {
7984 case MONO_PATCH_INFO_GOT_OFFSET:
7985 case MONO_PATCH_INFO_NONE:
7986 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7987 case MONO_PATCH_INFO_GC_NURSERY_START:
7988 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7989 break;
7990 case MONO_PATCH_INFO_IMAGE:
7991 /* The assembly is stored in GOT slot 0 */
7992 if (patch_info->data.image != acfg->image)
7993 cfg->has_got_slots = TRUE;
7994 break;
7995 default:
7996 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7997 cfg->has_got_slots = TRUE;
7998 break;
8002 if (!cfg->has_got_slots)
8003 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8005 /* Add gsharedvt wrappers for signatures used by the method */
8006 if (acfg->aot_opts.llvm_only) {
8007 GSList *l;
8009 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8010 /* These only need out wrappers */
8011 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
8013 for (l = cfg->signatures; l; l = l->next) {
8014 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8016 /* These only need in wrappers */
8017 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
8022 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8024 /* Make a copy of the patch info which is in the mempool */
8026 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8028 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8029 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8031 if (!patches)
8032 patches = new_patch_info;
8033 else
8034 patches_end->next = new_patch_info;
8035 patches_end = new_patch_info;
8037 cfg->patch_info = patches;
8039 /* Make a copy of the unwind info */
8041 GSList *l, *unwind_ops;
8042 MonoUnwindOp *op;
8044 unwind_ops = NULL;
8045 for (l = cfg->unwind_ops; l; l = l->next) {
8046 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8047 memcpy (op, l->data, sizeof (MonoUnwindOp));
8048 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8050 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8052 /* Make a copy of the argument/local info */
8054 ERROR_DECL (error);
8055 MonoInst **args, **locals;
8056 MonoMethodSignature *sig;
8057 MonoMethodHeader *header;
8058 int i;
8060 sig = mono_method_signature (method);
8061 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8062 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8063 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8064 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8066 cfg->args = args;
8068 header = mono_method_get_header_checked (method, error);
8069 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8070 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8071 for (i = 0; i < header->num_locals; ++i) {
8072 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8073 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8075 mono_metadata_free_mh (header);
8076 cfg->locals = locals;
8079 /* Free some fields used by cfg to conserve memory */
8080 mono_empty_compile (cfg);
8082 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8084 while (index >= acfg->cfgs_size) {
8085 MonoCompile **new_cfgs;
8086 int new_size;
8088 new_size = acfg->cfgs_size * 2;
8089 new_cfgs = g_new0 (MonoCompile*, new_size);
8090 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8091 g_free (acfg->cfgs);
8092 acfg->cfgs = new_cfgs;
8093 acfg->cfgs_size = new_size;
8095 acfg->cfgs [index] = cfg;
8097 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8099 /* Update global stats while holding a lock. */
8100 mono_update_jit_stats (cfg);
8103 if (cfg->orig_method->wrapper_type)
8104 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8107 mono_acfg_unlock (acfg);
8109 mono_atomic_inc_i32 (&acfg->stats.ccount);
8112 static mono_thread_start_return_t WINAPI
8113 compile_thread_main (gpointer user_data)
8115 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8116 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8117 int i;
8119 ERROR_DECL (error);
8120 MonoInternalThread *internal = mono_thread_internal_current ();
8121 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8122 mono_error_assert_ok (error);
8123 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8124 mono_error_assert_ok (error);
8126 for (i = 0; i < methods->len; ++i)
8127 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8129 return 0;
8132 /* Used by the LLVM backend */
8133 guint32
8134 mono_aot_get_got_offset (MonoJumpInfo *ji)
8136 return get_got_offset (llvm_acfg, TRUE, ji);
8140 * mono_aot_is_shared_got_offset:
8142 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8143 * when the AOT image is loaded.
8145 gboolean
8146 mono_aot_is_shared_got_offset (int offset)
8148 return offset < llvm_acfg->nshared_got_entries;
8151 char*
8152 mono_aot_get_method_name (MonoCompile *cfg)
8154 if (llvm_acfg->aot_opts.static_link)
8155 /* Include the assembly name too to avoid duplicate symbol errors */
8156 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8157 else
8158 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8162 * mono_aot_is_linkonce_method:
8164 * Return whenever METHOD should be emitted with linkonce linkage,
8165 * eliminating duplicate copies when compiling in static mode.
8167 gboolean
8168 mono_aot_is_linkonce_method (MonoMethod *method)
8170 return FALSE;
8171 #if 0
8172 WrapperInfo *info;
8174 // FIXME: Add more cases
8175 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8176 return FALSE;
8177 info = mono_marshal_get_wrapper_info (method);
8178 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8179 return TRUE;
8180 return FALSE;
8181 #endif
8184 static gboolean
8185 append_mangled_type (GString *s, MonoType *t)
8187 if (t->byref)
8188 g_string_append_printf (s, "b");
8189 switch (t->type) {
8190 case MONO_TYPE_VOID:
8191 g_string_append_printf (s, "void_");
8192 break;
8193 case MONO_TYPE_I1:
8194 g_string_append_printf (s, "i1");
8195 break;
8196 case MONO_TYPE_U1:
8197 g_string_append_printf (s, "u1");
8198 break;
8199 case MONO_TYPE_I2:
8200 g_string_append_printf (s, "i2");
8201 break;
8202 case MONO_TYPE_U2:
8203 g_string_append_printf (s, "u2");
8204 break;
8205 case MONO_TYPE_I4:
8206 g_string_append_printf (s, "i4");
8207 break;
8208 case MONO_TYPE_U4:
8209 g_string_append_printf (s, "u4");
8210 break;
8211 case MONO_TYPE_I8:
8212 g_string_append_printf (s, "i8");
8213 break;
8214 case MONO_TYPE_U8:
8215 g_string_append_printf (s, "u8");
8216 break;
8217 case MONO_TYPE_I:
8218 g_string_append_printf (s, "ii");
8219 break;
8220 case MONO_TYPE_U:
8221 g_string_append_printf (s, "ui");
8222 break;
8223 case MONO_TYPE_R4:
8224 g_string_append_printf (s, "fl");
8225 break;
8226 case MONO_TYPE_R8:
8227 g_string_append_printf (s, "do");
8228 break;
8229 default: {
8230 char *fullname = mono_type_full_name (t);
8231 GString *temp;
8232 char *temps;
8233 int i, len;
8236 * Have to create a mangled name which is:
8237 * - a valid symbol
8238 * - unique
8240 temp = g_string_new ("");
8241 len = strlen (fullname);
8242 for (i = 0; i < len; ++i) {
8243 char c = fullname [i];
8244 if (isalnum (c)) {
8245 g_string_append_c (temp, c);
8246 } else if (c == '_') {
8247 g_string_append_c (temp, '_');
8248 g_string_append_c (temp, '_');
8249 } else {
8250 g_string_append_c (temp, '_');
8251 g_string_append_printf (temp, "%x", (int)c);
8254 temps = g_string_free (temp, FALSE);
8255 /* Include the length to avoid different length type names aliasing each other */
8256 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8257 g_free (temps);
8260 if (t->attrs)
8261 g_string_append_printf (s, "_attrs_%d", t->attrs);
8262 return TRUE;
8265 static gboolean
8266 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8268 int i;
8269 gboolean supported;
8271 supported = append_mangled_type (s, sig->ret);
8272 if (!supported)
8273 return FALSE;
8274 if (sig->hasthis)
8275 g_string_append_printf (s, "this_");
8276 if (sig->pinvoke)
8277 g_string_append_printf (s, "pinvoke_");
8278 for (i = 0; i < sig->param_count; ++i) {
8279 supported = append_mangled_type (s, sig->params [i]);
8280 if (!supported)
8281 return FALSE;
8284 return TRUE;
8287 static void
8288 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8290 const char *label;
8292 switch (wrapper_type) {
8293 case MONO_WRAPPER_REMOTING_INVOKE:
8294 label = "remoting_invoke";
8295 break;
8296 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8297 label = "remoting_invoke_check";
8298 break;
8299 case MONO_WRAPPER_XDOMAIN_INVOKE:
8300 label = "remoting_invoke_xdomain";
8301 break;
8302 case MONO_WRAPPER_PROXY_ISINST:
8303 label = "proxy_isinst";
8304 break;
8305 case MONO_WRAPPER_LDFLD:
8306 label = "ldfld";
8307 break;
8308 case MONO_WRAPPER_LDFLDA:
8309 label = "ldflda";
8310 break;
8311 case MONO_WRAPPER_STFLD:
8312 label = "stfld";
8313 break;
8314 case MONO_WRAPPER_ALLOC:
8315 label = "alloc";
8316 break;
8317 case MONO_WRAPPER_WRITE_BARRIER:
8318 label = "write_barrier";
8319 break;
8320 case MONO_WRAPPER_STELEMREF:
8321 label = "stelemref";
8322 break;
8323 case MONO_WRAPPER_UNKNOWN:
8324 label = "unknown";
8325 break;
8326 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8327 label = "man2native";
8328 break;
8329 case MONO_WRAPPER_SYNCHRONIZED:
8330 label = "synch";
8331 break;
8332 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8333 label = "man2man";
8334 break;
8335 case MONO_WRAPPER_CASTCLASS:
8336 label = "castclass";
8337 break;
8338 case MONO_WRAPPER_RUNTIME_INVOKE:
8339 label = "run_invoke";
8340 break;
8341 case MONO_WRAPPER_DELEGATE_INVOKE:
8342 label = "del_inv";
8343 break;
8344 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8345 label = "del_beg_inv";
8346 break;
8347 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8348 label = "del_end_inv";
8349 break;
8350 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8351 label = "native2man";
8352 break;
8353 default:
8354 g_assert_not_reached ();
8357 g_string_append_printf (s, "%s_", label);
8360 static void
8361 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8363 const char *label;
8365 switch (subtype)
8367 case WRAPPER_SUBTYPE_NONE:
8368 return;
8369 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8370 label = "elem_addr";
8371 break;
8372 case WRAPPER_SUBTYPE_STRING_CTOR:
8373 label = "str_ctor";
8374 break;
8375 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8376 label = "virt_stelem";
8377 break;
8378 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8379 label = "fast_mon_enter";
8380 break;
8381 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8382 label = "fast_mon_enter_4";
8383 break;
8384 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8385 label = "fast_monitor_exit";
8386 break;
8387 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8388 label = "ptr2struct";
8389 break;
8390 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8391 label = "struct2ptr";
8392 break;
8393 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8394 label = "castclass_w_cache";
8395 break;
8396 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8397 label = "isinst_w_cache";
8398 break;
8399 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8400 label = "run_inv_norm";
8401 break;
8402 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8403 label = "run_inv_dyn";
8404 break;
8405 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8406 label = "run_inv_dir";
8407 break;
8408 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8409 label = "run_inv_vir";
8410 break;
8411 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8412 label = "icall";
8413 break;
8414 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8415 label = "native_func_aot";
8416 break;
8417 case WRAPPER_SUBTYPE_PINVOKE:
8418 label = "pinvoke";
8419 break;
8420 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8421 label = "synch_inner";
8422 break;
8423 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8424 label = "gshared_in";
8425 break;
8426 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8427 label = "gshared_out";
8428 break;
8429 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8430 label = "array_acc";
8431 break;
8432 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8433 label = "generic_arry_help";
8434 break;
8435 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8436 label = "del_inv_virt";
8437 break;
8438 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8439 label = "del_inv_bound";
8440 break;
8441 case WRAPPER_SUBTYPE_INTERP_IN:
8442 label = "interp_in";
8443 break;
8444 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8445 label = "gsharedvt_in_sig";
8446 break;
8447 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8448 label = "gsharedvt_out_sig";
8449 break;
8450 default:
8451 g_assert_not_reached ();
8454 g_string_append_printf (s, "%s_", label);
8457 static char *
8458 sanitize_mangled_string (const char *input)
8460 GString *s = g_string_new ("");
8462 for (int i=0; input [i] != '\0'; i++) {
8463 char c = input [i];
8464 switch (c) {
8465 case '.':
8466 g_string_append (s, "_dot_");
8467 break;
8468 case ' ':
8469 g_string_append (s, "_");
8470 break;
8471 case '`':
8472 g_string_append (s, "_bt_");
8473 break;
8474 case '<':
8475 g_string_append (s, "_le_");
8476 break;
8477 case '>':
8478 g_string_append (s, "_gt_");
8479 break;
8480 case '/':
8481 g_string_append (s, "_sl_");
8482 break;
8483 case '[':
8484 g_string_append (s, "_lbrack_");
8485 break;
8486 case ']':
8487 g_string_append (s, "_rbrack_");
8488 break;
8489 case '(':
8490 g_string_append (s, "_lparen_");
8491 break;
8492 case '-':
8493 g_string_append (s, "_dash_");
8494 break;
8495 case ')':
8496 g_string_append (s, "_rparen_");
8497 break;
8498 case ',':
8499 g_string_append (s, "_comma_");
8500 break;
8501 case ':':
8502 g_string_append (s, "_colon_");
8503 break;
8504 default:
8505 g_string_append_c (s, c);
8509 return g_string_free (s, FALSE);
8512 static gboolean
8513 append_mangled_klass (GString *s, MonoClass *klass)
8515 char *klass_desc = mono_class_full_name (klass);
8516 g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8517 g_free (klass_desc);
8519 // Success
8520 return TRUE;
8523 static gboolean
8524 append_mangled_method (GString *s, MonoMethod *method);
8526 static gboolean
8527 append_mangled_wrapper (GString *s, MonoMethod *method)
8529 gboolean success = TRUE;
8530 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8531 g_string_append_printf (s, "wrapper_");
8532 g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8534 append_mangled_wrapper_type (s, method->wrapper_type);
8536 switch (method->wrapper_type) {
8537 case MONO_WRAPPER_REMOTING_INVOKE:
8538 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8539 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8540 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8541 g_assert (m);
8542 success = success && append_mangled_method (s, m);
8543 break;
8545 case MONO_WRAPPER_PROXY_ISINST:
8546 case MONO_WRAPPER_LDFLD:
8547 case MONO_WRAPPER_LDFLDA:
8548 case MONO_WRAPPER_STFLD: {
8549 g_assert (info);
8550 success = success && append_mangled_klass (s, info->d.proxy.klass);
8551 break;
8553 case MONO_WRAPPER_ALLOC: {
8554 /* The GC name is saved once in MonoAotFileInfo */
8555 g_assert (info->d.alloc.alloc_type != -1);
8556 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8557 // SlowAlloc, etc
8558 g_string_append_printf (s, "%s_", method->name);
8559 break;
8561 case MONO_WRAPPER_WRITE_BARRIER: {
8562 g_string_append_printf (s, "%s_", method->name);
8563 break;
8565 case MONO_WRAPPER_STELEMREF: {
8566 append_mangled_wrapper_subtype (s, info->subtype);
8567 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8568 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8569 break;
8571 case MONO_WRAPPER_UNKNOWN: {
8572 append_mangled_wrapper_subtype (s, info->subtype);
8573 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8574 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8575 success = success && append_mangled_klass (s, method->klass);
8576 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8577 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8578 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8579 success = success && append_mangled_method (s, info->d.array_accessor.method);
8580 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
8581 append_mangled_signature (s, info->d.interp_in.sig);
8582 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8583 append_mangled_signature (s, info->d.gsharedvt.sig);
8584 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8585 append_mangled_signature (s, info->d.gsharedvt.sig);
8586 break;
8588 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8589 append_mangled_wrapper_subtype (s, info->subtype);
8590 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8591 g_string_append_printf (s, "%s", method->name);
8592 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8593 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8594 } else {
8595 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8596 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8598 break;
8600 case MONO_WRAPPER_SYNCHRONIZED: {
8601 MonoMethod *m;
8603 m = mono_marshal_method_from_wrapper (method);
8604 g_assert (m);
8605 g_assert (m != method);
8606 success = success && append_mangled_method (s, m);
8607 break;
8609 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8610 append_mangled_wrapper_subtype (s, info->subtype);
8612 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8613 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8614 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8615 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8616 success = success && append_mangled_method (s, info->d.string_ctor.method);
8617 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
8618 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
8619 } else {
8620 success = FALSE;
8622 break;
8624 case MONO_WRAPPER_CASTCLASS: {
8625 append_mangled_wrapper_subtype (s, info->subtype);
8626 break;
8628 case MONO_WRAPPER_RUNTIME_INVOKE: {
8629 append_mangled_wrapper_subtype (s, info->subtype);
8630 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8631 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8632 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8633 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8634 break;
8636 case MONO_WRAPPER_DELEGATE_INVOKE:
8637 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8638 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8639 if (method->is_inflated) {
8640 /* These wrappers are identified by their class */
8641 g_string_append_printf (s, "i_");
8642 success = success && append_mangled_klass (s, method->klass);
8643 } else {
8644 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8646 g_string_append_printf (s, "u_");
8647 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8648 append_mangled_wrapper_subtype (s, info->subtype);
8649 g_string_append_printf (s, "u_sigstart");
8651 break;
8653 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8654 g_assert (info);
8655 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8656 success = success && append_mangled_klass (s, method->klass);
8657 break;
8659 default:
8660 g_assert_not_reached ();
8662 return success && append_mangled_signature (s, mono_method_signature (method));
8665 static void
8666 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
8668 int i;
8670 for (i = 0; i < ginst->type_argc; ++i) {
8671 if (i > 0)
8672 g_string_append (str, ", ");
8673 MonoType *type = ginst->type_argv [i];
8674 switch (type->type) {
8675 case MONO_TYPE_VAR:
8676 case MONO_TYPE_MVAR: {
8677 MonoType *constraint = NULL;
8678 if (type->data.generic_param)
8679 constraint = type->data.generic_param->gshared_constraint;
8680 if (constraint) {
8681 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
8682 g_string_append (str, "gshared:");
8683 mono_type_get_desc (str, constraint, TRUE);
8684 break;
8686 // Else falls through to common case
8688 default:
8689 mono_type_get_desc (str, type, TRUE);
8694 static void
8695 append_mangled_context (GString *str, MonoGenericContext *context)
8697 GString *res = g_string_new ("");
8699 g_string_append_printf (res, "gens_");
8700 g_string_append (res, "00");
8702 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8703 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8704 g_assert (good);
8706 if (context->class_inst)
8707 append_mangled_ginst (res, context->class_inst);
8708 if (context->method_inst) {
8709 if (context->class_inst)
8710 g_string_append (res, "11");
8711 append_mangled_ginst (res, context->method_inst);
8713 g_string_append_printf (str, "gens_%s", res->str);
8714 g_free (res);
8717 static gboolean
8718 append_mangled_method (GString *s, MonoMethod *method)
8720 if (method->wrapper_type)
8721 return append_mangled_wrapper (s, method);
8723 if (method->is_inflated) {
8724 g_string_append_printf (s, "inflated_");
8725 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8726 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8728 append_mangled_context (s, &imethod->context);
8729 g_string_append_printf (s, "_declared_by_");
8730 append_mangled_method (s, imethod->declaring);
8731 } else if (method->is_generic) {
8732 g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8734 g_string_append_printf (s, "generic_");
8735 append_mangled_klass (s, method->klass);
8736 g_string_append_printf (s, "_%s_", method->name);
8738 MonoGenericContainer *container = mono_method_get_generic_container (method);
8739 g_string_append_printf (s, "_%s");
8740 append_mangled_context (s, &container->context);
8742 return append_mangled_signature (s, mono_method_signature (method));
8743 } else {
8744 g_string_append_printf (s, "_");
8745 append_mangled_klass (s, method->klass);
8746 g_string_append_printf (s, "_%s_", method->name);
8747 if (!append_mangled_signature (s, mono_method_signature (method))) {
8748 g_string_free (s, TRUE);
8749 return FALSE;
8753 return TRUE;
8757 * mono_aot_get_mangled_method_name:
8759 * Return a unique mangled name for METHOD, or NULL.
8761 char*
8762 mono_aot_get_mangled_method_name (MonoMethod *method)
8764 // FIXME: use static cache (mempool?)
8765 // We call this a *lot*
8767 GString *s = g_string_new ("aot_");
8768 if (!append_mangled_method (s, method)) {
8769 g_string_free (s, TRUE);
8770 return NULL;
8771 } else {
8772 char *out = g_string_free (s, FALSE);
8773 // Scrub method and class names
8774 char *cleaned = sanitize_mangled_string (out);
8775 g_free (out);
8776 return cleaned;
8780 gboolean
8781 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8783 return is_direct_callable (llvm_acfg, NULL, patch_info);
8786 void
8787 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8789 MonoPltEntry *plt_entry;
8791 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8792 plt_entry->llvm_used = FALSE;
8795 char*
8796 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8798 const char *sym = NULL;
8800 if (llvm_acfg->aot_opts.direct_icalls) {
8801 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8802 /* Call to a C function implementing a jit icall */
8803 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8804 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8805 MonoMethod *method = (MonoMethod *)data;
8806 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8807 sym = mono_lookup_icall_symbol (method);
8808 else if (llvm_acfg->aot_opts.direct_pinvoke)
8809 sym = get_pinvoke_import (llvm_acfg, method);
8811 if (sym)
8812 return g_strdup (sym);
8814 return NULL;
8817 char*
8818 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8820 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8821 MonoPltEntry *plt_entry;
8822 const char *sym = NULL;
8824 ji->type = type;
8825 ji->data.target = data;
8827 if (!can_encode_patch (llvm_acfg, ji))
8828 return NULL;
8830 if (llvm_acfg->aot_opts.direct_icalls) {
8831 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8832 /* Call to a C function implementing a jit icall */
8833 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8834 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8835 MonoMethod *method = (MonoMethod *)data;
8836 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8837 sym = mono_lookup_icall_symbol (method);
8839 if (sym)
8840 return g_strdup (sym);
8843 plt_entry = get_plt_entry (llvm_acfg, ji);
8844 plt_entry->llvm_used = TRUE;
8846 #if defined(TARGET_MACH)
8847 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8848 #else
8849 return g_strdup_printf (plt_entry->llvm_symbol);
8850 #endif
8854 mono_aot_get_method_index (MonoMethod *method)
8856 g_assert (llvm_acfg);
8857 return get_method_index (llvm_acfg, method);
8860 MonoJumpInfo*
8861 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8863 MonoJumpInfo *res;
8865 mono_acfg_lock (llvm_acfg);
8866 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8867 mono_acfg_unlock (llvm_acfg);
8869 return res;
8872 static int
8873 execute_system (const char * command)
8875 int status = 0;
8877 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
8878 // We need an extra set of quotes around the whole command to properly handle commands
8879 // with spaces since internally the command is called through "cmd /c.
8880 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8882 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8883 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8884 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8885 status = _wsystem (wstr);
8886 g_free (wstr);
8888 g_free (quoted_command);
8889 #elif defined (HAVE_SYSTEM)
8890 status = system (command);
8891 #else
8892 g_assert_not_reached ();
8893 #endif
8895 return status;
8898 #ifdef ENABLE_LLVM
8901 * emit_llvm_file:
8903 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8904 * tools.
8906 static gboolean
8907 emit_llvm_file (MonoAotCompile *acfg)
8909 char *command, *opts, *tempbc, *optbc, *output_fname;
8911 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8912 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8913 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8914 } else {
8915 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8916 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8919 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8922 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8923 * a lot of time, and doesn't seem to save much space.
8924 * The following optimizations cannot be enabled:
8925 * - 'tailcallelim'
8926 * - 'jump-threading' changes our blockaddress references to int constants.
8927 * - 'basiccg' fails because it contains:
8928 * if (CS && !isa<IntrinsicInst>(II)) {
8929 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8930 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8931 * The opt list below was produced by taking the output of:
8932 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8933 * then removing tailcallelim + the global opts.
8934 * strip-dead-prototypes deletes unused intrinsics definitions.
8936 /* The dse pass is disabled because of #13734 and #17616 */
8938 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8939 * // If we have no DataLayout information around, then the size of the store
8940 * // is inferrable from the pointee type. If they are the same type, then
8941 * // we know that the store is safe.
8942 * if (AA.getDataLayout() == 0 &&
8943 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8944 * return OverwriteComplete;
8945 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8947 if (acfg->aot_opts.llvm_only)
8948 // FIXME: This doesn't work yet
8949 opts = g_strdup ("");
8950 else
8951 #if LLVM_API_VERSION > 100
8952 opts = g_strdup ("-O2 -disable-tail-calls");
8953 #else
8954 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");
8955 #endif
8956 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8957 aot_printf (acfg, "Executing opt: %s\n", command);
8958 if (execute_system (command) != 0)
8959 return FALSE;
8960 g_free (opts);
8962 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8963 /* Nothing else to do */
8964 return TRUE;
8966 if (acfg->aot_opts.llvm_only) {
8967 /* Use the stock clang from xcode */
8968 // FIXME: arch
8969 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8971 aot_printf (acfg, "Executing clang: %s\n", command);
8972 if (execute_system (command) != 0)
8973 return FALSE;
8974 return TRUE;
8977 if (!acfg->llc_args)
8978 acfg->llc_args = g_string_new ("");
8980 /* Verbose asm slows down llc greatly */
8981 g_string_append (acfg->llc_args, " -asm-verbose=false");
8983 if (acfg->aot_opts.mtriple)
8984 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8986 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8988 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8990 #if LLVM_API_VERSION > 100
8991 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8992 #endif
8994 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
8995 /* ios requires PIC code now */
8996 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8997 #else
8998 if (llvm_acfg->aot_opts.static_link)
8999 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9000 else
9001 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9002 #endif
9004 if (acfg->llvm_owriter) {
9005 /* Emit an object file directly */
9006 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9007 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9008 } else {
9009 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9011 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9012 g_free (output_fname);
9014 aot_printf (acfg, "Executing llc: %s\n", command);
9016 if (execute_system (command) != 0)
9017 return FALSE;
9018 return TRUE;
9020 #endif
9022 static void
9023 emit_code (MonoAotCompile *acfg)
9025 int oindex, i, prev_index;
9026 gboolean saved_unbox_info = FALSE;
9027 char symbol [MAX_SYMBOL_SIZE];
9029 if (acfg->aot_opts.llvm_only)
9030 return;
9032 #if defined(TARGET_POWERPC64)
9033 sprintf (symbol, ".Lgot_addr");
9034 emit_section_change (acfg, ".text", 0);
9035 emit_alignment (acfg, 8);
9036 emit_label (acfg, symbol);
9037 emit_pointer (acfg, acfg->got_symbol);
9038 #endif
9041 * This global symbol is used to compute the address of each method using the
9042 * code_offsets array. It is also used to compute the memory ranges occupied by
9043 * AOT code, so it must be equal to the address of the first emitted method.
9045 emit_section_change (acfg, ".text", 0);
9046 emit_alignment_code (acfg, 8);
9047 emit_info_symbol (acfg, "jit_code_start");
9050 * Emit some padding so the local symbol for the first method doesn't have the
9051 * same address as 'methods'.
9053 emit_padding (acfg, 16);
9055 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9056 MonoCompile *cfg;
9057 MonoMethod *method;
9059 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9061 cfg = acfg->cfgs [i];
9063 if (!cfg)
9064 continue;
9066 method = cfg->orig_method;
9068 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9069 gboolean dedupable = mono_aot_can_dedup (method);
9071 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9072 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9073 mono_dedup_cache_method (acfg, method);
9075 // Don't compile inflated methods if we're in first phase of
9076 // dedup
9078 // In second phase, we emit methods that
9079 // are dedupable. We also emit later methods
9080 // which are referenced by them and added later.
9081 // For this reason, when in the dedup_include mode,
9082 // we never set skip.
9083 if (acfg->aot_opts.dedup)
9084 cfg->skip = TRUE;
9087 // Don't compile anything in this mode
9088 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9089 cfg->skip = TRUE;
9091 // Compile everything in this mode
9092 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9093 cfg->skip = FALSE;
9095 /*if (dedup_collect) {*/
9096 /*char *name = mono_aot_get_mangled_method_name (method);*/
9098 /*if (ignore_cfg (cfg))*/
9099 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9100 /*else*/
9101 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9103 /*g_free (name);*/
9104 /*}*/
9106 if (ignore_cfg (cfg))
9107 continue;
9109 /* Emit unbox trampoline */
9110 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
9111 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9113 emit_section_change (acfg, ".text", 0);
9115 if (acfg->thumb_mixed && cfg->compile_llvm) {
9116 emit_set_thumb_mode (acfg);
9117 fprintf (acfg->fp, "\n.thumb_func\n");
9120 emit_label (acfg, symbol);
9122 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9124 if (acfg->thumb_mixed && cfg->compile_llvm)
9125 emit_set_arm_mode (acfg);
9127 if (!saved_unbox_info) {
9128 char user_symbol [128];
9129 GSList *unwind_ops;
9130 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9132 emit_label (acfg, "ut_end");
9134 unwind_ops = mono_unwind_get_cie_program ();
9135 save_unwind_info (acfg, user_symbol, unwind_ops);
9136 mono_free_unwind_info (unwind_ops);
9138 /* Save the unbox trampoline size */
9139 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9141 saved_unbox_info = TRUE;
9145 if (cfg->compile_llvm) {
9146 acfg->stats.llvm_count ++;
9147 } else {
9148 emit_method_code (acfg, cfg);
9152 emit_section_change (acfg, ".text", 0);
9153 emit_alignment_code (acfg, 8);
9154 emit_info_symbol (acfg, "jit_code_end");
9156 /* To distinguish it from the next symbol */
9157 emit_padding (acfg, 4);
9160 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9161 * from optimizing them away, since it doesn't see that code_offsets references them.
9162 * JITted methods don't need this since they are referenced using assembler local
9163 * symbols.
9164 * FIXME: This is why write-symbols doesn't work on OSX ?
9166 if (acfg->llvm && acfg->need_no_dead_strip) {
9167 fprintf (acfg->fp, "\n");
9168 for (i = 0; i < acfg->nmethods; ++i) {
9169 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9170 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9175 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9176 * This is PIE code, and the linker can update it if needed.
9179 sprintf (symbol, "method_addresses");
9180 emit_section_change (acfg, ".text", 1);
9181 emit_alignment_code (acfg, 8);
9182 emit_info_symbol (acfg, symbol);
9183 if (acfg->aot_opts.write_symbols)
9184 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9185 emit_unset_mode (acfg);
9186 if (acfg->need_no_dead_strip)
9187 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9189 for (i = 0; i < acfg->nmethods; ++i) {
9190 #ifdef MONO_ARCH_AOT_SUPPORTED
9191 int call_size;
9193 if (!ignore_cfg (acfg->cfgs [i])) {
9194 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9195 } else {
9196 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9198 #endif
9201 sprintf (symbol, "method_addresses_end");
9202 emit_label (acfg, symbol);
9203 emit_line (acfg);
9205 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9206 sprintf (symbol, "unbox_trampolines");
9207 emit_section_change (acfg, RODATA_SECT, 0);
9208 emit_alignment (acfg, 8);
9209 emit_info_symbol (acfg, symbol);
9211 prev_index = -1;
9212 for (i = 0; i < acfg->nmethods; ++i) {
9213 MonoCompile *cfg;
9214 MonoMethod *method;
9215 int index;
9217 cfg = acfg->cfgs [i];
9218 if (ignore_cfg (cfg))
9219 continue;
9221 method = cfg->orig_method;
9223 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
9224 index = get_method_index (acfg, method);
9226 emit_int32 (acfg, index);
9227 /* Make sure the table is sorted by index */
9228 g_assert (index > prev_index);
9229 prev_index = index;
9232 sprintf (symbol, "unbox_trampolines_end");
9233 emit_info_symbol (acfg, symbol);
9234 emit_int32 (acfg, 0);
9236 /* Emit a separate table with the trampoline addresses/offsets */
9237 sprintf (symbol, "unbox_trampoline_addresses");
9238 emit_section_change (acfg, ".text", 0);
9239 emit_alignment_code (acfg, 8);
9240 emit_info_symbol (acfg, symbol);
9242 for (i = 0; i < acfg->nmethods; ++i) {
9243 MonoCompile *cfg;
9244 MonoMethod *method;
9245 int index;
9247 cfg = acfg->cfgs [i];
9248 if (ignore_cfg (cfg))
9249 continue;
9251 method = cfg->orig_method;
9253 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
9254 #ifdef MONO_ARCH_AOT_SUPPORTED
9255 int call_size;
9257 index = get_method_index (acfg, method);
9258 sprintf (symbol, "ut_%d", index);
9260 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9261 #endif
9264 emit_int32 (acfg, 0);
9267 static void
9268 emit_info (MonoAotCompile *acfg)
9270 int oindex, i;
9271 gint32 *offsets;
9273 offsets = g_new0 (gint32, acfg->nmethods);
9275 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9276 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9278 if (acfg->cfgs [i]) {
9279 emit_method_info (acfg, acfg->cfgs [i]);
9280 offsets [i] = acfg->cfgs [i]->method_info_offset;
9281 } else {
9282 offsets [i] = 0;
9286 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9288 g_free (offsets);
9291 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9293 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9294 #define mix(a,b,c) { \
9295 a -= c; a ^= rot(c, 4); c += b; \
9296 b -= a; b ^= rot(a, 6); a += c; \
9297 c -= b; c ^= rot(b, 8); b += a; \
9298 a -= c; a ^= rot(c,16); c += b; \
9299 b -= a; b ^= rot(a,19); a += c; \
9300 c -= b; c ^= rot(b, 4); b += a; \
9302 #define final(a,b,c) { \
9303 c ^= b; c -= rot(b,14); \
9304 a ^= c; a -= rot(c,11); \
9305 b ^= a; b -= rot(a,25); \
9306 c ^= b; c -= rot(b,16); \
9307 a ^= c; a -= rot(c,4); \
9308 b ^= a; b -= rot(a,14); \
9309 c ^= b; c -= rot(b,24); \
9312 static guint
9313 mono_aot_type_hash (MonoType *t1)
9315 guint hash = t1->type;
9317 hash |= t1->byref << 6; /* do not collide with t1->type values */
9318 switch (t1->type) {
9319 case MONO_TYPE_VALUETYPE:
9320 case MONO_TYPE_CLASS:
9321 case MONO_TYPE_SZARRAY:
9322 /* check if the distribution is good enough */
9323 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9324 case MONO_TYPE_PTR:
9325 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9326 case MONO_TYPE_ARRAY:
9327 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9328 case MONO_TYPE_GENERICINST:
9329 return ((hash << 5) - hash) ^ 0;
9330 default:
9331 return hash;
9336 * mono_aot_method_hash:
9338 * Return a hash code for methods which only depends on metadata.
9340 guint32
9341 mono_aot_method_hash (MonoMethod *method)
9343 MonoMethodSignature *sig;
9344 MonoClass *klass;
9345 int i, hindex;
9346 int hashes_count;
9347 guint32 *hashes_start, *hashes;
9348 guint32 a, b, c;
9349 MonoGenericInst *class_ginst = NULL;
9350 MonoGenericInst *ginst = NULL;
9352 /* Similar to the hash in mono_method_get_imt_slot () */
9354 sig = mono_method_signature (method);
9356 if (mono_class_is_ginst (method->klass))
9357 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9358 if (method->is_inflated)
9359 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9361 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9362 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9363 hashes = hashes_start;
9365 /* Some wrappers are assigned to random classes */
9366 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9367 klass = method->klass;
9368 else
9369 klass = mono_defaults.object_class;
9371 if (!method->wrapper_type) {
9372 char *full_name;
9374 if (mono_class_is_ginst (klass))
9375 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9376 else
9377 full_name = mono_type_full_name (&klass->byval_arg);
9379 hashes [0] = mono_metadata_str_hash (full_name);
9380 hashes [1] = 0;
9381 g_free (full_name);
9382 } else {
9383 hashes [0] = mono_metadata_str_hash (klass->name);
9384 hashes [1] = mono_metadata_str_hash (klass->name_space);
9386 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9387 /* The method name includes a stringified pointer */
9388 hashes [2] = 0;
9389 else
9390 hashes [2] = mono_metadata_str_hash (method->name);
9391 hashes [3] = method->wrapper_type;
9392 hashes [4] = mono_aot_type_hash (sig->ret);
9393 hindex = 5;
9394 for (i = 0; i < sig->param_count; i++) {
9395 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9397 if (class_ginst) {
9398 for (i = 0; i < class_ginst->type_argc; ++i)
9399 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9401 if (ginst) {
9402 for (i = 0; i < ginst->type_argc; ++i)
9403 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9405 g_assert (hindex == hashes_count);
9407 /* Setup internal state */
9408 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9410 /* Handle most of the hashes */
9411 while (hashes_count > 3) {
9412 a += hashes [0];
9413 b += hashes [1];
9414 c += hashes [2];
9415 mix (a,b,c);
9416 hashes_count -= 3;
9417 hashes += 3;
9420 /* Handle the last 3 hashes (all the case statements fall through) */
9421 switch (hashes_count) {
9422 case 3 : c += hashes [2];
9423 case 2 : b += hashes [1];
9424 case 1 : a += hashes [0];
9425 final (a,b,c);
9426 case 0: /* nothing left to add */
9427 break;
9430 g_free (hashes_start);
9432 return c;
9434 #undef rot
9435 #undef mix
9436 #undef final
9439 * mono_aot_get_array_helper_from_wrapper;
9441 * Get the helper method in Array called by an array wrapper method.
9443 MonoMethod*
9444 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9446 MonoMethod *m;
9447 const char *prefix;
9448 MonoGenericContext ctx;
9449 MonoType *args [16];
9450 char *mname, *iname, *s, *s2, *helper_name = NULL;
9452 prefix = "System.Collections.Generic";
9453 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9454 s2 = strstr (s, "`1.");
9455 g_assert (s2);
9456 s2 [0] = '\0';
9457 iname = s;
9458 mname = s2 + 3;
9460 //printf ("X: %s %s\n", iname, mname);
9462 if (!strcmp (iname, "IList"))
9463 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9464 else
9465 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9466 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9467 g_assert (m);
9468 g_free (helper_name);
9469 g_free (s);
9471 if (m->is_generic) {
9472 ERROR_DECL (error);
9473 memset (&ctx, 0, sizeof (ctx));
9474 args [0] = &method->klass->element_class->byval_arg;
9475 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9476 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
9477 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9480 return m;
9483 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9485 typedef struct HashEntry {
9486 guint32 key, value, index;
9487 struct HashEntry *next;
9488 } HashEntry;
9491 * emit_extra_methods:
9493 * Emit methods which are not in the METHOD table, like wrappers.
9495 static void
9496 emit_extra_methods (MonoAotCompile *acfg)
9498 int i, table_size, buf_size;
9499 guint8 *p, *buf;
9500 guint32 *info_offsets;
9501 guint32 hash;
9502 GPtrArray *table;
9503 HashEntry *entry, *new_entry;
9504 int nmethods, max_chain_length;
9505 int *chain_lengths;
9507 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9509 /* Emit method info */
9510 nmethods = 0;
9511 for (i = 0; i < acfg->extra_methods->len; ++i) {
9512 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9513 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9515 if (ignore_cfg (cfg))
9516 continue;
9518 buf_size = 10240;
9519 p = buf = (guint8 *)g_malloc (buf_size);
9521 nmethods ++;
9523 method = cfg->method_to_register;
9525 encode_method_ref (acfg, method, p, &p);
9527 g_assert ((p - buf) < buf_size);
9529 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9530 g_free (buf);
9534 * Construct a chained hash table for mapping indexes in extra_method_info to
9535 * method indexes.
9537 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9538 table = g_ptr_array_sized_new (table_size);
9539 for (i = 0; i < table_size; ++i)
9540 g_ptr_array_add (table, NULL);
9541 chain_lengths = g_new0 (int, table_size);
9542 max_chain_length = 0;
9543 for (i = 0; i < acfg->extra_methods->len; ++i) {
9544 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9545 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9546 guint32 key, value;
9548 if (ignore_cfg (cfg))
9549 continue;
9551 key = info_offsets [i];
9552 value = get_method_index (acfg, method);
9554 hash = mono_aot_method_hash (method) % table_size;
9555 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9557 chain_lengths [hash] ++;
9558 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9560 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9561 new_entry->key = key;
9562 new_entry->value = value;
9564 entry = (HashEntry *)g_ptr_array_index (table, hash);
9565 if (entry == NULL) {
9566 new_entry->index = hash;
9567 g_ptr_array_index (table, hash) = new_entry;
9568 } else {
9569 while (entry->next)
9570 entry = entry->next;
9572 entry->next = new_entry;
9573 new_entry->index = table->len;
9574 g_ptr_array_add (table, new_entry);
9577 g_free (chain_lengths);
9579 //printf ("MAX: %d\n", max_chain_length);
9581 buf_size = table->len * 12 + 4;
9582 p = buf = (guint8 *)g_malloc (buf_size);
9583 encode_int (table_size, p, &p);
9585 for (i = 0; i < table->len; ++i) {
9586 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9588 if (entry == NULL) {
9589 encode_int (0, p, &p);
9590 encode_int (0, p, &p);
9591 encode_int (0, p, &p);
9592 } else {
9593 //g_assert (entry->key > 0);
9594 encode_int (entry->key, p, &p);
9595 encode_int (entry->value, p, &p);
9596 if (entry->next)
9597 encode_int (entry->next->index, p, &p);
9598 else
9599 encode_int (0, p, &p);
9602 g_assert (p - buf <= buf_size);
9604 /* Emit the table */
9605 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9607 g_free (buf);
9610 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9611 * This is used by mono_aot_find_jit_info ().
9613 buf_size = acfg->extra_methods->len * 8 + 4;
9614 p = buf = (guint8 *)g_malloc (buf_size);
9615 encode_int (acfg->extra_methods->len, p, &p);
9616 for (i = 0; i < acfg->extra_methods->len; ++i) {
9617 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9619 encode_int (get_method_index (acfg, method), p, &p);
9620 encode_int (info_offsets [i], p, &p);
9622 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9624 g_free (buf);
9625 g_free (info_offsets);
9626 g_ptr_array_free (table, TRUE);
9629 static void
9630 generate_aotid (guint8* aotid)
9632 gpointer rand_handle;
9633 ERROR_DECL (error);
9635 mono_rand_open ();
9636 rand_handle = mono_rand_init (NULL, 0);
9638 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
9639 mono_error_assert_ok (error);
9641 mono_rand_close (rand_handle);
9644 static void
9645 emit_exception_info (MonoAotCompile *acfg)
9647 int i;
9648 gint32 *offsets;
9649 SeqPointData sp_data;
9650 gboolean seq_points_to_file = FALSE;
9652 offsets = g_new0 (gint32, acfg->nmethods);
9653 for (i = 0; i < acfg->nmethods; ++i) {
9654 if (acfg->cfgs [i]) {
9655 MonoCompile *cfg = acfg->cfgs [i];
9657 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9658 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9659 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9660 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9661 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9663 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9664 offsets [i] = cfg->ex_info_offset;
9666 if (method_seq_points_to_file) {
9667 if (!seq_points_to_file) {
9668 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9669 seq_points_to_file = TRUE;
9671 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9673 } else {
9674 offsets [i] = 0;
9678 if (seq_points_to_file) {
9679 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9680 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9681 char *image_basename = g_path_get_basename (acfg->image->name);
9682 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9683 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9685 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9686 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9687 exit (1);
9690 mono_seq_point_data_write (&sp_data, aot_file_path);
9691 mono_seq_point_data_free (&sp_data);
9693 g_free (aotid);
9694 g_free (dir);
9695 g_free (image_basename);
9696 g_free (aot_file);
9697 g_free (aot_file_path);
9700 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9701 g_free (offsets);
9704 static void
9705 emit_unwind_info (MonoAotCompile *acfg)
9707 int i;
9708 char symbol [128];
9710 if (acfg->aot_opts.llvm_only) {
9711 g_assert (acfg->unwind_ops->len == 0);
9712 return;
9716 * The unwind info contains a lot of duplicates so we emit each unique
9717 * entry once, and only store the offset from the start of the table in the
9718 * exception info.
9721 sprintf (symbol, "unwind_info");
9722 emit_section_change (acfg, RODATA_SECT, 1);
9723 emit_alignment (acfg, 8);
9724 emit_info_symbol (acfg, symbol);
9726 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9727 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9728 guint8 *unwind_info;
9729 guint32 unwind_info_len;
9730 guint8 buf [16];
9731 guint8 *p;
9733 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9735 p = buf;
9736 encode_value (unwind_info_len, p, &p);
9737 emit_bytes (acfg, buf, p - buf);
9738 emit_bytes (acfg, unwind_info, unwind_info_len);
9740 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9744 static void
9745 emit_class_info (MonoAotCompile *acfg)
9747 int i;
9748 gint32 *offsets;
9750 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9751 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9752 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9754 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);
9755 g_free (offsets);
9758 typedef struct ClassNameTableEntry {
9759 guint32 token, index;
9760 struct ClassNameTableEntry *next;
9761 } ClassNameTableEntry;
9763 static void
9764 emit_class_name_table (MonoAotCompile *acfg)
9766 int i, table_size, buf_size;
9767 guint32 token, hash;
9768 MonoClass *klass;
9769 GPtrArray *table;
9770 char *full_name;
9771 guint8 *buf, *p;
9772 ClassNameTableEntry *entry, *new_entry;
9775 * Construct a chained hash table for mapping class names to typedef tokens.
9777 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9778 table = g_ptr_array_sized_new (table_size);
9779 for (i = 0; i < table_size; ++i)
9780 g_ptr_array_add (table, NULL);
9781 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9782 ERROR_DECL (error);
9783 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9784 klass = mono_class_get_checked (acfg->image, token, error);
9785 if (!klass) {
9786 mono_error_cleanup (error);
9787 continue;
9789 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9790 hash = mono_metadata_str_hash (full_name) % table_size;
9791 g_free (full_name);
9793 /* FIXME: Allocate from the mempool */
9794 new_entry = g_new0 (ClassNameTableEntry, 1);
9795 new_entry->token = token;
9797 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9798 if (entry == NULL) {
9799 new_entry->index = hash;
9800 g_ptr_array_index (table, hash) = new_entry;
9801 } else {
9802 while (entry->next)
9803 entry = entry->next;
9805 entry->next = new_entry;
9806 new_entry->index = table->len;
9807 g_ptr_array_add (table, new_entry);
9811 /* Emit the table */
9812 buf_size = table->len * 4 + 4;
9813 p = buf = (guint8 *)g_malloc0 (buf_size);
9815 /* FIXME: Optimize memory usage */
9816 g_assert (table_size < 65000);
9817 encode_int16 (table_size, p, &p);
9818 g_assert (table->len < 65000);
9819 for (i = 0; i < table->len; ++i) {
9820 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9822 if (entry == NULL) {
9823 encode_int16 (0, p, &p);
9824 encode_int16 (0, p, &p);
9825 } else {
9826 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9827 if (entry->next)
9828 encode_int16 (entry->next->index, p, &p);
9829 else
9830 encode_int16 (0, p, &p);
9832 g_free (entry);
9834 g_assert (p - buf <= buf_size);
9835 g_ptr_array_free (table, TRUE);
9837 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9839 g_free (buf);
9842 static void
9843 emit_image_table (MonoAotCompile *acfg)
9845 int i, buf_size;
9846 guint8 *buf, *p;
9849 * The image table is small but referenced in a lot of places.
9850 * So we emit it at once, and reference its elements by an index.
9852 buf_size = acfg->image_table->len * 28 + 4;
9853 for (i = 0; i < acfg->image_table->len; i++) {
9854 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9855 MonoAssemblyName *aname = &image->assembly->aname;
9857 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9860 buf = p = (guint8 *)g_malloc0 (buf_size);
9861 encode_int (acfg->image_table->len, p, &p);
9862 for (i = 0; i < acfg->image_table->len; i++) {
9863 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9864 MonoAssemblyName *aname = &image->assembly->aname;
9866 /* FIXME: Support multi-module assemblies */
9867 g_assert (image->assembly->image == image);
9869 encode_string (image->assembly_name, p, &p);
9870 encode_string (image->guid, p, &p);
9871 encode_string (aname->culture ? aname->culture : "", p, &p);
9872 encode_string ((const char*)aname->public_key_token, p, &p);
9874 while (GPOINTER_TO_UINT (p) % 8 != 0)
9875 p ++;
9877 encode_int (aname->flags, p, &p);
9878 encode_int (aname->major, p, &p);
9879 encode_int (aname->minor, p, &p);
9880 encode_int (aname->build, p, &p);
9881 encode_int (aname->revision, p, &p);
9883 g_assert (p - buf <= buf_size);
9885 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9887 g_free (buf);
9890 static void
9891 emit_weak_field_indexes (MonoAotCompile *acfg)
9893 GHashTable *indexes;
9894 GHashTableIter iter;
9895 gpointer key, value;
9896 int buf_size;
9897 guint8 *buf, *p;
9899 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
9900 mono_assembly_init_weak_fields (acfg->image);
9901 indexes = acfg->image->weak_field_indexes;
9902 g_assert (indexes);
9904 buf_size = (g_hash_table_size (indexes) + 1) * 4;
9905 buf = p = (guint8 *)g_malloc0 (buf_size);
9907 encode_int (g_hash_table_size (indexes), p, &p);
9908 g_hash_table_iter_init (&iter, indexes);
9909 while (g_hash_table_iter_next (&iter, &key, &value)) {
9910 guint32 index = GPOINTER_TO_UINT (key);
9911 encode_int (index, p, &p);
9913 g_assert (p - buf <= buf_size);
9915 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
9917 g_free (buf);
9920 static void
9921 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9923 int i, first_plt_got_patch = 0, buf_size;
9924 guint8 *p, *buf;
9925 guint32 *got_info_offsets;
9926 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9928 /* Add the patches needed by the PLT to the GOT */
9929 if (!llvm) {
9930 acfg->plt_got_offset_base = acfg->got_offset;
9931 first_plt_got_patch = info->got_patches->len;
9932 for (i = 1; i < acfg->plt_offset; ++i) {
9933 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9935 g_ptr_array_add (info->got_patches, plt_entry->ji);
9937 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9940 acfg->got_offset += acfg->plt_offset;
9944 * FIXME:
9945 * - optimize offsets table.
9946 * - reduce number of exported symbols.
9947 * - emit info for a klass only once.
9948 * - determine when a method uses a GOT slot which is guaranteed to be already
9949 * initialized.
9950 * - clean up and document the code.
9951 * - use String.Empty in class libs.
9954 /* Encode info required to decode shared GOT entries */
9955 buf_size = info->got_patches->len * 128;
9956 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9957 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9958 if (!llvm) {
9959 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9960 /* Unused */
9961 if (acfg->plt_offset)
9962 acfg->plt_got_info_offsets [0] = 0;
9964 for (i = 0; i < info->got_patches->len; ++i) {
9965 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9966 guint8 *p2;
9968 p = buf;
9970 encode_value (ji->type, p, &p);
9971 p2 = p;
9972 encode_patch (acfg, ji, p, &p);
9973 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9974 g_assert (p - buf <= buf_size);
9975 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9977 if (!llvm && i >= first_plt_got_patch)
9978 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9979 acfg->stats.got_info_size += p - buf;
9982 /* Emit got_info_offsets table */
9984 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9985 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);
9988 static void
9989 emit_got (MonoAotCompile *acfg)
9991 char symbol [MAX_SYMBOL_SIZE];
9993 if (acfg->aot_opts.llvm_only)
9994 return;
9996 /* Don't make GOT global so accesses to it don't need relocations */
9997 sprintf (symbol, "%s", acfg->got_symbol);
9999 #ifdef TARGET_MACH
10000 emit_unset_mode (acfg);
10001 fprintf (acfg->fp, ".section __DATA, __bss\n");
10002 emit_alignment (acfg, 8);
10003 if (acfg->llvm)
10004 emit_info_symbol (acfg, "jit_got");
10005 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
10006 #else
10007 emit_section_change (acfg, ".bss", 0);
10008 emit_alignment (acfg, 8);
10009 if (acfg->aot_opts.write_symbols)
10010 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10011 emit_label (acfg, symbol);
10012 if (acfg->llvm)
10013 emit_info_symbol (acfg, "jit_got");
10014 if (acfg->got_offset > 0)
10015 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
10016 #endif
10018 sprintf (symbol, "got_end");
10019 emit_label (acfg, symbol);
10022 typedef struct GlobalsTableEntry {
10023 guint32 value, index;
10024 struct GlobalsTableEntry *next;
10025 } GlobalsTableEntry;
10027 #ifdef TARGET_WIN32_MSVC
10028 #define DLL_ENTRY_POINT "DllMain"
10030 static void
10031 emit_library_info (MonoAotCompile *acfg)
10033 // Only include for shared libraries linked directly from generated object.
10034 if (link_shared_library (acfg)) {
10035 char *name = NULL;
10036 char symbol [MAX_SYMBOL_SIZE];
10038 // Ask linker to export all global symbols.
10039 emit_section_change (acfg, ".drectve", 0);
10040 for (guint i = 0; i < acfg->globals->len; ++i) {
10041 name = (char *)g_ptr_array_index (acfg->globals, i);
10042 g_assert (name != NULL);
10043 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10044 emit_string (acfg, symbol);
10047 // Emit DLLMain function, needed by MSVC linker for DLL's.
10048 // NOTE, DllMain should not go into exports above.
10049 emit_section_change (acfg, ".text", 0);
10050 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10051 emit_label (acfg, DLL_ENTRY_POINT);
10053 // Simple implementation of DLLMain, just returning TRUE.
10054 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10055 fprintf (acfg->fp, "movl $1, %%eax\n");
10056 fprintf (acfg->fp, "ret\n");
10058 // Inform linker about our dll entry function.
10059 emit_section_change (acfg, ".drectve", 0);
10060 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10061 return;
10065 #else
10067 static inline void
10068 emit_library_info (MonoAotCompile *acfg)
10070 return;
10072 #endif
10074 static void
10075 emit_globals (MonoAotCompile *acfg)
10077 int i, table_size;
10078 guint32 hash;
10079 GPtrArray *table;
10080 char symbol [1024];
10081 GlobalsTableEntry *entry, *new_entry;
10083 if (!acfg->aot_opts.static_link)
10084 return;
10086 if (acfg->aot_opts.llvm_only) {
10087 g_assert (acfg->globals->len == 0);
10088 return;
10092 * When static linking, we emit a table containing our globals.
10096 * Construct a chained hash table for mapping global names to their index in
10097 * the globals table.
10099 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10100 table = g_ptr_array_sized_new (table_size);
10101 for (i = 0; i < table_size; ++i)
10102 g_ptr_array_add (table, NULL);
10103 for (i = 0; i < acfg->globals->len; ++i) {
10104 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10106 hash = mono_metadata_str_hash (name) % table_size;
10108 /* FIXME: Allocate from the mempool */
10109 new_entry = g_new0 (GlobalsTableEntry, 1);
10110 new_entry->value = i;
10112 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10113 if (entry == NULL) {
10114 new_entry->index = hash;
10115 g_ptr_array_index (table, hash) = new_entry;
10116 } else {
10117 while (entry->next)
10118 entry = entry->next;
10120 entry->next = new_entry;
10121 new_entry->index = table->len;
10122 g_ptr_array_add (table, new_entry);
10126 /* Emit the table */
10127 sprintf (symbol, ".Lglobals_hash");
10128 emit_section_change (acfg, RODATA_SECT, 0);
10129 emit_alignment (acfg, 8);
10130 emit_label (acfg, symbol);
10132 /* FIXME: Optimize memory usage */
10133 g_assert (table_size < 65000);
10134 emit_int16 (acfg, table_size);
10135 for (i = 0; i < table->len; ++i) {
10136 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10138 if (entry == NULL) {
10139 emit_int16 (acfg, 0);
10140 emit_int16 (acfg, 0);
10141 } else {
10142 emit_int16 (acfg, entry->value + 1);
10143 if (entry->next)
10144 emit_int16 (acfg, entry->next->index);
10145 else
10146 emit_int16 (acfg, 0);
10150 /* Emit the names */
10151 for (i = 0; i < acfg->globals->len; ++i) {
10152 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10154 sprintf (symbol, "name_%d", i);
10155 emit_section_change (acfg, RODATA_SECT, 1);
10156 #ifdef TARGET_MACH
10157 emit_alignment (acfg, 4);
10158 #endif
10159 emit_label (acfg, symbol);
10160 emit_string (acfg, name);
10163 /* Emit the globals table */
10164 sprintf (symbol, "globals");
10165 emit_section_change (acfg, ".data", 0);
10166 /* This is not a global, since it is accessed by the init function */
10167 emit_alignment (acfg, 8);
10168 emit_info_symbol (acfg, symbol);
10170 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10171 emit_pointer (acfg, symbol);
10173 for (i = 0; i < acfg->globals->len; ++i) {
10174 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10176 sprintf (symbol, "name_%d", i);
10177 emit_pointer (acfg, symbol);
10179 g_assert (strlen (name) < sizeof (symbol));
10180 sprintf (symbol, "%s", name);
10181 emit_pointer (acfg, symbol);
10183 /* Null terminate the table */
10184 emit_int32 (acfg, 0);
10185 emit_int32 (acfg, 0);
10188 static void
10189 emit_mem_end (MonoAotCompile *acfg)
10191 char symbol [128];
10193 if (acfg->aot_opts.llvm_only)
10194 return;
10196 sprintf (symbol, "mem_end");
10197 emit_section_change (acfg, ".text", 1);
10198 emit_alignment_code (acfg, 8);
10199 emit_label (acfg, symbol);
10202 static void
10203 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10205 int i;
10207 info->version = MONO_AOT_FILE_VERSION;
10208 info->plt_got_offset_base = acfg->plt_got_offset_base;
10209 info->got_size = acfg->got_offset * sizeof (gpointer);
10210 info->plt_size = acfg->plt_offset;
10211 info->nmethods = acfg->nmethods;
10212 info->flags = acfg->flags;
10213 info->opts = acfg->opts;
10214 info->simd_opts = acfg->simd_opts;
10215 info->gc_name_index = acfg->gc_name_offset;
10216 info->datafile_size = acfg->datafile_offset;
10217 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10218 info->table_offsets [i] = acfg->table_offsets [i];
10219 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10220 info->num_trampolines [i] = acfg->num_trampolines [i];
10221 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10222 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10223 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10224 info->trampoline_size [i] = acfg->trampoline_size [i];
10225 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10227 info->double_align = MONO_ABI_ALIGNOF (double);
10228 info->long_align = MONO_ABI_ALIGNOF (gint64);
10229 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10230 info->tramp_page_size = acfg->tramp_page_size;
10231 info->nshared_got_entries = acfg->nshared_got_entries;
10232 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10233 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10235 memcpy(&info->aotid, acfg->image->aotid, 16);
10238 static void
10239 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10241 char symbol [MAX_SYMBOL_SIZE];
10242 int i, sindex;
10243 const char **symbols;
10245 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10246 sindex = 0;
10247 symbols [sindex ++] = acfg->got_symbol;
10248 if (acfg->llvm) {
10249 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10250 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
10251 } else {
10252 symbols [sindex ++] = NULL;
10253 symbols [sindex ++] = NULL;
10255 /* llvm_get_method */
10256 symbols [sindex ++] = NULL;
10257 /* llvm_get_unbox_tramp */
10258 symbols [sindex ++] = NULL;
10259 if (!acfg->aot_opts.llvm_only) {
10260 symbols [sindex ++] = "jit_code_start";
10261 symbols [sindex ++] = "jit_code_end";
10262 symbols [sindex ++] = "method_addresses";
10263 } else {
10264 symbols [sindex ++] = NULL;
10265 symbols [sindex ++] = NULL;
10266 symbols [sindex ++] = NULL;
10269 if (acfg->data_outfile) {
10270 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10271 symbols [sindex ++] = NULL;
10272 } else {
10273 symbols [sindex ++] = "blob";
10274 symbols [sindex ++] = "class_name_table";
10275 symbols [sindex ++] = "class_info_offsets";
10276 symbols [sindex ++] = "method_info_offsets";
10277 symbols [sindex ++] = "ex_info_offsets";
10278 symbols [sindex ++] = "extra_method_info_offsets";
10279 symbols [sindex ++] = "extra_method_table";
10280 symbols [sindex ++] = "got_info_offsets";
10281 if (acfg->llvm)
10282 symbols [sindex ++] = "llvm_got_info_offsets";
10283 else
10284 symbols [sindex ++] = NULL;
10285 symbols [sindex ++] = "image_table";
10286 symbols [sindex ++] = "weak_field_indexes";
10289 symbols [sindex ++] = "mem_end";
10290 symbols [sindex ++] = "assembly_guid";
10291 symbols [sindex ++] = "runtime_version";
10292 if (acfg->num_trampoline_got_entries) {
10293 symbols [sindex ++] = "specific_trampolines";
10294 symbols [sindex ++] = "static_rgctx_trampolines";
10295 symbols [sindex ++] = "imt_trampolines";
10296 symbols [sindex ++] = "gsharedvt_arg_trampolines";
10297 } else {
10298 symbols [sindex ++] = NULL;
10299 symbols [sindex ++] = NULL;
10300 symbols [sindex ++] = NULL;
10301 symbols [sindex ++] = NULL;
10303 if (acfg->aot_opts.static_link) {
10304 symbols [sindex ++] = "globals";
10305 } else {
10306 symbols [sindex ++] = NULL;
10308 symbols [sindex ++] = "assembly_name";
10309 symbols [sindex ++] = "plt";
10310 symbols [sindex ++] = "plt_end";
10311 symbols [sindex ++] = "unwind_info";
10312 if (!acfg->aot_opts.llvm_only) {
10313 symbols [sindex ++] = "unbox_trampolines";
10314 symbols [sindex ++] = "unbox_trampolines_end";
10315 symbols [sindex ++] = "unbox_trampoline_addresses";
10316 } else {
10317 symbols [sindex ++] = NULL;
10318 symbols [sindex ++] = NULL;
10319 symbols [sindex ++] = NULL;
10322 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10324 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10325 emit_section_change (acfg, ".data", 0);
10326 emit_alignment (acfg, 8);
10327 emit_label (acfg, symbol);
10328 if (!acfg->aot_opts.static_link)
10329 emit_global (acfg, symbol, FALSE);
10331 /* The data emitted here must match MonoAotFileInfo. */
10333 emit_int32 (acfg, info->version);
10334 emit_int32 (acfg, info->dummy);
10337 * We emit pointers to our data structures instead of emitting global symbols which
10338 * point to them, to reduce the number of globals, and because using globals leads to
10339 * various problems (i.e. arm/thumb).
10341 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10342 emit_pointer (acfg, symbols [i]);
10344 emit_int32 (acfg, info->plt_got_offset_base);
10345 emit_int32 (acfg, info->got_size);
10346 emit_int32 (acfg, info->plt_size);
10347 emit_int32 (acfg, info->nmethods);
10348 emit_int32 (acfg, info->flags);
10349 emit_int32 (acfg, info->opts);
10350 emit_int32 (acfg, info->simd_opts);
10351 emit_int32 (acfg, info->gc_name_index);
10352 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10353 emit_int32 (acfg, info->double_align);
10354 emit_int32 (acfg, info->long_align);
10355 emit_int32 (acfg, info->generic_tramp_num);
10356 emit_int32 (acfg, info->tramp_page_size);
10357 emit_int32 (acfg, info->nshared_got_entries);
10358 emit_int32 (acfg, info->datafile_size);
10360 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10361 emit_int32 (acfg, info->table_offsets [i]);
10362 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10363 emit_int32 (acfg, info->num_trampolines [i]);
10364 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10365 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10366 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10367 emit_int32 (acfg, info->trampoline_size [i]);
10368 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10369 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10371 emit_bytes (acfg, info->aotid, 16);
10373 if (acfg->aot_opts.static_link) {
10374 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10375 emit_alignment (acfg, sizeof (gpointer));
10376 emit_label (acfg, acfg->static_linking_symbol);
10377 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10382 * Emit a structure containing all the information not stored elsewhere.
10384 static void
10385 emit_file_info (MonoAotCompile *acfg)
10387 char *build_info;
10388 MonoAotFileInfo *info;
10390 if (acfg->aot_opts.bind_to_runtime_version) {
10391 build_info = mono_get_runtime_build_info ();
10392 emit_string_symbol (acfg, "runtime_version", build_info);
10393 g_free (build_info);
10394 } else {
10395 emit_string_symbol (acfg, "runtime_version", "");
10398 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10400 /* Emit a string holding the assembly name */
10401 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10403 info = g_new0 (MonoAotFileInfo, 1);
10404 init_aot_file_info (acfg, info);
10406 if (acfg->aot_opts.static_link) {
10407 char symbol [MAX_SYMBOL_SIZE];
10408 char *p;
10411 * Emit a global symbol which can be passed by an embedding app to
10412 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10413 * structure.
10415 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10417 /* Get rid of characters which cannot occur in symbols */
10418 p = symbol;
10419 for (p = symbol; *p; ++p) {
10420 if (!(isalnum (*p) || *p == '_'))
10421 *p = '_';
10423 acfg->static_linking_symbol = g_strdup (symbol);
10426 if (acfg->llvm)
10427 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10428 else
10429 emit_aot_file_info (acfg, info);
10432 static void
10433 emit_blob (MonoAotCompile *acfg)
10435 acfg->blob_closed = TRUE;
10437 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10440 static void
10441 emit_objc_selectors (MonoAotCompile *acfg)
10443 int i;
10444 char symbol [128];
10446 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10447 return;
10450 * From
10451 * cat > foo.m << EOF
10452 * void *ret ()
10454 * return @selector(print:);
10456 * EOF
10459 mono_img_writer_emit_unset_mode (acfg->w);
10460 g_assert (acfg->fp);
10461 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10462 fprintf (acfg->fp, ".align 3\n");
10463 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10464 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10465 emit_label (acfg, symbol);
10466 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10467 emit_pointer (acfg, symbol);
10470 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10471 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10472 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10473 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10476 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10477 fprintf (acfg->fp, ".align 3\n");
10478 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10479 fprintf (acfg->fp, ".long 0\n");
10480 fprintf (acfg->fp, ".long 16\n");
10483 static void
10484 emit_dwarf_info (MonoAotCompile *acfg)
10486 #ifdef EMIT_DWARF_INFO
10487 int i;
10488 char symbol2 [128];
10490 /* DIEs for methods */
10491 for (i = 0; i < acfg->nmethods; ++i) {
10492 MonoCompile *cfg = acfg->cfgs [i];
10494 if (ignore_cfg (cfg))
10495 continue;
10497 // FIXME: LLVM doesn't define .Lme_...
10498 if (cfg->compile_llvm)
10499 continue;
10501 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10503 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 ()));
10505 #endif
10508 #ifdef EMIT_WIN32_CODEVIEW_INFO
10509 typedef struct _CodeViewSubSectionData
10511 gchar *start_section;
10512 gchar *end_section;
10513 gchar *start_section_record;
10514 gchar *end_section_record;
10515 int section_type;
10516 int section_record_type;
10517 int section_id;
10518 } CodeViewSubsectionData;
10520 typedef struct _CodeViewCompilerVersion
10522 gint major;
10523 gint minor;
10524 gint revision;
10525 gint patch;
10526 } CodeViewCompilerVersion;
10528 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
10529 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
10530 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
10531 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
10532 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
10533 #define CODEVIEW_CPU_TYPE 0x0
10534 #define CODEVIEW_MAGIC_HEADER 0x4
10536 static void
10537 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
10539 g_free (section_data->start_section);
10540 g_free (section_data->end_section);
10541 g_free (section_data->start_section_record);
10542 g_free (section_data->end_section_record);
10544 memset (section_data, 0, sizeof (CodeViewSubsectionData));
10547 static void
10548 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
10550 gint values[4] = { 0 };
10551 gint *value = values;
10553 while (*version && (value < values + G_N_ELEMENTS (values))) {
10554 if (isdigit (*version)) {
10555 *value *= 10;
10556 *value += *version - '0';
10558 else if (*version == '.') {
10559 value++;
10562 version++;
10565 data->major = values[0];
10566 data->minor = values[1];
10567 data->revision = values[2];
10568 data->patch = values[3];
10571 static void
10572 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
10574 // Starting a new subsection, clear old data.
10575 codeview_clear_subsection_data (section_data);
10577 // Keep subsection data.
10578 section_data->section_id = section_id;
10579 section_data->section_type = section_type;
10580 section_data->section_record_type = section_record_type;
10582 // Allocate all labels used in subsection.
10583 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
10584 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
10585 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
10586 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
10588 // Subsection type, function symbol.
10589 emit_int32 (acfg, section_data->section_type);
10591 // Subsection size.
10592 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
10593 emit_label (acfg, section_data->start_section);
10595 // Subsection record size.
10596 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
10597 emit_label (acfg, section_data->start_section_record);
10599 // Subsection record type.
10600 emit_int16 (acfg, section_record_type);
10603 static void
10604 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10606 g_assert (section_data->start_section);
10607 g_assert (section_data->end_section);
10608 g_assert (section_data->start_section_record);
10609 g_assert (section_data->end_section_record);
10611 emit_label (acfg, section_data->end_section_record);
10613 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
10614 // Emit record length.
10615 emit_int16 (acfg, 2);
10617 // Emit specific record type end.
10618 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
10621 emit_label (acfg, section_data->end_section);
10623 // Next subsection needs to be 4 byte aligned.
10624 emit_alignment (acfg, 4);
10626 *section_id = section_data->section_id + 1;
10627 codeview_clear_subsection_data (section_data);
10630 inline static void
10631 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
10633 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
10636 inline static void
10637 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10639 emit_codeview_end_subsection (acfg, section_data, section_id);
10642 static void
10643 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
10645 CodeViewSubsectionData section_data = { 0 };
10646 CodeViewCompilerVersion compiler_version = { 0 };
10648 // Start new compiler record subsection.
10649 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
10651 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
10652 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
10654 // Get compiler version information.
10655 codeview_parse_compiler_version (VERSION, &compiler_version);
10657 // Compiler frontend version, 4 digits.
10658 emit_int16 (acfg, compiler_version.major);
10659 emit_int16 (acfg, compiler_version.minor);
10660 emit_int16 (acfg, compiler_version.revision);
10661 emit_int16 (acfg, compiler_version.patch);
10663 // Compiler backend version, 4 digits (currently same as frontend).
10664 emit_int16 (acfg, compiler_version.major);
10665 emit_int16 (acfg, compiler_version.minor);
10666 emit_int16 (acfg, compiler_version.revision);
10667 emit_int16 (acfg, compiler_version.patch);
10669 // Compiler string.
10670 emit_string (acfg, "Mono AOT compiler");
10672 // Done with section.
10673 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
10676 static void
10677 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
10679 CodeViewSubsectionData section_data = { 0 };
10680 gchar *full_method_name = NULL;
10682 // Start new function record subsection.
10683 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
10685 // Emit 3 int 0 byte padding, currently not used.
10686 emit_zero_bytes (acfg, sizeof (int) * 3);
10688 // Emit size of function.
10689 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
10691 // Emit 3 int 0 byte padding, currently not used.
10692 emit_zero_bytes (acfg, sizeof (int) * 3);
10694 // Emit reallocation info.
10695 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
10696 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
10698 // Emit flag, currently not used.
10699 emit_zero_bytes (acfg, 1);
10701 // Emit function name, exclude signature since it should be described by own metadata.
10702 full_method_name = mono_method_full_name (method, FALSE);
10703 emit_string (acfg, full_method_name ? full_method_name : "");
10704 g_free (full_method_name);
10706 // Done with section.
10707 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
10710 static void
10711 emit_codeview_info (MonoAotCompile *acfg)
10713 int i;
10714 int section_id = 0;
10715 gchar symbol_buffer[MAX_SYMBOL_SIZE];
10717 // Emit codeview debug info section
10718 emit_section_change (acfg, ".debug$S", 0);
10720 // Emit magic header.
10721 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
10723 emit_codeview_compiler_info (acfg, &section_id);
10725 for (i = 0; i < acfg->nmethods; ++i) {
10726 MonoCompile *cfg = acfg->cfgs[i];
10728 if (!cfg)
10729 continue;
10731 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
10732 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
10733 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
10736 #else
10737 static void
10738 emit_codeview_info (MonoAotCompile *acfg)
10741 #endif /* EMIT_WIN32_CODEVIEW_INFO */
10743 #ifdef EMIT_WIN32_UNWIND_INFO
10744 static UnwindInfoSectionCacheItem *
10745 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
10747 UnwindInfoSectionCacheItem *item = NULL;
10749 if (!acfg->unwind_info_section_cache)
10750 acfg->unwind_info_section_cache = g_list_alloc ();
10752 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
10754 // Search for unwind info in cache.
10755 GList *list = acfg->unwind_info_section_cache;
10756 int list_size = 0;
10757 while (list && list->data) {
10758 item = (UnwindInfoSectionCacheItem*)list->data;
10759 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
10760 // Cache hit, return cached item.
10761 return item;
10763 list = list->next;
10764 list_size++;
10767 // Add to cache.
10768 if (acfg->unwind_info_section_cache) {
10769 item = g_new0 (UnwindInfoSectionCacheItem, 1);
10770 if (item) {
10771 // Format .xdata section label for function, used to get unwind info address RVA.
10772 // Since the unwind info is similar for most functions, the symbol will be reused.
10773 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
10775 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
10776 //over ownership of unwind info.
10777 item->unwind_info = unwind_info;
10779 // Needs to be emitted once.
10780 item->xdata_section_emitted = FALSE;
10782 // Prepend to beginning of list to speed up inserts.
10783 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
10787 return item;
10790 static void
10791 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
10793 GList *list = acfg->unwind_info_section_cache;
10795 while (list) {
10796 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
10797 if (item) {
10798 g_free (item->xdata_section_label);
10799 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
10801 g_free (item);
10802 list->data = NULL;
10805 list = list->next;
10808 g_list_free (acfg->unwind_info_section_cache);
10809 acfg->unwind_info_section_cache = NULL;
10812 static void
10813 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
10815 // Emit the unwind info struct.
10816 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
10818 // Emit all unwind codes encoded in unwind info struct.
10819 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
10820 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
10822 while (current_unwind_node < last_unwind_node) {
10823 guint8 node_count = 0;
10824 switch (current_unwind_node->UnwindOp) {
10825 case UWOP_PUSH_NONVOL:
10826 case UWOP_ALLOC_SMALL:
10827 case UWOP_SET_FPREG:
10828 case UWOP_PUSH_MACHFRAME:
10829 node_count = 1;
10830 break;
10831 case UWOP_SAVE_NONVOL:
10832 case UWOP_SAVE_XMM128:
10833 node_count = 2;
10834 break;
10835 case UWOP_SAVE_NONVOL_FAR:
10836 case UWOP_SAVE_XMM128_FAR:
10837 node_count = 3;
10838 break;
10839 case UWOP_ALLOC_LARGE:
10840 if (current_unwind_node->OpInfo == 0)
10841 node_count = 2;
10842 else
10843 node_count = 3;
10844 break;
10845 default:
10846 g_assert (!"Unknown unwind opcode.");
10849 while (node_count > 0) {
10850 g_assert (current_unwind_node < last_unwind_node);
10852 //Emit current node.
10853 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
10855 node_count--;
10856 current_unwind_node++;
10861 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
10862 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
10863 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
10864 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
10865 static void
10866 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
10868 char *pdata_section_label = NULL;
10870 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
10871 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
10872 temp_prefix_len = 0;
10875 // Format .pdata section label for function.
10876 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
10878 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
10879 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
10881 // Emit .pdata section.
10882 emit_section_change (acfg, ".pdata", 0);
10883 emit_alignment (acfg, sizeof (DWORD));
10884 emit_label (acfg, pdata_section_label);
10886 // Emit function start address RVA.
10887 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
10889 // Emit function end address RVA.
10890 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
10892 // Emit unwind info address RVA.
10893 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
10895 if (!cache_item->xdata_section_emitted) {
10896 // Emit .xdata section.
10897 emit_section_change (acfg, ".xdata", 0);
10898 emit_alignment (acfg, sizeof (DWORD));
10899 emit_label (acfg, cache_item->xdata_section_label);
10901 // Emit unwind info into .xdata section.
10902 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
10903 cache_item->xdata_section_emitted = TRUE;
10906 g_free (pdata_section_label);
10908 #endif
10910 static gboolean
10911 collect_methods (MonoAotCompile *acfg)
10913 int mindex, i;
10914 MonoImage *image = acfg->image;
10916 /* Collect methods */
10917 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10918 ERROR_DECL (error);
10919 MonoMethod *method;
10920 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10922 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
10924 if (!method) {
10925 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
10926 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10927 mono_error_cleanup (error);
10928 return FALSE;
10931 /* Load all methods eagerly to skip the slower lazy loading code */
10932 mono_class_setup_methods (method->klass);
10934 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10935 /* Compile the wrapper instead */
10936 /* We do this here instead of add_wrappers () because it is easy to do it here */
10937 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10938 method = wrapper;
10941 /* FIXME: Some mscorlib methods don't have debug info */
10943 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10944 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10945 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10946 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10947 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10948 if (!mono_debug_lookup_method (method)) {
10949 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10950 exit (1);
10956 if (method->is_generic || mono_class_is_gtd (method->klass))
10957 /* Compile the ref shared version instead */
10958 method = mini_get_shared_method (method);
10960 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10961 add_method_with_index (acfg, method, i, FALSE);
10962 acfg->method_index ++;
10965 /* gsharedvt methods */
10966 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10967 ERROR_DECL (error);
10968 MonoMethod *method;
10969 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10971 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10972 continue;
10974 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
10975 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
10977 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10978 MonoMethod *gshared;
10980 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10981 add_extra_method (acfg, gshared);
10985 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10986 add_generic_instances (acfg);
10988 if (mono_aot_mode_is_full (&acfg->aot_opts))
10989 add_wrappers (acfg);
10990 return TRUE;
10993 static void
10994 compile_methods (MonoAotCompile *acfg)
10996 int i, methods_len;
10998 if (acfg->aot_opts.nthreads > 0) {
10999 GPtrArray *frag;
11000 int len, j;
11001 GPtrArray *threads;
11002 MonoThreadHandle *thread_handle;
11003 gpointer *user_data;
11004 MonoMethod **methods;
11006 methods_len = acfg->methods->len;
11008 len = acfg->methods->len / acfg->aot_opts.nthreads;
11009 g_assert (len > 0);
11011 * Partition the list of methods into fragments, and hand it to threads to
11012 * process.
11014 threads = g_ptr_array_new ();
11015 /* Make a copy since acfg->methods is modified by compile_method () */
11016 methods = g_new0 (MonoMethod*, methods_len);
11017 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11018 for (i = 0; i < methods_len; ++i)
11019 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11020 i = 0;
11021 while (i < methods_len) {
11022 ERROR_DECL (error);
11023 MonoInternalThread *thread;
11025 frag = g_ptr_array_new ();
11026 for (j = 0; j < len; ++j) {
11027 if (i < methods_len) {
11028 g_ptr_array_add (frag, methods [i]);
11029 i ++;
11033 user_data = g_new0 (gpointer, 3);
11034 user_data [0] = acfg;
11035 user_data [1] = frag;
11037 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11038 mono_error_assert_ok (error);
11040 thread_handle = mono_threads_open_thread_handle (thread->handle);
11041 g_ptr_array_add (threads, thread_handle);
11043 g_free (methods);
11045 for (i = 0; i < threads->len; ++i) {
11046 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11047 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
11049 } else {
11050 methods_len = 0;
11053 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11054 for (i = methods_len; i < acfg->methods->len; ++i) {
11055 /* This can add new methods to acfg->methods */
11056 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11060 static int
11061 compile_asm (MonoAotCompile *acfg)
11063 char *command, *objfile;
11064 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11065 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11066 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11068 #ifdef TARGET_WIN32_MSVC
11069 #define AS_OPTIONS "-c -x assembler"
11070 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11071 #define AS_OPTIONS "--64"
11072 #elif defined(TARGET_POWERPC64)
11073 #define AS_OPTIONS "-a64 -mppc64"
11074 #elif defined(sparc) && SIZEOF_VOID_P == 8
11075 #define AS_OPTIONS "-xarch=v9"
11076 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11077 #define AS_OPTIONS "-arch i386"
11078 #else
11079 #define AS_OPTIONS ""
11080 #endif
11082 #if defined(TARGET_OSX)
11083 #define AS_NAME "clang"
11084 #elif defined(TARGET_WIN32_MSVC)
11085 #define AS_NAME "clang.exe"
11086 #else
11087 #define AS_NAME "as"
11088 #endif
11090 #ifdef TARGET_WIN32_MSVC
11091 #define AS_OBJECT_FILE_SUFFIX "obj"
11092 #else
11093 #define AS_OBJECT_FILE_SUFFIX "o"
11094 #endif
11096 #if defined(sparc)
11097 #define LD_NAME "ld"
11098 #define LD_OPTIONS "-shared -G"
11099 #elif defined(__ppc__) && defined(TARGET_MACH)
11100 #define LD_NAME "gcc"
11101 #define LD_OPTIONS "-dynamiclib"
11102 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11103 #define LD_NAME "clang"
11104 #define LD_OPTIONS "--shared"
11105 #elif defined(TARGET_WIN32_MSVC)
11106 #define LD_NAME "link.exe"
11107 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11108 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11109 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11110 #define LD_NAME "gcc"
11111 #define LD_OPTIONS "-shared"
11112 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11113 #define LD_NAME "clang"
11114 #define LD_OPTIONS "-m32 -dynamiclib"
11115 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11116 #define LD_NAME "gcc"
11117 #define LD_OPTIONS "--shared"
11118 #elif defined(TARGET_POWERPC64)
11119 #define LD_OPTIONS "-m elf64ppc"
11120 #endif
11122 #ifndef LD_OPTIONS
11123 #define LD_OPTIONS ""
11124 #endif
11126 if (acfg->aot_opts.asm_only) {
11127 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11128 if (acfg->aot_opts.static_link)
11129 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11130 if (acfg->llvm)
11131 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11132 return 0;
11135 if (acfg->aot_opts.static_link) {
11136 if (acfg->aot_opts.outfile)
11137 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11138 else
11139 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11140 } else {
11141 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11144 #ifdef TARGET_OSX
11145 g_string_append (acfg->as_args, "-c -x assembler");
11146 #endif
11148 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11149 acfg->as_args ? acfg->as_args->str : "",
11150 wrap_path (objfile), wrap_path (acfg->tmpfname));
11151 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11152 if (execute_system (command) != 0) {
11153 g_free (command);
11154 g_free (objfile);
11155 return 1;
11158 if (acfg->llvm && !acfg->llvm_owriter) {
11159 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11160 acfg->as_args ? acfg->as_args->str : "",
11161 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11162 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11163 if (execute_system (command) != 0) {
11164 g_free (command);
11165 g_free (objfile);
11166 return 1;
11170 g_free (command);
11172 if (acfg->aot_opts.static_link) {
11173 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11174 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11175 g_free (objfile);
11176 return 0;
11179 if (acfg->aot_opts.outfile)
11180 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11181 else
11182 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11184 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11186 if (acfg->llvm) {
11187 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11188 } else {
11189 llvm_ofile = g_strdup ("");
11192 /* replace the ; flags separators with spaces */
11193 g_strdelimit (ld_flags, ";", ' ');
11195 if (acfg->aot_opts.llvm_only)
11196 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11198 #ifdef TARGET_WIN32_MSVC
11199 g_assert (tmp_outfile_name != NULL);
11200 g_assert (objfile != NULL);
11201 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME,
11202 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, tmp_outfile_name, objfile);
11203 #elif defined(LD_NAME)
11204 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11205 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11206 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11207 #else
11208 // Default (linux)
11209 if (acfg->aot_opts.tool_prefix) {
11210 /* Cross compiling */
11211 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
11212 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11213 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11214 } else {
11215 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
11216 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11217 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11219 if (acfg->aot_opts.llvm_only) {
11220 command = g_strdup_printf ("clang++ %s", args);
11221 } else {
11222 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
11224 g_free (args);
11226 #endif
11227 aot_printf (acfg, "Executing the native linker: %s\n", command);
11228 if (execute_system (command) != 0) {
11229 g_free (tmp_outfile_name);
11230 g_free (outfile_name);
11231 g_free (command);
11232 g_free (objfile);
11233 g_free (ld_flags);
11234 return 1;
11237 g_free (command);
11239 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
11240 printf ("Stripping the binary: %s\n", com);
11241 execute_system (com);
11242 g_free (com);*/
11244 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
11246 * gas generates 'mapping symbols' each time code and data is mixed, which
11247 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
11249 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
11250 aot_printf (acfg, "Stripping the binary: %s\n", command);
11251 if (execute_system (command) != 0) {
11252 g_free (tmp_outfile_name);
11253 g_free (outfile_name);
11254 g_free (command);
11255 g_free (objfile);
11256 return 1;
11258 #endif
11260 if (0 != rename (tmp_outfile_name, outfile_name)) {
11261 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
11262 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
11263 unlink (outfile_name);
11264 rename (tmp_outfile_name, outfile_name);
11268 #if defined(TARGET_MACH)
11269 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
11270 aot_printf (acfg, "Executing dsymutil: %s\n", command);
11271 if (execute_system (command) != 0) {
11272 return 1;
11274 #endif
11276 if (!acfg->aot_opts.save_temps)
11277 unlink (objfile);
11279 g_free (tmp_outfile_name);
11280 g_free (outfile_name);
11281 g_free (objfile);
11283 if (acfg->aot_opts.save_temps)
11284 aot_printf (acfg, "Retained input file.\n");
11285 else
11286 unlink (acfg->tmpfname);
11288 return 0;
11291 static guint8
11292 profread_byte (FILE *infile)
11294 guint8 i;
11295 int res;
11297 res = fread (&i, 1, 1, infile);
11298 g_assert (res == 1);
11299 return i;
11302 static int
11303 profread_int (FILE *infile)
11305 int i, res;
11307 res = fread (&i, 4, 1, infile);
11308 g_assert (res == 1);
11309 return i;
11312 static char*
11313 profread_string (FILE *infile)
11315 int len, res;
11316 char *pbuf;
11318 len = profread_int (infile);
11319 pbuf = (char*)g_malloc (len + 1);
11320 res = fread (pbuf, 1, len, infile);
11321 g_assert (res == len);
11322 pbuf [len] = '\0';
11323 return pbuf;
11326 static void
11327 load_profile_file (MonoAotCompile *acfg, char *filename)
11329 FILE *infile;
11330 char buf [1024];
11331 int res, len, version;
11332 char magic [32];
11334 infile = fopen (filename, "r");
11335 if (!infile) {
11336 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
11337 exit (1);
11340 printf ("Using profile data file '%s'\n", filename);
11342 sprintf (magic, AOT_PROFILER_MAGIC);
11343 len = strlen (magic);
11344 res = fread (buf, 1, len, infile);
11345 magic [len] = '\0';
11346 buf [len] = '\0';
11347 if ((res != len) || strcmp (buf, magic) != 0) {
11348 printf ("Profile file has wrong header: '%s'.\n", buf);
11349 fclose (infile);
11350 exit (1);
11352 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
11353 version = profread_int (infile);
11354 if (version != expected_version) {
11355 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
11356 fclose (infile);
11357 exit (1);
11360 ProfileData *data = g_new0 (ProfileData, 1);
11361 data->images = g_hash_table_new (NULL, NULL);
11362 data->classes = g_hash_table_new (NULL, NULL);
11363 data->ginsts = g_hash_table_new (NULL, NULL);
11364 data->methods = g_hash_table_new (NULL, NULL);
11366 while (TRUE) {
11367 int type = profread_byte (infile);
11368 int id = profread_int (infile);
11370 if (type == AOTPROF_RECORD_NONE)
11371 break;
11373 switch (type) {
11374 case AOTPROF_RECORD_IMAGE: {
11375 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
11376 idata->name = profread_string (infile);
11377 char *mvid = profread_string (infile);
11378 g_free (mvid);
11379 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
11380 break;
11382 case AOTPROF_RECORD_GINST: {
11383 int i;
11384 int len = profread_int (infile);
11386 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
11387 gdata->argc = len;
11388 gdata->argv = g_new0 (ClassProfileData*, len);
11390 for (i = 0; i < len; ++i) {
11391 int class_id = profread_int (infile);
11393 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11394 g_assert (gdata->argv [i]);
11396 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
11397 break;
11399 case AOTPROF_RECORD_TYPE: {
11400 int type = profread_byte (infile);
11402 switch (type) {
11403 case MONO_TYPE_CLASS: {
11404 int image_id = profread_int (infile);
11405 int ginst_id = profread_int (infile);
11406 char *class_name = profread_string (infile);
11408 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
11409 g_assert (image);
11411 char *p = strrchr (class_name, '.');
11412 g_assert (p);
11413 *p = '\0';
11415 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
11416 cdata->image = image;
11417 cdata->ns = g_strdup (class_name);
11418 cdata->name = g_strdup (p + 1);
11420 if (ginst_id != -1) {
11421 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11422 g_assert (cdata->inst);
11424 g_free (class_name);
11426 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
11427 break;
11429 #if 0
11430 case MONO_TYPE_SZARRAY: {
11431 int elem_id = profread_int (infile);
11432 // FIXME:
11433 break;
11435 #endif
11436 default:
11437 g_assert_not_reached ();
11438 break;
11440 break;
11442 case AOTPROF_RECORD_METHOD: {
11443 int class_id = profread_int (infile);
11444 int ginst_id = profread_int (infile);
11445 int param_count = profread_int (infile);
11446 char *method_name = profread_string (infile);
11447 char *sig = profread_string (infile);
11449 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11450 g_assert (klass);
11452 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
11453 mdata->id = id;
11454 mdata->klass = klass;
11455 mdata->name = method_name;
11456 mdata->signature = sig;
11457 mdata->param_count = param_count;
11459 if (ginst_id != -1) {
11460 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11461 g_assert (mdata->inst);
11463 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
11464 break;
11466 default:
11467 printf ("%d\n", type);
11468 g_assert_not_reached ();
11469 break;
11473 fclose (infile);
11474 acfg->profile_data = g_list_append (acfg->profile_data, data);
11477 static void
11478 resolve_class (ClassProfileData *cdata);
11480 static void
11481 resolve_ginst (GInstProfileData *inst_data)
11483 int i;
11485 if (inst_data->inst)
11486 return;
11488 for (i = 0; i < inst_data->argc; ++i) {
11489 resolve_class (inst_data->argv [i]);
11490 if (!inst_data->argv [i]->klass)
11491 return;
11493 MonoType **args = g_new0 (MonoType*, inst_data->argc);
11494 for (i = 0; i < inst_data->argc; ++i)
11495 args [i] = &inst_data->argv [i]->klass->byval_arg;
11497 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
11500 static void
11501 resolve_class (ClassProfileData *cdata)
11503 ERROR_DECL (error);
11504 MonoClass *klass;
11506 if (!cdata->image->image)
11507 return;
11509 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
11510 if (!klass) {
11511 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
11512 return;
11514 if (cdata->inst) {
11515 resolve_ginst (cdata->inst);
11516 if (!cdata->inst->inst)
11517 return;
11518 MonoGenericContext ctx;
11520 memset (&ctx, 0, sizeof (ctx));
11521 ctx.class_inst = cdata->inst->inst;
11522 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
11523 } else {
11524 cdata->klass = klass;
11529 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
11531 static void
11532 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
11534 GHashTableIter iter;
11535 gpointer key, value;
11536 int i;
11538 if (!data)
11539 return;
11541 /* Images */
11542 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
11543 g_hash_table_iter_init (&iter, data->images);
11544 while (g_hash_table_iter_next (&iter, &key, &value)) {
11545 ImageProfileData *idata = (ImageProfileData*)value;
11547 for (i = 0; i < assemblies->len; ++i) {
11548 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
11550 if (!strcmp (ass->aname.name, idata->name)) {
11551 idata->image = ass->image;
11552 break;
11556 g_ptr_array_free (assemblies, TRUE);
11558 /* Classes */
11559 g_hash_table_iter_init (&iter, data->classes);
11560 while (g_hash_table_iter_next (&iter, &key, &value)) {
11561 ClassProfileData *cdata = (ClassProfileData*)value;
11563 if (!cdata->image->image) {
11564 if (acfg->aot_opts.verbose)
11565 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
11566 continue;
11569 resolve_class (cdata);
11571 if (cdata->klass)
11572 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
11576 /* Methods */
11577 g_hash_table_iter_init (&iter, data->methods);
11578 while (g_hash_table_iter_next (&iter, &key, &value)) {
11579 MethodProfileData *mdata = (MethodProfileData*)value;
11580 MonoClass *klass;
11581 MonoMethod *m;
11582 gpointer miter;
11584 resolve_class (mdata->klass);
11585 klass = mdata->klass->klass;
11586 if (!klass) {
11587 if (acfg->aot_opts.verbose)
11588 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
11589 continue;
11591 miter = NULL;
11592 while ((m = mono_class_get_methods (klass, &miter))) {
11593 ERROR_DECL (error);
11595 if (strcmp (m->name, mdata->name))
11596 continue;
11597 MonoMethodSignature *sig = mono_method_signature (m);
11598 if (!sig)
11599 continue;
11600 if (sig->param_count != mdata->param_count)
11601 continue;
11602 if (mdata->inst) {
11603 resolve_ginst (mdata->inst);
11604 if (!mdata->inst->inst)
11605 continue;
11606 MonoGenericContext ctx;
11608 memset (&ctx, 0, sizeof (ctx));
11609 ctx.method_inst = mdata->inst->inst;
11611 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
11612 if (!m)
11613 continue;
11614 sig = mono_method_signature_checked (m, error);
11615 if (!is_ok (error)) {
11616 mono_error_cleanup (error);
11617 continue;
11620 char *sig_str = mono_signature_full_name (sig);
11621 gboolean match = !strcmp (sig_str, mdata->signature);
11622 g_free (sig_str);
11623 if (!match)
11625 continue;
11626 //printf ("%s\n", mono_method_full_name (m, 1));
11627 mdata->method = m;
11628 break;
11630 if (!mdata->method) {
11631 if (acfg->aot_opts.verbose)
11632 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
11637 static gboolean
11638 inst_references_image (MonoGenericInst *inst, MonoImage *image)
11640 int i;
11642 for (i = 0; i < inst->type_argc; ++i) {
11643 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
11644 if (k->image == image)
11645 return TRUE;
11646 if (mono_class_is_ginst (k)) {
11647 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
11648 if (inst_references_image (kinst, image))
11649 return TRUE;
11652 return FALSE;
11655 static gboolean
11656 is_local_inst (MonoGenericInst *inst, MonoImage *image)
11658 int i;
11660 for (i = 0; i < inst->type_argc; ++i) {
11661 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
11662 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
11663 return FALSE;
11665 return TRUE;
11668 static void
11669 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
11671 GHashTableIter iter;
11672 gpointer key, value;
11673 int count = 0;
11675 if (!data)
11676 return;
11678 if (acfg->aot_opts.profile_only) {
11679 /* Add methods referenced by the profile */
11680 g_hash_table_iter_init (&iter, data->methods);
11681 while (g_hash_table_iter_next (&iter, &key, &value)) {
11682 MethodProfileData *mdata = (MethodProfileData*)value;
11683 MonoMethod *m = mdata->method;
11685 if (!m)
11686 continue;
11687 if (m->is_inflated)
11688 continue;
11689 add_extra_method (acfg, m);
11690 g_hash_table_insert (acfg->profile_methods, m, m);
11691 count ++;
11696 * Add method instances 'related' to this assembly to the AOT image.
11698 g_hash_table_iter_init (&iter, data->methods);
11699 while (g_hash_table_iter_next (&iter, &key, &value)) {
11700 MethodProfileData *mdata = (MethodProfileData*)value;
11701 MonoMethod *m = mdata->method;
11702 MonoGenericContext *ctx;
11704 if (!m)
11705 continue;
11706 if (!m->is_inflated)
11707 continue;
11709 ctx = mono_method_get_context (m);
11710 /* For simplicity, add instances which reference the assembly we are compiling */
11711 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
11712 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
11713 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11714 //printf ("%s\n", mono_method_full_name (m, TRUE));
11715 add_extra_method (acfg, m);
11716 count ++;
11717 } else if (m->klass->image == acfg->image &&
11718 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11719 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11720 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11721 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11722 //printf ("%s\n", mono_method_full_name (m, TRUE));
11723 add_extra_method (acfg, m);
11724 count ++;
11727 * FIXME: We might skip some instances, for example:
11728 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11729 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11733 printf ("Added %d methods from profile.\n", count);
11736 static void
11737 init_got_info (GotInfo *info)
11739 int i;
11741 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11742 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11743 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11744 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11745 info->got_patches = g_ptr_array_new ();
11748 static MonoAotCompile*
11749 acfg_create (MonoAssembly *ass, guint32 opts)
11751 MonoImage *image = ass->image;
11752 MonoAotCompile *acfg;
11754 acfg = g_new0 (MonoAotCompile, 1);
11755 acfg->methods = g_ptr_array_new ();
11756 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11757 acfg->method_depth = g_hash_table_new (NULL, NULL);
11758 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11759 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11760 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11761 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11762 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11763 acfg->image_hash = g_hash_table_new (NULL, NULL);
11764 acfg->image_table = g_ptr_array_new ();
11765 acfg->globals = g_ptr_array_new ();
11766 acfg->image = image;
11767 acfg->opts = opts;
11768 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11769 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11770 acfg->mempool = mono_mempool_new ();
11771 acfg->extra_methods = g_ptr_array_new ();
11772 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11773 acfg->unwind_ops = g_ptr_array_new ();
11774 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11775 acfg->method_order = g_ptr_array_new ();
11776 acfg->export_names = g_hash_table_new (NULL, NULL);
11777 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11778 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11779 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11780 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11781 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11782 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11783 mono_os_mutex_init_recursive (&acfg->mutex);
11785 init_got_info (&acfg->got_info);
11786 init_got_info (&acfg->llvm_got_info);
11788 return acfg;
11791 static void
11792 got_info_free (GotInfo *info)
11794 int i;
11796 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11797 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11798 g_free (info->patch_to_got_offset_by_type);
11799 g_hash_table_destroy (info->patch_to_got_offset);
11800 g_ptr_array_free (info->got_patches, TRUE);
11803 static void
11804 acfg_free (MonoAotCompile *acfg)
11806 int i;
11808 mono_img_writer_destroy (acfg->w);
11809 for (i = 0; i < acfg->nmethods; ++i)
11810 if (acfg->cfgs [i])
11811 mono_destroy_compile (acfg->cfgs [i]);
11813 g_free (acfg->cfgs);
11815 g_free (acfg->static_linking_symbol);
11816 g_free (acfg->got_symbol);
11817 g_free (acfg->plt_symbol);
11818 g_ptr_array_free (acfg->methods, TRUE);
11819 g_ptr_array_free (acfg->image_table, TRUE);
11820 g_ptr_array_free (acfg->globals, TRUE);
11821 g_ptr_array_free (acfg->unwind_ops, TRUE);
11822 g_hash_table_destroy (acfg->method_indexes);
11823 g_hash_table_destroy (acfg->method_depth);
11824 g_hash_table_destroy (acfg->plt_offset_to_entry);
11825 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11826 if (acfg->patch_to_plt_entry [i])
11827 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11829 g_free (acfg->patch_to_plt_entry);
11830 g_hash_table_destroy (acfg->method_to_cfg);
11831 g_hash_table_destroy (acfg->token_info_hash);
11832 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11833 g_hash_table_destroy (acfg->image_hash);
11834 g_hash_table_destroy (acfg->unwind_info_offsets);
11835 g_hash_table_destroy (acfg->method_label_hash);
11836 if (acfg->typespec_classes)
11837 g_hash_table_destroy (acfg->typespec_classes);
11838 g_hash_table_destroy (acfg->export_names);
11839 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11840 g_hash_table_destroy (acfg->klass_blob_hash);
11841 g_hash_table_destroy (acfg->method_blob_hash);
11842 got_info_free (&acfg->got_info);
11843 got_info_free (&acfg->llvm_got_info);
11844 arch_free_unwind_info_section_cache (acfg);
11845 mono_mempool_destroy (acfg->mempool);
11846 g_free (acfg);
11849 #define WRAPPER(e,n) n,
11850 static const char* const
11851 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11852 #include "mono/metadata/wrapper-types.h"
11853 NULL
11856 static G_GNUC_UNUSED const char*
11857 get_wrapper_type_name (int type)
11859 return wrapper_type_names [type];
11862 //#define DUMP_PLT
11863 //#define DUMP_GOT
11865 static void aot_dump (MonoAotCompile *acfg)
11867 FILE *dumpfile;
11868 char * dumpname;
11870 JsonWriter writer;
11871 mono_json_writer_init (&writer);
11873 mono_json_writer_object_begin(&writer);
11875 // Methods
11876 mono_json_writer_indent (&writer);
11877 mono_json_writer_object_key(&writer, "methods");
11878 mono_json_writer_array_begin (&writer);
11880 int i;
11881 for (i = 0; i < acfg->nmethods; ++i) {
11882 MonoCompile *cfg;
11883 MonoMethod *method;
11884 MonoClass *klass;
11886 cfg = acfg->cfgs [i];
11887 if (ignore_cfg (cfg))
11888 continue;
11890 method = cfg->orig_method;
11892 mono_json_writer_indent (&writer);
11893 mono_json_writer_object_begin(&writer);
11895 mono_json_writer_indent (&writer);
11896 mono_json_writer_object_key(&writer, "name");
11897 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11899 mono_json_writer_indent (&writer);
11900 mono_json_writer_object_key(&writer, "signature");
11901 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11903 mono_json_writer_indent (&writer);
11904 mono_json_writer_object_key(&writer, "code_size");
11905 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11907 klass = method->klass;
11909 mono_json_writer_indent (&writer);
11910 mono_json_writer_object_key(&writer, "class");
11911 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11913 mono_json_writer_indent (&writer);
11914 mono_json_writer_object_key(&writer, "namespace");
11915 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11917 mono_json_writer_indent (&writer);
11918 mono_json_writer_object_key(&writer, "wrapper_type");
11919 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11921 mono_json_writer_indent_pop (&writer);
11922 mono_json_writer_indent (&writer);
11923 mono_json_writer_object_end (&writer);
11924 mono_json_writer_printf (&writer, ",\n");
11927 mono_json_writer_indent_pop (&writer);
11928 mono_json_writer_indent (&writer);
11929 mono_json_writer_array_end (&writer);
11930 mono_json_writer_printf (&writer, ",\n");
11932 // PLT entries
11933 #ifdef DUMP_PLT
11934 mono_json_writer_indent_push (&writer);
11935 mono_json_writer_indent (&writer);
11936 mono_json_writer_object_key(&writer, "plt");
11937 mono_json_writer_array_begin (&writer);
11939 for (i = 0; i < acfg->plt_offset; ++i) {
11940 MonoPltEntry *plt_entry = NULL;
11941 MonoJumpInfo *ji;
11943 if (i == 0)
11945 * The first plt entry is unused.
11947 continue;
11949 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11950 ji = plt_entry->ji;
11952 mono_json_writer_indent (&writer);
11953 mono_json_writer_printf (&writer, "{ ");
11954 mono_json_writer_object_key(&writer, "symbol");
11955 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11958 mono_json_writer_indent_pop (&writer);
11959 mono_json_writer_indent (&writer);
11960 mono_json_writer_array_end (&writer);
11961 mono_json_writer_printf (&writer, ",\n");
11962 #endif
11964 // GOT entries
11965 #ifdef DUMP_GOT
11966 mono_json_writer_indent_push (&writer);
11967 mono_json_writer_indent (&writer);
11968 mono_json_writer_object_key(&writer, "got");
11969 mono_json_writer_array_begin (&writer);
11971 mono_json_writer_indent_push (&writer);
11972 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11973 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11975 mono_json_writer_indent (&writer);
11976 mono_json_writer_printf (&writer, "{ ");
11977 mono_json_writer_object_key(&writer, "patch_name");
11978 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11981 mono_json_writer_indent_pop (&writer);
11982 mono_json_writer_indent (&writer);
11983 mono_json_writer_array_end (&writer);
11984 mono_json_writer_printf (&writer, ",\n");
11985 #endif
11987 mono_json_writer_indent_pop (&writer);
11988 mono_json_writer_indent (&writer);
11989 mono_json_writer_object_end (&writer);
11991 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11992 dumpfile = fopen (dumpname, "w+");
11993 g_free (dumpname);
11995 fprintf (dumpfile, "%s", writer.text->str);
11996 fclose (dumpfile);
11998 mono_json_writer_destroy (&writer);
12001 static const char *preinited_jit_icalls[] = {
12002 "mono_aot_init_llvm_method",
12003 "mono_aot_init_gshared_method_this",
12004 "mono_aot_init_gshared_method_mrgctx",
12005 "mono_aot_init_gshared_method_vtable",
12006 "mono_llvm_throw_corlib_exception",
12007 "mono_init_vtable_slot",
12008 "mono_helper_ldstr_mscorlib"
12011 static void
12012 add_preinit_got_slots (MonoAotCompile *acfg)
12014 MonoJumpInfo *ji;
12015 int i;
12018 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12019 * during method initialization etc.
12022 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12023 ji->type = MONO_PATCH_INFO_IMAGE;
12024 ji->data.image = acfg->image;
12025 get_got_offset (acfg, FALSE, ji);
12026 get_got_offset (acfg, TRUE, ji);
12028 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12029 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12030 get_got_offset (acfg, FALSE, ji);
12031 get_got_offset (acfg, TRUE, ji);
12033 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12034 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12035 get_got_offset (acfg, FALSE, ji);
12036 get_got_offset (acfg, TRUE, ji);
12038 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12039 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12040 get_got_offset (acfg, FALSE, ji);
12041 get_got_offset (acfg, TRUE, ji);
12043 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12044 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12045 get_got_offset (acfg, FALSE, ji);
12046 get_got_offset (acfg, TRUE, ji);
12048 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12049 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12050 get_got_offset (acfg, FALSE, ji);
12051 get_got_offset (acfg, TRUE, ji);
12053 for (i = 0; i < TLS_KEY_NUM; i++) {
12054 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12055 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12056 ji->data.index = i;
12057 get_got_offset (acfg, FALSE, ji);
12058 get_got_offset (acfg, TRUE, ji);
12060 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12061 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12062 ji->data.index = i;
12063 get_got_offset (acfg, FALSE, ji);
12064 get_got_offset (acfg, TRUE, ji);
12067 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12068 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
12069 get_got_offset (acfg, FALSE, ji);
12070 get_got_offset (acfg, TRUE, ji);
12072 /* Called by native-to-managed wrappers on possibly unattached threads */
12073 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12074 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12075 ji->data.name = "mono_threads_attach_coop";
12076 get_got_offset (acfg, FALSE, ji);
12077 get_got_offset (acfg, TRUE, ji);
12079 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
12080 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12081 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
12082 ji->data.name = preinited_jit_icalls [i];
12083 get_got_offset (acfg, FALSE, ji);
12084 get_got_offset (acfg, TRUE, ji);
12087 acfg->nshared_got_entries = acfg->got_offset;
12090 static void
12091 mono_dedup_log_stats (MonoAotCompile *acfg)
12093 GHashTableIter iter;
12094 g_assert (acfg->dedup_stats);
12096 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12097 // deduped modules
12098 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12099 MonoCompile *dcfg = NULL;
12100 MonoMethod *method = NULL;
12102 size_t wrappers_size_saved = 0;
12103 size_t inflated_size_saved = 0;
12104 size_t copied_singles = 0;
12106 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12107 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12108 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12110 if (count == 0)
12111 continue;
12113 if (acfg->dedup_emit_mode) {
12114 // Size *saved* is the size due to things not emitted.
12115 if (count < 2) {
12116 // Just moved, didn't save space / dedup
12117 copied_singles += dcfg->code_len;
12118 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12119 wrappers_size_saved += dcfg->code_len * (count - 1);
12120 } else {
12121 inflated_size_saved += dcfg->code_len * (count - 1);
12124 if (acfg->aot_opts.dedup) {
12125 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12126 wrappers_size_saved += dcfg->code_len * count;
12127 } else {
12128 inflated_size_saved += dcfg->code_len * count;
12133 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%zu bytes\n", wrappers_size_saved);
12134 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%zu bytes\n", inflated_size_saved);
12135 if (acfg->dedup_emit_mode)
12136 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%zu bytes\n", copied_singles);
12138 g_hash_table_destroy (acfg->dedup_stats);
12139 acfg->dedup_stats = NULL;
12142 // Flush the cache to tell future calls what to skip
12143 static void
12144 mono_flush_method_cache (MonoAotCompile *acfg)
12146 GHashTable *method_cache = acfg->dedup_cache;
12147 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12148 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12149 g_free (filename);
12150 return;
12153 acfg->dedup_cache = NULL;
12155 FILE *cache = fopen (filename, "w");
12157 if (!cache)
12158 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12160 GHashTableIter iter;
12161 gchar *name = NULL;
12162 g_hash_table_iter_init (&iter, method_cache);
12163 gboolean cont = TRUE;
12164 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12165 int res = fprintf (cache, "%s\n", name);
12166 cont = res >= 0;
12168 // FIXME: don't assert if error when flushing
12169 g_assert (cont);
12171 fclose (cache);
12172 g_free (filename);
12174 // The keys are all in the imageset, nothing to free
12175 // Values are just pointers to memory owned elsewhere, or sentinels
12176 g_hash_table_destroy (method_cache);
12179 // Read in what has been emitted by previous invocations,
12180 // what can be skipped
12181 static void
12182 mono_read_method_cache (MonoAotCompile *acfg)
12184 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12185 // Only do once, when dedup_cache is null
12186 if (acfg->dedup_cache)
12187 goto early_exit;
12189 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
12190 g_assert (acfg->dedup_stats);
12192 // only in skip mode
12193 if (!acfg->aot_opts.dedup)
12194 goto early_exit;
12196 g_assert (acfg->dedup_cache);
12198 FILE *cache = fopen (filename, "r");
12199 if (!cache)
12200 goto early_exit;
12202 // Since we do pointer comparisons, and it can't be allocated at
12203 // the address 0x1 due to alignment, we use this as a sentinel
12204 gpointer other_acfg_sentinel = GINT_TO_POINTER (0x1);
12206 if (fseek (cache, 0L, SEEK_END))
12207 goto cleanup;
12209 size_t fileLength = ftell (cache);
12210 g_assert (fileLength > 0);
12212 if (fseek (cache, 0L, SEEK_SET))
12213 goto cleanup;
12215 // Avoid thousands of new malloc entries
12216 // FIXME: allocate into imageset, so we don't need to free.
12217 // put the other mangled names there too.
12218 char *bulk = g_malloc0 (fileLength * sizeof (char));
12219 size_t offset = 0;
12221 while (fgets (&bulk [offset], fileLength - offset, cache)) {
12222 // strip newline
12223 char *line = &bulk [offset];
12224 size_t len = strlen (line);
12225 if (len == 0)
12226 break;
12228 if (len >= 0 && line [len] == '\n')
12229 line [len] = '\0';
12230 offset += strlen (line) + 1;
12231 g_assert (fileLength >= offset);
12233 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
12236 cleanup:
12237 fclose (cache);
12239 early_exit:
12240 g_free (filename);
12241 return;
12244 typedef struct {
12245 GHashTable *cache;
12246 GHashTable *stats;
12247 gboolean emit_inflated_methods;
12248 MonoAssembly *inflated_assembly;
12249 } MonoAotState;
12251 static MonoAotState *
12252 alloc_aot_state (void)
12254 MonoAotState *state = g_malloc (sizeof (MonoAotState));
12255 // FIXME: Should this own the memory?
12256 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
12257 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
12258 // Start in "collect mode"
12259 state->emit_inflated_methods = FALSE;
12260 state->inflated_assembly = NULL;
12261 return state;
12264 static void
12265 free_aot_state (MonoAotState *astate)
12267 g_hash_table_destroy (astate->cache);
12268 g_free (astate);
12271 static void
12272 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
12274 GHashTableIter iter;
12275 gchar *name = NULL;
12276 MonoMethod *method = NULL;
12278 acfg->dedup_emit_mode = TRUE;
12280 g_hash_table_iter_init (&iter, astate->cache);
12281 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
12282 add_method_full (acfg, method, TRUE, 0);
12284 return;
12287 static void
12288 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
12290 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
12291 return;
12293 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
12294 // Thread the state through when making the inflate pass
12295 *astate = *global_aot_state;
12298 if (!*astate) {
12299 *astate = alloc_aot_state ();
12300 *global_aot_state = *astate;
12303 acfg->dedup_cache = (*astate)->cache;
12304 acfg->dedup_stats = (*astate)->stats;
12306 // fills out acfg->dedup_cache
12307 if (acfg->aot_opts.dedup)
12308 mono_read_method_cache (acfg);
12310 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
12311 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
12312 gchar *asm_file = NULL;
12314 // Get the last part of the path, the filename
12315 for (int i=0; asm_path [i] != NULL; i++)
12316 asm_file = asm_path [i];
12318 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
12319 // Save
12320 *is_dedup_dummy = TRUE;
12321 (*astate)->inflated_assembly = ass;
12323 g_strfreev (asm_path);
12324 } else if ((*astate)->inflated_assembly) {
12325 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
12329 int
12330 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12332 // create assembly, loop and add extra_methods
12333 // in add_generic_instances , rip out what's in that for loop
12334 // and apply that to this aot_state inside of mono_compile_assembly
12335 MonoAotState *astate;
12336 astate = *(MonoAotState **)aot_state;
12337 g_assert (astate);
12339 // FIXME: allow suffixes?
12340 if (!astate->inflated_assembly) {
12341 char *inflate = strstr (aot_options, "dedup-inflate");
12342 if (!inflate)
12343 return 0;
12344 else
12345 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
12348 // Switch modes
12349 astate->emit_inflated_methods = TRUE;
12351 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
12353 *aot_state = NULL;
12354 free_aot_state (astate);
12356 return res;
12359 static const char* interp_in_static_sigs[] = {
12360 "bool ptr int32 ptr&",
12361 "bool ptr ptr&",
12362 "int32 int32 ptr&",
12363 "int32 int32 ptr ptr&",
12364 "int32 ptr int32 ptr",
12365 "int32 ptr int32 ptr&",
12366 "int32 ptr ptr&",
12367 "object object ptr ptr ptr",
12368 "ptr int32 ptr&",
12369 "ptr ptr int32 ptr ptr ptr&",
12370 "ptr ptr int32 ptr ptr&",
12371 "ptr ptr int32 ptr&",
12372 "ptr ptr ptr int32 ptr&",
12373 "ptr ptr ptr ptr& ptr&",
12374 "ptr ptr ptr ptr ptr&",
12375 "ptr ptr ptr ptr&",
12376 "ptr ptr ptr&",
12377 "ptr ptr uint32 ptr&",
12378 "ptr uint32 ptr&",
12379 "void object ptr ptr ptr",
12380 "void ptr ptr int32 ptr ptr& ptr ptr&",
12381 "void ptr ptr int32 ptr ptr&",
12382 "void ptr ptr ptr&",
12383 "void ptr ptr&",
12384 "void ptr",
12385 "void int32 ptr&",
12386 "void uint32 ptr&",
12390 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
12392 MonoImage *image = ass->image;
12393 int i, res;
12394 gint64 all_sizes;
12395 MonoAotCompile *acfg;
12396 char *outfile_name, *tmp_outfile_name, *p;
12397 char llvm_stats_msg [256];
12398 TV_DECLARE (atv);
12399 TV_DECLARE (btv);
12401 acfg = acfg_create (ass, opts);
12403 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
12404 acfg->aot_opts.write_symbols = TRUE;
12405 acfg->aot_opts.ntrampolines = 4096;
12406 acfg->aot_opts.nrgctx_trampolines = 4096;
12407 acfg->aot_opts.nimt_trampolines = 512;
12408 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
12409 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
12410 acfg->aot_opts.llvm_path = g_strdup ("");
12411 acfg->aot_opts.temp_path = g_strdup ("");
12412 #ifdef MONOTOUCH
12413 acfg->aot_opts.use_trampolines_page = TRUE;
12414 #endif
12416 mono_aot_parse_options (aot_options, &acfg->aot_opts);
12418 // start dedup
12419 MonoAotState *astate = NULL;
12420 gboolean is_dedup_dummy = FALSE;
12421 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
12423 // Process later
12424 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
12425 return 0;
12427 // end dedup
12429 if (acfg->aot_opts.logfile) {
12430 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
12433 if (acfg->aot_opts.data_outfile) {
12434 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
12435 if (!acfg->data_outfile) {
12436 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
12437 return 1;
12439 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
12442 //acfg->aot_opts.print_skipped_methods = TRUE;
12444 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
12445 if (acfg->opts & MONO_OPT_GSHAREDVT) {
12446 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
12447 return 1;
12449 if (acfg->aot_opts.llvm_only) {
12450 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
12451 return 1;
12453 #else
12454 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12455 acfg->opts |= MONO_OPT_GSHAREDVT;
12456 #endif
12458 #if !defined(ENABLE_LLVM)
12459 if (acfg->aot_opts.llvm_only) {
12460 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
12461 return 1;
12463 #endif
12465 if (acfg->opts & MONO_OPT_GSHAREDVT)
12466 mono_set_generic_sharing_vt_supported (TRUE);
12468 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
12470 generate_aotid ((guint8*) &acfg->image->aotid);
12472 char *aotid = mono_guid_to_string (acfg->image->aotid);
12473 aot_printf (acfg, "AOTID %s\n", aotid);
12474 g_free (aotid);
12476 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
12477 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12478 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
12479 return 1;
12481 #endif
12483 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
12484 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
12485 return 1;
12488 if (acfg->aot_opts.static_link)
12489 acfg->aot_opts.asm_writer = TRUE;
12491 if (acfg->aot_opts.soft_debug) {
12492 MonoDebugOptions *opt = mini_get_debug_options ();
12494 opt->mdb_optimizations = TRUE;
12495 opt->gen_sdb_seq_points = TRUE;
12497 if (!mono_debug_enabled ()) {
12498 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
12499 return 1;
12501 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
12504 if (mono_use_llvm || acfg->aot_opts.llvm) {
12505 acfg->llvm = TRUE;
12506 acfg->aot_opts.asm_writer = TRUE;
12507 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
12509 if (acfg->aot_opts.soft_debug) {
12510 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
12511 return 1;
12514 mini_llvm_init ();
12516 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
12517 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
12518 return 1;
12522 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12523 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
12524 acfg->is_full_aot = TRUE;
12527 if (mono_threads_are_safepoints_enabled ())
12528 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
12530 // The methods in dedup-emit amodules must be available on runtime startup
12531 // Note: Only one such amodule can have this attribute
12532 if (astate && astate->emit_inflated_methods)
12533 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
12536 if (acfg->aot_opts.instances_logfile_path) {
12537 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
12538 if (!acfg->instances_logfile) {
12539 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
12540 return 1;
12544 if (acfg->aot_opts.profile_files) {
12545 GList *l;
12547 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
12548 load_profile_file (acfg, (char*)l->data);
12552 if (!mono_aot_mode_is_interp (&acfg->aot_opts)) {
12553 int method_index;
12555 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
12556 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
12560 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
12561 #ifdef MONO_ARCH_GSHARED_SUPPORTED
12562 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
12563 #endif
12564 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
12565 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
12566 if (acfg->opts & MONO_OPT_GSHAREDVT)
12567 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
12568 #endif
12570 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
12572 arch_init (acfg);
12574 if (mono_use_llvm || acfg->aot_opts.llvm) {
12577 * Emit all LLVM code into a separate assembly/object file and link with it
12578 * normally.
12580 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
12581 acfg->llvm_owriter = TRUE;
12582 } else if (acfg->aot_opts.llvm_outfile) {
12583 int len = strlen (acfg->aot_opts.llvm_outfile);
12585 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
12586 acfg->llvm_owriter = TRUE;
12590 if (acfg->llvm && acfg->thumb_mixed)
12591 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
12592 if (acfg->aot_opts.llvm_only)
12593 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
12595 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
12596 /* Get rid of characters which cannot occur in symbols */
12597 for (p = acfg->assembly_name_sym; *p; ++p) {
12598 if (!(isalnum (*p) || *p == '_'))
12599 *p = '_';
12602 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
12603 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
12604 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
12605 if (acfg->llvm) {
12606 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
12607 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
12610 acfg->method_index = 1;
12612 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12613 mono_set_partial_sharing_supported (TRUE);
12615 if (!mono_aot_mode_is_interp (&acfg->aot_opts)) {
12616 res = collect_methods (acfg);
12618 if (!res)
12619 return 1;
12622 // If we're emitting all of the inflated methods into a dummy
12623 // Assembly, then after extra_methods is set up, we're done
12624 // in this function.
12625 if (astate && astate->emit_inflated_methods)
12626 mono_add_deferred_extra_methods (acfg, astate);
12629 GList *l;
12631 for (l = acfg->profile_data; l; l = l->next)
12632 resolve_profile_data (acfg, (ProfileData*)l->data);
12633 for (l = acfg->profile_data; l; l = l->next)
12634 add_profile_instances (acfg, (ProfileData*)l->data);
12637 acfg->cfgs_size = acfg->methods->len + 32;
12638 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
12640 /* PLT offset 0 is reserved for the PLT trampoline */
12641 acfg->plt_offset = 1;
12642 add_preinit_got_slots (acfg);
12644 #ifdef ENABLE_LLVM
12645 if (acfg->llvm) {
12646 llvm_acfg = acfg;
12647 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
12649 #endif
12651 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
12652 for (int i = 0; i < sizeof (interp_in_static_sigs) / sizeof (const char *); i++) {
12653 MonoMethodSignature *sig = mono_create_icall_signature (interp_in_static_sigs [i]);
12654 MonoMethod *wrapper = mini_get_interp_in_wrapper (sig);
12655 add_method (acfg, wrapper);
12659 TV_GETTIME (atv);
12661 compile_methods (acfg);
12663 TV_GETTIME (btv);
12665 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
12667 TV_GETTIME (atv);
12669 #ifdef ENABLE_LLVM
12670 if (acfg->llvm) {
12671 if (acfg->aot_opts.asm_only) {
12672 if (acfg->aot_opts.outfile) {
12673 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12674 acfg->tmpbasename = g_strdup (acfg->tmpfname);
12675 } else {
12676 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
12677 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12679 g_assert (acfg->aot_opts.llvm_outfile);
12680 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
12681 if (acfg->llvm_owriter)
12682 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
12683 else
12684 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
12685 } else {
12686 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
12687 g_strdup_printf ("%s", "temp") :
12688 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
12690 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12691 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
12692 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
12695 #endif
12697 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
12698 if (acfg->aot_opts.outfile)
12699 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
12700 else
12701 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
12702 acfg->fp = fopen (acfg->tmpfname, "w+");
12703 } else {
12704 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
12705 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
12706 acfg->fp = fdopen (i, "w+");
12707 } else {
12708 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
12709 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
12710 acfg->fp = fopen (acfg->tmpfname, "w+");
12713 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
12714 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
12715 return 1;
12717 if (acfg->fp)
12718 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
12720 tmp_outfile_name = NULL;
12721 outfile_name = NULL;
12723 /* Compute symbols for methods */
12724 for (i = 0; i < acfg->nmethods; ++i) {
12725 if (acfg->cfgs [i]) {
12726 MonoCompile *cfg = acfg->cfgs [i];
12727 int method_index = get_method_index (acfg, cfg->orig_method);
12729 if (COMPILE_LLVM (cfg))
12730 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
12731 else if (acfg->global_symbols || acfg->llvm)
12732 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
12733 else
12734 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
12735 cfg->asm_debug_symbol = cfg->asm_symbol;
12739 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
12741 * CLANG supports GAS .file/.loc directives, so emit line number information this way
12743 acfg->gas_line_numbers = TRUE;
12746 #ifdef EMIT_DWARF_INFO
12747 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
12748 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
12749 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
12750 return 1;
12752 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
12754 #endif /* EMIT_DWARF_INFO */
12756 if (acfg->w)
12757 mono_img_writer_emit_start (acfg->w);
12759 if (acfg->dwarf)
12760 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
12762 emit_code (acfg);
12763 if (acfg->aot_opts.dedup)
12764 mono_flush_method_cache (acfg);
12765 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
12766 mono_dedup_log_stats (acfg);
12768 emit_info (acfg);
12770 emit_extra_methods (acfg);
12772 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
12773 return 0;
12775 emit_trampolines (acfg);
12777 emit_class_name_table (acfg);
12779 emit_got_info (acfg, FALSE);
12780 if (acfg->llvm)
12781 emit_got_info (acfg, TRUE);
12783 emit_exception_info (acfg);
12785 emit_unwind_info (acfg);
12787 emit_class_info (acfg);
12789 emit_plt (acfg);
12791 emit_image_table (acfg);
12793 emit_weak_field_indexes (acfg);
12795 emit_got (acfg);
12799 * The managed allocators are GC specific, so can't use an AOT image created by one GC
12800 * in another.
12802 const char *gc_name = mono_gc_get_gc_name ();
12803 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
12806 emit_blob (acfg);
12808 emit_objc_selectors (acfg);
12810 emit_globals (acfg);
12812 emit_file_info (acfg);
12814 emit_library_info (acfg);
12816 if (acfg->dwarf) {
12817 emit_dwarf_info (acfg);
12818 mono_dwarf_writer_close (acfg->dwarf);
12819 } else {
12820 if (!acfg->aot_opts.nodebug)
12821 emit_codeview_info (acfg);
12824 emit_mem_end (acfg);
12826 if (acfg->need_pt_gnu_stack) {
12827 /* This is required so the .so doesn't have an executable stack */
12828 /* The bin writer already emits this */
12829 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
12832 if (acfg->aot_opts.data_outfile)
12833 fclose (acfg->data_outfile);
12835 #ifdef ENABLE_LLVM
12836 if (acfg->llvm) {
12837 gboolean res;
12839 res = emit_llvm_file (acfg);
12840 if (!res)
12841 return 1;
12843 #endif
12845 TV_GETTIME (btv);
12847 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
12849 if (acfg->llvm)
12850 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
12851 else
12852 strcpy (llvm_stats_msg, "");
12854 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
12856 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
12857 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
12858 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
12859 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
12860 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
12861 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
12862 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,
12863 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
12864 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
12865 (int)(acfg->got_offset * sizeof (gpointer)));
12866 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
12867 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
12868 llvm_stats_msg,
12869 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
12870 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
12871 if (acfg->stats.genericcount)
12872 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
12873 if (acfg->stats.abscount)
12874 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
12875 if (acfg->stats.lmfcount)
12876 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
12877 if (acfg->stats.ocount)
12878 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
12880 TV_GETTIME (atv);
12881 if (acfg->w) {
12882 res = mono_img_writer_emit_writeout (acfg->w);
12883 if (res != 0) {
12884 acfg_free (acfg);
12885 return res;
12887 res = compile_asm (acfg);
12888 if (res != 0) {
12889 acfg_free (acfg);
12890 return res;
12893 TV_GETTIME (btv);
12894 acfg->stats.link_time = TV_ELAPSED (atv, btv);
12896 if (acfg->aot_opts.stats) {
12897 int i;
12899 aot_printf (acfg, "GOT slot distribution:\n");
12900 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12901 if (acfg->stats.got_slot_types [i])
12902 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]);
12903 aot_printf (acfg, "\nMethod stats:\n");
12904 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
12905 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
12906 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
12907 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
12910 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);
12912 if (acfg->aot_opts.dump_json)
12913 aot_dump (acfg);
12915 acfg_free (acfg);
12917 return 0;
12920 #else
12922 /* AOT disabled */
12924 void*
12925 mono_aot_readonly_field_override (MonoClassField *field)
12927 return NULL;
12931 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
12933 return 0;
12936 gboolean
12937 mono_aot_is_shared_got_offset (int offset)
12939 return FALSE;
12943 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12945 g_assert_not_reached ();
12946 return 0;
12949 #endif