Reorganize the scan-minor-copy/scan.h header files a bit. Move the nursery copying...
[mono-project.git] / mono / mini / aot-compiler.c
blobdf4253f1f61e5f8c196be1508f7c59cee8d43cdd
1 /*
2 * aot-compiler.c: mono Ahead of Time compiler
4 * Author:
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
16 * relocations.
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
24 #include "config.h"
25 #include <sys/types.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_STDINT_H
30 #include <stdint.h>
31 #endif
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <string.h>
35 #ifndef HOST_WIN32
36 #include <sys/time.h>
37 #else
38 #include <winsock2.h>
39 #include <windows.h>
40 #endif
42 #include <errno.h>
43 #include <sys/stat.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
65 #include "mini.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68 #include "mini-gc.h"
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72 #if defined(__linux__) || defined(__native_client_codegen__)
73 #define RODATA_SECT ".rodata"
74 #else
75 #define RODATA_SECT ".text"
76 #endif
78 #define TV_DECLARE(name) gint64 name
79 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
80 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
82 #ifdef TARGET_WIN32
83 #define SHARED_EXT ".dll"
84 #elif defined(__ppc__) && defined(TARGET_MACH)
85 #define SHARED_EXT ".dylib"
86 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
87 #define SHARED_EXT ".dylib"
88 #else
89 #define SHARED_EXT ".so"
90 #endif
92 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
93 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
94 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
96 /* predefined values for static readonly fields without needed to run the .cctor */
97 typedef struct _ReadOnlyValue ReadOnlyValue;
98 struct _ReadOnlyValue {
99 ReadOnlyValue *next;
100 char *name;
101 int type; /* to be used later for typechecking to prevent user errors */
102 union {
103 guint8 i1;
104 guint16 i2;
105 guint32 i4;
106 guint64 i8;
107 gpointer ptr;
108 } value;
110 static ReadOnlyValue *readonly_values = NULL;
112 typedef struct MonoAotOptions {
113 char *outfile;
114 gboolean save_temps;
115 gboolean write_symbols;
116 gboolean metadata_only;
117 gboolean bind_to_runtime_version;
118 gboolean full_aot;
119 gboolean no_dlsym;
120 gboolean static_link;
121 gboolean asm_only;
122 gboolean asm_writer;
123 gboolean nodebug;
124 gboolean soft_debug;
125 gboolean log_generics;
126 gboolean direct_pinvoke;
127 gboolean direct_icalls;
128 int nthreads;
129 int ntrampolines;
130 int nrgctx_trampolines;
131 int nimt_trampolines;
132 gboolean print_skipped_methods;
133 gboolean stats;
134 char *tool_prefix;
135 gboolean autoreg;
136 char *mtriple;
137 char *llvm_path;
138 } MonoAotOptions;
140 typedef struct MonoAotStats {
141 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
142 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
143 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
144 int got_slots, offsets_size;
145 int got_slot_types [MONO_PATCH_INFO_NONE];
146 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
147 int jit_time, gen_time, link_time;
148 } MonoAotStats;
150 typedef struct MonoAotCompile {
151 MonoImage *image;
152 GPtrArray *methods;
153 GHashTable *method_indexes;
154 GHashTable *method_depth;
155 MonoCompile **cfgs;
156 int cfgs_size;
157 GHashTable *patch_to_plt_entry;
158 GHashTable *plt_offset_to_entry;
159 GHashTable *patch_to_got_offset;
160 GHashTable **patch_to_got_offset_by_type;
161 GPtrArray *got_patches;
162 GHashTable *image_hash;
163 GHashTable *method_to_cfg;
164 GHashTable *token_info_hash;
165 GHashTable *method_to_pinvoke_import;
166 GPtrArray *extra_methods;
167 GPtrArray *image_table;
168 GPtrArray *globals;
169 GPtrArray *method_order;
170 GHashTable *export_names;
171 /* Maps MonoClass* -> blob offset */
172 GHashTable *klass_blob_hash;
173 /* Maps MonoMethod* -> blob offset */
174 GHashTable *method_blob_hash;
175 guint32 *plt_got_info_offsets;
176 guint32 got_offset, plt_offset, plt_got_offset_base;
177 guint32 final_got_size;
178 /* Number of GOT entries reserved for trampolines */
179 guint32 num_trampoline_got_entries;
181 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
182 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
183 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
185 MonoAotOptions aot_opts;
186 guint32 nmethods;
187 guint32 opts;
188 guint32 simd_opts;
189 MonoMemPool *mempool;
190 MonoAotStats stats;
191 int method_index;
192 char *static_linking_symbol;
193 CRITICAL_SECTION mutex;
194 gboolean use_bin_writer;
195 MonoImageWriter *w;
196 MonoDwarfWriter *dwarf;
197 FILE *fp;
198 char *tmpfname;
199 GSList *cie_program;
200 GHashTable *unwind_info_offsets;
201 GPtrArray *unwind_ops;
202 guint32 unwind_info_offset;
203 char *got_symbol_base;
204 char *got_symbol;
205 char *plt_symbol;
206 GHashTable *method_label_hash;
207 const char *temp_prefix;
208 const char *llvm_label_prefix;
209 guint32 label_generator;
210 gboolean llvm;
211 MonoAotFileFlags flags;
212 MonoDynamicStream blob;
213 MonoClass **typespec_classes;
214 GString *llc_args;
215 GString *as_args;
216 char *assembly_name_sym;
217 GHashTable *plt_entry_debug_sym_cache;
218 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
219 GHashTable *ginst_hash;
220 } MonoAotCompile;
222 typedef struct {
223 int plt_offset;
224 char *symbol, *llvm_symbol, *debug_sym;
225 MonoJumpInfo *ji;
226 gboolean jit_used, llvm_used;
227 } MonoPltEntry;
229 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
230 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
232 /* This points to the current acfg in LLVM mode */
233 static MonoAotCompile *llvm_acfg;
235 #ifdef HAVE_ARRAY_ELEM_INIT
236 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
237 #define MSGSTRFIELD1(line) str##line
238 static const struct msgstr_t {
239 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
240 #include "patch-info.h"
241 #undef PATCH_INFO
242 } opstr = {
243 #define PATCH_INFO(a,b) b,
244 #include "patch-info.h"
245 #undef PATCH_INFO
247 static const gint16 opidx [] = {
248 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
249 #include "patch-info.h"
250 #undef PATCH_INFO
253 static G_GNUC_UNUSED const char*
254 get_patch_name (int info)
256 return (const char*)&opstr + opidx [info];
259 #else
260 #define PATCH_INFO(a,b) b,
261 static const char* const
262 patch_types [MONO_PATCH_INFO_NUM + 1] = {
263 #include "patch-info.h"
264 NULL
267 static G_GNUC_UNUSED const char*
268 get_patch_name (int info)
270 return patch_types [info];
273 #endif
275 static char*
276 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
278 /* Wrappers around the image writer functions */
280 static inline void
281 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
283 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
286 static inline void
287 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
289 img_writer_emit_push_section (acfg->w, section_name, subsection);
292 static inline void
293 emit_pop_section (MonoAotCompile *acfg)
295 img_writer_emit_pop_section (acfg->w);
298 static inline void
299 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
301 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
304 static inline void
305 emit_label (MonoAotCompile *acfg, const char *name)
307 img_writer_emit_label (acfg->w, name);
310 static inline void
311 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
313 img_writer_emit_bytes (acfg->w, buf, size);
316 static inline void
317 emit_string (MonoAotCompile *acfg, const char *value)
319 img_writer_emit_string (acfg->w, value);
322 static inline void
323 emit_line (MonoAotCompile *acfg)
325 img_writer_emit_line (acfg->w);
328 static inline void
329 emit_alignment (MonoAotCompile *acfg, int size)
331 img_writer_emit_alignment (acfg->w, size);
334 static inline void
335 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
337 img_writer_emit_pointer_unaligned (acfg->w, target);
340 static inline void
341 emit_pointer (MonoAotCompile *acfg, const char *target)
343 img_writer_emit_pointer (acfg->w, target);
346 static inline void
347 emit_int16 (MonoAotCompile *acfg, int value)
349 img_writer_emit_int16 (acfg->w, value);
352 static inline void
353 emit_int32 (MonoAotCompile *acfg, int value)
355 img_writer_emit_int32 (acfg->w, value);
358 static inline void
359 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
361 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
364 static inline void
365 emit_zero_bytes (MonoAotCompile *acfg, int num)
367 img_writer_emit_zero_bytes (acfg->w, num);
370 static inline void
371 emit_byte (MonoAotCompile *acfg, guint8 val)
373 img_writer_emit_byte (acfg->w, val);
376 #ifdef __native_client_codegen__
377 static inline void
378 emit_nacl_call_alignment (MonoAotCompile *acfg)
380 img_writer_emit_nacl_call_alignment (acfg->w);
382 #endif
384 static G_GNUC_UNUSED void
385 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
387 img_writer_emit_global (acfg->w, name, func);
390 static void
391 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
393 if (acfg->aot_opts.no_dlsym) {
394 g_ptr_array_add (acfg->globals, g_strdup (name));
395 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
396 } else {
397 img_writer_emit_global (acfg->w, name, func);
401 static void
402 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
404 img_writer_emit_symbol_size (acfg->w, name, end_label);
407 static void
408 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
410 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
411 #ifdef TARGET_MACH
412 /* On apple, all symbols need to be aligned to avoid warnings from ld */
413 emit_alignment (acfg, 4);
414 #endif
415 img_writer_emit_label (acfg->w, name);
416 img_writer_emit_string (acfg->w, value);
419 static G_GNUC_UNUSED void
420 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
422 do {
423 guint8 b = value & 0x7f;
424 value >>= 7;
425 if (value != 0) /* more bytes to come */
426 b |= 0x80;
427 emit_byte (acfg, b);
428 } while (value);
431 static G_GNUC_UNUSED void
432 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
434 gboolean more = 1;
435 gboolean negative = (value < 0);
436 guint32 size = 64;
437 guint8 byte;
439 while (more) {
440 byte = value & 0x7f;
441 value >>= 7;
442 /* the following is unnecessary if the
443 * implementation of >>= uses an arithmetic rather
444 * than logical shift for a signed left operand
446 if (negative)
447 /* sign extend */
448 value |= - ((gint64)1 <<(size - 7));
449 /* sign bit of byte is second high order bit (0x40) */
450 if ((value == 0 && !(byte & 0x40)) ||
451 (value == -1 && (byte & 0x40)))
452 more = 0;
453 else
454 byte |= 0x80;
455 emit_byte (acfg, byte);
459 static G_GNUC_UNUSED void
460 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
462 guint8 *p = buf;
464 do {
465 guint8 b = value & 0x7f;
466 value >>= 7;
467 if (value != 0) /* more bytes to come */
468 b |= 0x80;
469 *p ++ = b;
470 } while (value);
472 *endbuf = p;
475 static G_GNUC_UNUSED void
476 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
478 gboolean more = 1;
479 gboolean negative = (value < 0);
480 guint32 size = 32;
481 guint8 byte;
482 guint8 *p = buf;
484 while (more) {
485 byte = value & 0x7f;
486 value >>= 7;
487 /* the following is unnecessary if the
488 * implementation of >>= uses an arithmetic rather
489 * than logical shift for a signed left operand
491 if (negative)
492 /* sign extend */
493 value |= - (1 <<(size - 7));
494 /* sign bit of byte is second high order bit (0x40) */
495 if ((value == 0 && !(byte & 0x40)) ||
496 (value == -1 && (byte & 0x40)))
497 more = 0;
498 else
499 byte |= 0x80;
500 *p ++= byte;
503 *endbuf = p;
506 /* ARCHITECTURE SPECIFIC CODE */
508 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
509 #define EMIT_DWARF_INFO 1
510 #endif
512 #if defined(TARGET_ARM)
513 #define AOT_FUNC_ALIGNMENT 4
514 #else
515 #define AOT_FUNC_ALIGNMENT 16
516 #endif
517 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
518 #undef AOT_FUNC_ALIGNMENT
519 #define AOT_FUNC_ALIGNMENT 32
520 #endif
522 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
523 #define PPC_LD_OP "ld"
524 #define PPC_LDX_OP "ldx"
525 #else
526 #define PPC_LD_OP "lwz"
527 #define PPC_LDX_OP "lwzx"
528 #endif
530 #ifdef TARGET_AMD64
531 #define AOT_TARGET_STR "AMD64"
532 #endif
534 #ifdef TARGET_ARM
535 #ifdef TARGET_MACH
536 #define AOT_TARGET_STR "ARM (MACH)"
537 #else
538 #define AOT_TARGET_STR "ARM (!MACH)"
539 #endif
540 #endif
542 #ifdef TARGET_POWERPC64
543 #ifdef __mono_ilp32__
544 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
545 #else
546 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
547 #endif
548 #else
549 #ifdef TARGET_POWERPC
550 #ifdef __mono_ilp32__
551 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
552 #else
553 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
554 #endif
555 #endif
556 #endif
558 #ifdef TARGET_X86
559 #ifdef TARGET_WIN32
560 #define AOT_TARGET_STR "X86 (WIN32)"
561 #elif defined(__native_client_codegen__)
562 #define AOT_TARGET_STR "X86 (native client codegen)"
563 #else
564 #define AOT_TARGET_STR "X86 (!native client codegen)"
565 #endif
566 #endif
568 #ifndef AOT_TARGET_STR
569 #define AOT_TARGET_STR ""
570 #endif
572 static void
573 arch_init (MonoAotCompile *acfg)
575 acfg->llc_args = g_string_new ("");
576 acfg->as_args = g_string_new ("");
579 * The prefix LLVM likes to put in front of symbol names on darwin.
580 * The mach-os specs require this for globals, but LLVM puts them in front of all
581 * symbols. We need to handle this, since we need to refer to LLVM generated
582 * symbols.
584 acfg->llvm_label_prefix = "";
586 #ifdef TARGET_ARM
587 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
588 g_string_append (acfg->llc_args, "-mattr=+v6");
589 } else {
590 #ifdef ARM_FPU_VFP
591 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
592 g_string_append (acfg->as_args, " -mfpu=vfp3");
593 #else
594 g_string_append (acfg->llc_args, " -soft-float");
595 #endif
597 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
598 acfg->thumb_mixed = TRUE;
600 if (acfg->aot_opts.mtriple)
601 mono_arch_set_target (acfg->aot_opts.mtriple);
602 #endif
604 #ifdef TARGET_MACH
605 acfg->llvm_label_prefix = "_";
606 acfg->need_no_dead_strip = TRUE;
607 #endif
609 #if defined(__linux__) && !defined(TARGET_ARM)
610 acfg->need_pt_gnu_stack = TRUE;
611 #endif
615 * arch_emit_direct_call:
617 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
618 * calling code.
620 static void
621 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
623 #if defined(TARGET_X86) || defined(TARGET_AMD64)
624 /* Need to make sure this is exactly 5 bytes long */
625 if (FALSE && !acfg->use_bin_writer) {
626 img_writer_emit_unset_mode (acfg->w);
627 fprintf (acfg->fp, "call %s\n", target);
628 } else {
629 emit_byte (acfg, '\xe8');
630 emit_symbol_diff (acfg, target, ".", -4);
632 *call_size = 5;
633 #elif defined(TARGET_ARM)
634 if (acfg->use_bin_writer) {
635 guint8 buf [4];
636 guint8 *code;
638 code = buf;
639 ARM_BL (code, 0);
641 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
642 emit_bytes (acfg, buf, 4);
643 } else {
644 img_writer_emit_unset_mode (acfg->w);
645 fprintf (acfg->fp, "bl %s\n", target);
647 *call_size = 4;
648 #elif defined(TARGET_POWERPC)
649 if (acfg->use_bin_writer) {
650 g_assert_not_reached ();
651 } else {
652 img_writer_emit_unset_mode (acfg->w);
653 fprintf (acfg->fp, "bl %s\n", target);
654 *call_size = 4;
656 #else
657 g_assert_not_reached ();
658 #endif
662 * PPC32 design:
663 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
664 * the GOT pointer.
665 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
666 * in in the 2. slot of every GOT, and require every method to place the GOT
667 * address in r30, even when it doesn't access the GOT otherwise. This way,
668 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
672 * PPC64 design:
673 * PPC64 uses function descriptors which greatly complicate all code, since
674 * these are used very inconsistently in the runtime. Some functions like
675 * mono_compile_method () return ftn descriptors, while others like the
676 * trampoline creation functions do not.
677 * We assume that all GOT slots contain function descriptors, and create
678 * descriptors in aot-runtime.c when needed.
679 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
680 * from function descriptors, we could do the same, but it would require
681 * rewriting all the ppc/aot code to handle function descriptors properly.
682 * So instead, we use the same approach as on PPC32.
683 * This is a horrible mess, but fixing it would probably lead to an even bigger
684 * one.
688 * X86 design:
689 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
692 #ifdef MONO_ARCH_AOT_SUPPORTED
694 * arch_emit_got_offset:
696 * The memory pointed to by CODE should hold native code for computing the GOT
697 * address. Emit this code while patching it with the offset between code and
698 * the GOT. CODE_SIZE is set to the number of bytes emitted.
700 static void
701 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
703 #if defined(TARGET_POWERPC64)
704 g_assert (!acfg->use_bin_writer);
705 img_writer_emit_unset_mode (acfg->w);
707 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
708 * unsupported relocations. So we store the got address into the .Lgot_addr
709 * symbol which is in the text segment, compute its address, and load it.
711 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
712 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
713 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
714 fprintf (acfg->fp, "add 30, 30, 0\n");
715 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
716 acfg->label_generator ++;
717 *code_size = 16;
718 #elif defined(TARGET_POWERPC)
719 g_assert (!acfg->use_bin_writer);
720 img_writer_emit_unset_mode (acfg->w);
721 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
722 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
723 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
724 acfg->label_generator ++;
725 *code_size = 8;
726 #else
727 guint32 offset = mono_arch_get_patch_offset (code);
728 emit_bytes (acfg, code, offset);
729 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
731 *code_size = offset + 4;
732 #endif
736 * arch_emit_got_access:
738 * The memory pointed to by CODE should hold native code for loading a GOT
739 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
740 * CODE_SIZE is set to the number of bytes emitted.
742 static void
743 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
745 /* Emit beginning of instruction */
746 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
748 /* Emit the offset */
749 #ifdef TARGET_AMD64
750 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
751 *code_size = mono_arch_get_patch_offset (code) + 4;
752 #elif defined(TARGET_X86)
753 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
754 *code_size = mono_arch_get_patch_offset (code) + 4;
755 #elif defined(TARGET_ARM)
756 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
757 *code_size = mono_arch_get_patch_offset (code) + 4;
758 #elif defined(TARGET_POWERPC)
760 guint8 buf [32];
761 guint8 *code;
763 code = buf;
764 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
765 g_assert (code - buf == 8);
766 emit_bytes (acfg, buf, code - buf);
767 *code_size = code - buf;
769 #else
770 g_assert_not_reached ();
771 #endif
774 #endif
777 * arch_emit_plt_entry:
779 * Emit code for the PLT entry with index INDEX.
781 static void
782 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
784 #if defined(TARGET_X86)
785 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
786 #if defined(__default_codegen__)
787 /* jmp *<offset>(%ebx) */
788 emit_byte (acfg, 0xff);
789 emit_byte (acfg, 0xa3);
790 emit_int32 (acfg, offset);
791 /* Used by mono_aot_get_plt_info_offset */
792 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
793 #elif defined(__native_client_codegen__)
794 const guint8 kSizeOfNaClJmp = 11;
795 guint8 bytes[kSizeOfNaClJmp];
796 guint8 *pbytes = &bytes[0];
798 x86_jump_membase32 (pbytes, X86_EBX, offset);
799 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
800 /* four bytes of data, used by mono_arch_patch_plt_entry */
801 /* For Native Client, make this work with data embedded in push. */
802 emit_byte (acfg, 0x68); /* hide data in a push */
803 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
804 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
805 #endif /*__native_client_codegen__*/
806 #elif defined(TARGET_AMD64)
807 #if defined(__default_codegen__)
809 * We can't emit jumps because they are 32 bits only so they can't be patched.
810 * So we make indirect calls through GOT entries which are patched by the AOT
811 * loader to point to .Lpd entries.
813 /* jmpq *<offset>(%rip) */
814 emit_byte (acfg, '\xff');
815 emit_byte (acfg, '\x25');
816 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
817 /* Used by mono_aot_get_plt_info_offset */
818 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
819 #elif defined(__native_client_codegen__)
820 guint8 buf [256];
821 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
822 guint8 *code = buf_aligned;
824 /* mov <OFFSET>(%rip), %r11d */
825 emit_byte (acfg, '\x45');
826 emit_byte (acfg, '\x8b');
827 emit_byte (acfg, '\x1d');
828 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
830 amd64_jump_reg (code, AMD64_R11);
831 /* This should be constant for the plt patch */
832 g_assert ((size_t)(code-buf_aligned) == 10);
833 emit_bytes (acfg, buf_aligned, code - buf_aligned);
835 /* Hide data in a push imm32 so it passes validation */
836 emit_byte (acfg, 0x68); /* push */
837 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
838 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
839 #endif /*__native_client_codegen__*/
840 #elif defined(TARGET_ARM)
841 guint8 buf [256];
842 guint8 *code;
844 code = buf;
845 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
846 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
847 emit_bytes (acfg, buf, code - buf);
848 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
849 /* Used by mono_aot_get_plt_info_offset */
850 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
851 #elif defined(TARGET_POWERPC)
852 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
854 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
855 g_assert (!acfg->use_bin_writer);
856 img_writer_emit_unset_mode (acfg->w);
857 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
858 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
859 fprintf (acfg->fp, "add 11, 11, 30\n");
860 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
861 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
862 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
863 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
864 #endif
865 fprintf (acfg->fp, "mtctr 11\n");
866 fprintf (acfg->fp, "bctr\n");
867 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
868 #else
869 g_assert_not_reached ();
870 #endif
873 static void
874 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
876 #if defined(TARGET_ARM)
877 #if 0
878 /* LLVM calls the PLT entries using bl, so emit a stub */
879 /* FIXME: Too much overhead on every call */
880 fprintf (acfg->fp, ".thumb_func\n");
881 fprintf (acfg->fp, "bx pc\n");
882 fprintf (acfg->fp, "nop\n");
883 fprintf (acfg->fp, ".arm\n");
884 #endif
885 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
886 /* The caller already transitioned to thumb */
887 /* The code below should be 12 bytes long */
888 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
889 /* thumb can't encode ld pc, [pc, ip] */
890 fprintf (acfg->fp, "add ip, pc, ip\n");
891 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
892 fprintf (acfg->fp, "bx ip\n");
893 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
894 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
895 #else
896 g_assert_not_reached ();
897 #endif
901 * arch_emit_specific_trampoline:
903 * Emit code for a specific trampoline. OFFSET is the offset of the first of
904 * two GOT slots which contain the generic trampoline address and the trampoline
905 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
907 static void
908 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
911 * The trampolines created here are variations of the specific
912 * trampolines created in mono_arch_create_specific_trampoline (). The
913 * differences are:
914 * - the generic trampoline address is taken from a got slot.
915 * - the offset of the got slot where the trampoline argument is stored
916 * is embedded in the instruction stream, and the generic trampoline
917 * can load the argument by loading the offset, adding it to the
918 * address of the trampoline to get the address of the got slot, and
919 * loading the argument from there.
920 * - all the trampolines should be of the same length.
922 #if defined(TARGET_AMD64)
923 #if defined(__default_codegen__)
924 /* This should be exactly 16 bytes long */
925 *tramp_size = 16;
926 /* call *<offset>(%rip) */
927 emit_byte (acfg, '\x41');
928 emit_byte (acfg, '\xff');
929 emit_byte (acfg, '\x15');
930 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
931 /* This should be relative to the start of the trampoline */
932 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
933 emit_zero_bytes (acfg, 5);
934 #elif defined(__native_client_codegen__)
935 guint8 buf [256];
936 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
937 guint8 *code = buf_aligned;
938 guint8 *call_start;
939 size_t call_len;
940 int got_offset;
942 /* Emit this call in 'code' so we can find out how long it is. */
943 amd64_call_reg (code, AMD64_R11);
944 call_start = mono_arch_nacl_skip_nops (buf_aligned);
945 call_len = code - call_start;
947 /* The tramp_size is twice the NaCl alignment because it starts with */
948 /* a call which needs to be aligned to the end of the boundary. */
949 *tramp_size = kNaClAlignment*2;
951 /* Emit nops to align call site below which is 7 bytes plus */
952 /* the length of the call sequence emitted above. */
953 /* Note: this requires the specific trampoline starts on a */
954 /* kNaclAlignedment aligned address, which it does because */
955 /* it's its own function that is aligned. */
956 guint8 nop_buf[256];
957 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
958 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
959 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
961 /* The trampoline is stored at the offset'th pointer, the -4 is */
962 /* present because RIP relative addressing starts at the end of */
963 /* the current instruction, while the label "." is relative to */
964 /* the beginning of the current asm location, which in this case */
965 /* is not the mov instruction, but the offset itself, due to the */
966 /* way the bytes and ints are emitted here. */
967 got_offset = (offset * sizeof(gpointer)) - 4;
969 /* mov <OFFSET>(%rip), %r11d */
970 emit_byte (acfg, '\x45');
971 emit_byte (acfg, '\x8b');
972 emit_byte (acfg, '\x1d');
973 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
975 /* naclcall %r11 */
976 emit_bytes (acfg, call_start, call_len);
978 /* The arg is stored at the offset+1 pointer, relative to beginning */
979 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
980 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
982 /* We can't emit this data directly, hide in a "push imm32" */
983 emit_byte (acfg, '\x68'); /* push */
984 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
985 emit_alignment (acfg, kNaClAlignment);
986 #endif /*__native_client_codegen__*/
987 #elif defined(TARGET_ARM)
988 guint8 buf [128];
989 guint8 *code;
991 /* This should be exactly 20 bytes long */
992 *tramp_size = 20;
993 code = buf;
994 ARM_PUSH (code, 0x5fff);
995 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
996 /* Load the value from the GOT */
997 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
998 /* Branch to it */
999 ARM_BLX_REG (code, ARMREG_R1);
1001 g_assert (code - buf == 16);
1003 /* Emit it */
1004 emit_bytes (acfg, buf, code - buf);
1006 * Only one offset is needed, since the second one would be equal to the
1007 * first one.
1009 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1010 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1011 #elif defined(TARGET_POWERPC)
1012 guint8 buf [128];
1013 guint8 *code;
1015 *tramp_size = 4;
1016 code = buf;
1018 g_assert (!acfg->use_bin_writer);
1021 * PPC has no ip relative addressing, so we need to compute the address
1022 * of the mscorlib got. That is slow and complex, so instead, we store it
1023 * in the second got slot of every aot image. The caller already computed
1024 * the address of its got and placed it into r30.
1026 img_writer_emit_unset_mode (acfg->w);
1027 /* Load mscorlib got address */
1028 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1029 /* Load generic trampoline address */
1030 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1031 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1032 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1033 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1034 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1035 #endif
1036 fprintf (acfg->fp, "mtctr 11\n");
1037 /* Load trampoline argument */
1038 /* On ppc, we pass it normally to the generic trampoline */
1039 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1040 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1041 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1042 /* Branch to generic trampoline */
1043 fprintf (acfg->fp, "bctr\n");
1045 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1046 *tramp_size = 10 * 4;
1047 #else
1048 *tramp_size = 9 * 4;
1049 #endif
1050 #elif defined(TARGET_X86)
1051 guint8 buf [128];
1052 guint8 *code;
1054 /* Similar to the PPC code above */
1056 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1058 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1059 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1060 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1061 #endif
1063 code = buf;
1064 /* Load mscorlib got address */
1065 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1066 /* Push trampoline argument */
1067 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1068 /* Load generic trampoline address */
1069 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1070 /* Branch to generic trampoline */
1071 x86_jump_reg (code, X86_ECX);
1073 #ifdef __native_client_codegen__
1075 /* emit nops to next 32 byte alignment */
1076 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1077 while (code < (buf + a)) x86_nop(code);
1079 #endif
1080 emit_bytes (acfg, buf, code - buf);
1082 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1083 g_assert (code - buf == *tramp_size);
1084 #else
1085 g_assert_not_reached ();
1086 #endif
1090 * arch_emit_unbox_trampoline:
1092 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1093 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1095 static void
1096 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1098 #if defined(TARGET_AMD64)
1099 guint8 buf [32];
1100 guint8 *code;
1101 int this_reg;
1103 this_reg = mono_arch_get_this_arg_reg (NULL);
1104 code = buf;
1105 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1107 emit_bytes (acfg, buf, code - buf);
1108 /* jump <method> */
1109 emit_byte (acfg, '\xe9');
1110 emit_symbol_diff (acfg, call_target, ".", -4);
1111 #elif defined(TARGET_X86)
1112 guint8 buf [32];
1113 guint8 *code;
1114 int this_pos = 4;
1116 code = buf;
1118 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1120 emit_bytes (acfg, buf, code - buf);
1122 /* jump <method> */
1123 emit_byte (acfg, '\xe9');
1124 emit_symbol_diff (acfg, call_target, ".", -4);
1125 #elif defined(TARGET_ARM)
1126 guint8 buf [128];
1127 guint8 *code;
1129 if (acfg->thumb_mixed && cfg->compile_llvm) {
1130 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1131 fprintf (acfg->fp, "b %s\n", call_target);
1132 fprintf (acfg->fp, ".arm\n");
1133 return;
1136 code = buf;
1138 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1140 emit_bytes (acfg, buf, code - buf);
1141 /* jump to method */
1142 if (acfg->use_bin_writer) {
1143 guint8 buf [4];
1144 guint8 *code;
1146 code = buf;
1147 ARM_B (code, 0);
1149 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1150 emit_bytes (acfg, buf, 4);
1151 } else {
1152 if (acfg->thumb_mixed && cfg->compile_llvm)
1153 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1154 else
1155 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1157 #elif defined(TARGET_POWERPC)
1158 int this_pos = 3;
1160 g_assert (!acfg->use_bin_writer);
1162 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1163 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1164 #else
1165 g_assert_not_reached ();
1166 #endif
1170 * arch_emit_static_rgctx_trampoline:
1172 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1173 * two GOT slots which contain the rgctx argument, and the method to jump to.
1174 * TRAMP_SIZE is set to the size of the emitted trampoline.
1175 * These kinds of trampolines cannot be enumerated statically, since there could
1176 * be one trampoline per method instantiation, so we emit the same code for all
1177 * trampolines, and parameterize them using two GOT slots.
1179 static void
1180 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1182 #if defined(TARGET_AMD64)
1183 #if defined(__default_codegen__)
1184 /* This should be exactly 13 bytes long */
1185 *tramp_size = 13;
1187 /* mov <OFFSET>(%rip), %r10 */
1188 emit_byte (acfg, '\x4d');
1189 emit_byte (acfg, '\x8b');
1190 emit_byte (acfg, '\x15');
1191 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1193 /* jmp *<offset>(%rip) */
1194 emit_byte (acfg, '\xff');
1195 emit_byte (acfg, '\x25');
1196 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1197 #elif defined(__native_client_codegen__)
1198 guint8 buf [128];
1199 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1200 guint8 *code = buf_aligned;
1202 /* mov <OFFSET>(%rip), %r10d */
1203 emit_byte (acfg, '\x45');
1204 emit_byte (acfg, '\x8b');
1205 emit_byte (acfg, '\x15');
1206 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1208 /* mov <OFFSET>(%rip), %r11d */
1209 emit_byte (acfg, '\x45');
1210 emit_byte (acfg, '\x8b');
1211 emit_byte (acfg, '\x1d');
1212 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1214 /* nacljmp *%r11 */
1215 amd64_jump_reg (code, AMD64_R11);
1216 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1218 emit_alignment (acfg, kNaClAlignment);
1219 *tramp_size = kNaClAlignment;
1220 #endif /*__native_client_codegen__*/
1222 #elif defined(TARGET_ARM)
1223 guint8 buf [128];
1224 guint8 *code;
1226 /* This should be exactly 24 bytes long */
1227 *tramp_size = 24;
1228 code = buf;
1229 /* Load rgctx value */
1230 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1231 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1232 /* Load branch addr + branch */
1233 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1234 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1236 g_assert (code - buf == 16);
1238 /* Emit it */
1239 emit_bytes (acfg, buf, code - buf);
1240 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1241 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1242 #elif defined(TARGET_POWERPC)
1243 guint8 buf [128];
1244 guint8 *code;
1246 *tramp_size = 4;
1247 code = buf;
1249 g_assert (!acfg->use_bin_writer);
1252 * PPC has no ip relative addressing, so we need to compute the address
1253 * of the mscorlib got. That is slow and complex, so instead, we store it
1254 * in the second got slot of every aot image. The caller already computed
1255 * the address of its got and placed it into r30.
1257 img_writer_emit_unset_mode (acfg->w);
1258 /* Load mscorlib got address */
1259 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1260 /* Load rgctx */
1261 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1262 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1263 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1264 /* Load target address */
1265 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1266 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1267 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1268 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1269 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1270 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1271 #endif
1272 fprintf (acfg->fp, "mtctr 11\n");
1273 /* Branch to the target address */
1274 fprintf (acfg->fp, "bctr\n");
1276 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1277 *tramp_size = 11 * 4;
1278 #else
1279 *tramp_size = 9 * 4;
1280 #endif
1282 #elif defined(TARGET_X86)
1283 guint8 buf [128];
1284 guint8 *code;
1286 /* Similar to the PPC code above */
1288 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1290 code = buf;
1291 /* Load mscorlib got address */
1292 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1293 /* Load arg */
1294 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1295 /* Branch to the target address */
1296 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1298 #ifdef __native_client_codegen__
1300 /* emit nops to next 32 byte alignment */
1301 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1302 while (code < (buf + a)) x86_nop(code);
1304 #endif
1306 emit_bytes (acfg, buf, code - buf);
1308 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1309 g_assert (code - buf == *tramp_size);
1310 #else
1311 g_assert_not_reached ();
1312 #endif
1316 * arch_emit_imt_thunk:
1318 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1319 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1320 * key is the IMT key, and ptr holds the address of a memory location holding
1321 * the address to branch to if the IMT arg matches the key. The array is
1322 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1323 * fail_tramp.
1324 * TRAMP_SIZE is set to the size of the emitted trampoline.
1326 static void
1327 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1329 #if defined(TARGET_AMD64)
1330 guint8 *buf, *code;
1331 #if defined(__native_client_codegen__)
1332 guint8 *buf_alloc;
1333 #endif
1334 guint8 *labels [16];
1335 guint8 mov_buf[3];
1336 guint8 *mov_buf_ptr = mov_buf;
1338 const int kSizeOfMove = 7;
1339 #if defined(__default_codegen__)
1340 code = buf = g_malloc (256);
1341 #elif defined(__native_client_codegen__)
1342 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1343 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1344 /* The RIP relative move below is emitted first */
1345 buf += kSizeOfMove;
1346 code = buf;
1347 #endif
1349 /* FIXME: Optimize this, i.e. use binary search etc. */
1350 /* Maybe move the body into a separate function (slower, but much smaller) */
1352 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1354 labels [0] = code;
1355 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1356 labels [1] = code;
1357 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1359 /* Check key */
1360 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1361 labels [2] = code;
1362 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1364 /* Loop footer */
1365 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1366 amd64_jump_code (code, labels [0]);
1368 /* Match */
1369 mono_amd64_patch (labels [2], code);
1370 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1371 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1373 /* No match */
1374 mono_amd64_patch (labels [1], code);
1375 /* Load fail tramp */
1376 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1377 /* Check if there is a fail tramp */
1378 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1379 labels [3] = code;
1380 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1381 /* Jump to fail tramp */
1382 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1384 /* Fail */
1385 mono_amd64_patch (labels [3], code);
1386 x86_breakpoint (code);
1388 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1389 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1390 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1391 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1392 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1393 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1395 emit_bytes (acfg, buf, code - buf);
1397 *tramp_size = code - buf + kSizeOfMove;
1398 #if defined(__native_client_codegen__)
1399 /* The tramp will be padded to the next kNaClAlignment bundle. */
1400 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1401 #endif
1403 #if defined(__default_codegen__)
1404 g_free (buf);
1405 #elif defined(__native_client_codegen__)
1406 g_free (buf_alloc);
1407 #endif
1409 #elif defined(TARGET_X86)
1410 guint8 *buf, *code;
1411 #ifdef __native_client_codegen__
1412 guint8 *buf_alloc;
1413 #endif
1414 guint8 *labels [16];
1416 #if defined(__default_codegen__)
1417 code = buf = g_malloc (256);
1418 #elif defined(__native_client_codegen__)
1419 buf_alloc = g_malloc (256 + kNaClAlignment);
1420 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1421 #endif
1423 /* Allocate a temporary stack slot */
1424 x86_push_reg (code, X86_EAX);
1425 /* Save EAX */
1426 x86_push_reg (code, X86_EAX);
1428 /* Load mscorlib got address */
1429 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1430 /* Load arg */
1431 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1433 labels [0] = code;
1434 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1435 labels [1] = code;
1436 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1438 /* Check key */
1439 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1440 labels [2] = code;
1441 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1443 /* Loop footer */
1444 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1445 x86_jump_code (code, labels [0]);
1447 /* Match */
1448 mono_x86_patch (labels [2], code);
1449 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1450 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1451 /* Save the target address to the temporary stack location */
1452 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1453 /* Restore EAX */
1454 x86_pop_reg (code, X86_EAX);
1455 /* Jump to the target address */
1456 x86_ret (code);
1458 /* No match */
1459 mono_x86_patch (labels [1], code);
1460 /* Load fail tramp */
1461 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1462 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1463 labels [3] = code;
1464 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1465 /* Jump to fail tramp */
1466 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1467 x86_pop_reg (code, X86_EAX);
1468 x86_ret (code);
1470 /* Fail */
1471 mono_x86_patch (labels [3], code);
1472 x86_breakpoint (code);
1474 #ifdef __native_client_codegen__
1476 /* emit nops to next 32 byte alignment */
1477 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1478 while (code < (buf + a)) x86_nop(code);
1480 #endif
1481 emit_bytes (acfg, buf, code - buf);
1483 *tramp_size = code - buf;
1485 #if defined(__default_codegen__)
1486 g_free (buf);
1487 #elif defined(__native_client_codegen__)
1488 g_free (buf_alloc);
1489 #endif
1491 #elif defined(TARGET_ARM)
1492 guint8 buf [128];
1493 guint8 *code, *code2, *labels [16];
1495 code = buf;
1497 /* The IMT method is in v5 */
1499 /* Need at least two free registers, plus a slot for storing the pc */
1500 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1501 labels [0] = code;
1502 /* Load the parameter from the GOT */
1503 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1504 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1506 labels [1] = code;
1507 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1508 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1509 labels [2] = code;
1510 ARM_B_COND (code, ARMCOND_EQ, 0);
1512 /* End-of-loop check */
1513 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1514 labels [3] = code;
1515 ARM_B_COND (code, ARMCOND_EQ, 0);
1517 /* Loop footer */
1518 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1519 labels [4] = code;
1520 ARM_B (code, 0);
1521 arm_patch (labels [4], labels [1]);
1523 /* Match */
1524 arm_patch (labels [2], code);
1525 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1526 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1527 /* Save it to the third stack slot */
1528 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1529 /* Restore the registers and branch */
1530 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1532 /* No match */
1533 arm_patch (labels [3], code);
1534 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1535 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1536 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1538 /* Fixup offset */
1539 code2 = labels [0];
1540 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1542 emit_bytes (acfg, buf, code - buf);
1543 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1545 *tramp_size = code - buf + 4;
1546 #elif defined(TARGET_POWERPC)
1547 guint8 buf [128];
1548 guint8 *code, *labels [16];
1550 code = buf;
1552 /* Load the mscorlib got address */
1553 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1554 /* Load the parameter from the GOT */
1555 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1556 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1558 /* Load and check key */
1559 labels [1] = code;
1560 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1561 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1562 labels [2] = code;
1563 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1565 /* End-of-loop check */
1566 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1567 labels [3] = code;
1568 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1570 /* Loop footer */
1571 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1572 labels [4] = code;
1573 ppc_b (code, 0);
1574 mono_ppc_patch (labels [4], labels [1]);
1576 /* Match */
1577 mono_ppc_patch (labels [2], code);
1578 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1579 /* r11 now contains the value of the vtable slot */
1580 /* this is not a function descriptor on ppc64 */
1581 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1582 ppc_mtctr (code, ppc_r11);
1583 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1585 /* Fail */
1586 mono_ppc_patch (labels [3], code);
1587 /* FIXME: */
1588 ppc_break (code);
1590 *tramp_size = code - buf;
1592 emit_bytes (acfg, buf, code - buf);
1593 #else
1594 g_assert_not_reached ();
1595 #endif
1598 static void
1599 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1601 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1602 /* Based on code generated by gcc */
1603 img_writer_emit_unset_mode (acfg->w);
1605 fprintf (acfg->fp,
1606 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1607 ".section .ctors,\"aw\",@progbits\n"
1608 ".align 2\n"
1609 ".globl %s\n"
1610 ".long %s\n"
1611 ".section .opd,\"aw\"\n"
1612 ".align 2\n"
1613 "%s:\n"
1614 ".long .%s,.TOC.@tocbase32\n"
1615 ".size %s,.-%s\n"
1616 ".section .text\n"
1617 ".type .%s,@function\n"
1618 ".align 2\n"
1619 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1620 #else
1621 ".section .ctors,\"aw\",@progbits\n"
1622 ".align 2\n"
1623 ".globl %1$s\n"
1624 ".long %1$s\n"
1625 ".section .opd,\"aw\"\n"
1626 ".align 2\n"
1627 "%1$s:\n"
1628 ".long .%1$s,.TOC.@tocbase32\n"
1629 ".size %1$s,.-%1$s\n"
1630 ".section .text\n"
1631 ".type .%1$s,@function\n"
1632 ".align 2\n"
1633 ".%1$s:\n", symbol);
1634 #endif
1637 fprintf (acfg->fp,
1638 "stdu 1,-128(1)\n"
1639 "mflr 0\n"
1640 "std 31,120(1)\n"
1641 "std 0,144(1)\n"
1643 ".Lautoreg:\n"
1644 "lis 3, .Lglobals@h\n"
1645 "ori 3, 3, .Lglobals@l\n"
1646 "bl .mono_aot_register_module\n"
1647 "ld 11,0(1)\n"
1648 "ld 0,16(11)\n"
1649 "mtlr 0\n"
1650 "ld 31,-8(11)\n"
1651 "mr 1,11\n"
1652 "blr\n"
1654 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1655 fprintf (acfg->fp,
1656 ".size .%s,.-.%s\n", symbol, symbol);
1657 #else
1658 fprintf (acfg->fp,
1659 ".size .%1$s,.-.%1$s\n", symbol);
1660 #endif
1661 #else
1662 #endif
1665 /* END OF ARCH SPECIFIC CODE */
1667 static guint32
1668 mono_get_field_token (MonoClassField *field)
1670 MonoClass *klass = field->parent;
1671 int i;
1673 for (i = 0; i < klass->field.count; ++i) {
1674 if (field == &klass->fields [i])
1675 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1678 g_assert_not_reached ();
1679 return 0;
1682 static inline void
1683 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1685 guint8 *p = buf;
1687 //printf ("ENCODE: %d 0x%x.\n", value, value);
1690 * Same encoding as the one used in the metadata, extended to handle values
1691 * greater than 0x1fffffff.
1693 if ((value >= 0) && (value <= 127))
1694 *p++ = value;
1695 else if ((value >= 0) && (value <= 16383)) {
1696 p [0] = 0x80 | (value >> 8);
1697 p [1] = value & 0xff;
1698 p += 2;
1699 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1700 p [0] = (value >> 24) | 0xc0;
1701 p [1] = (value >> 16) & 0xff;
1702 p [2] = (value >> 8) & 0xff;
1703 p [3] = value & 0xff;
1704 p += 4;
1706 else {
1707 p [0] = 0xff;
1708 p [1] = (value >> 24) & 0xff;
1709 p [2] = (value >> 16) & 0xff;
1710 p [3] = (value >> 8) & 0xff;
1711 p [4] = value & 0xff;
1712 p += 5;
1714 if (endbuf)
1715 *endbuf = p;
1718 static void
1719 stream_init (MonoDynamicStream *sh)
1721 sh->index = 0;
1722 sh->alloc_size = 4096;
1723 sh->data = g_malloc (4096);
1725 /* So offsets are > 0 */
1726 sh->data [0] = 0;
1727 sh->index ++;
1730 static void
1731 make_room_in_stream (MonoDynamicStream *stream, int size)
1733 if (size <= stream->alloc_size)
1734 return;
1736 while (stream->alloc_size <= size) {
1737 if (stream->alloc_size < 4096)
1738 stream->alloc_size = 4096;
1739 else
1740 stream->alloc_size *= 2;
1743 stream->data = g_realloc (stream->data, stream->alloc_size);
1746 static guint32
1747 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1749 guint32 idx;
1751 make_room_in_stream (stream, stream->index + len);
1752 memcpy (stream->data + stream->index, data, len);
1753 idx = stream->index;
1754 stream->index += len;
1755 return idx;
1759 * add_to_blob:
1761 * Add data to the binary blob inside the aot image. Returns the offset inside the
1762 * blob where the data was stored.
1764 static guint32
1765 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1767 if (acfg->blob.alloc_size == 0)
1768 stream_init (&acfg->blob);
1770 return add_stream_data (&acfg->blob, (char*)data, data_len);
1773 static guint32
1774 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1776 char buf [4] = {0};
1777 guint32 count;
1779 if (acfg->blob.alloc_size == 0)
1780 stream_init (&acfg->blob);
1782 count = acfg->blob.index % align;
1784 /* we assume the stream data will be aligned */
1785 if (count)
1786 add_stream_data (&acfg->blob, buf, 4 - count);
1788 return add_stream_data (&acfg->blob, (char*)data, data_len);
1792 * emit_offset_table:
1794 * Emit a table of increasing offsets in a compact form using differential encoding.
1795 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1796 * group size, the more compact the table becomes, but the slower it becomes to compute
1797 * a given entry. Returns the size of the table.
1799 static guint32
1800 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1802 gint32 current_offset;
1803 int i, buf_size, ngroups, index_entry_size;
1804 guint8 *p, *buf;
1805 guint32 *index_offsets;
1807 ngroups = (noffsets + (group_size - 1)) / group_size;
1809 index_offsets = g_new0 (guint32, ngroups);
1811 buf_size = noffsets * 4;
1812 p = buf = g_malloc0 (buf_size);
1814 current_offset = 0;
1815 for (i = 0; i < noffsets; ++i) {
1816 //printf ("D: %d -> %d\n", i, offsets [i]);
1817 if ((i % group_size) == 0) {
1818 index_offsets [i / group_size] = p - buf;
1819 /* Emit the full value for these entries */
1820 encode_value (offsets [i], p, &p);
1821 } else {
1822 /* The offsets are allowed to be non-increasing */
1823 //g_assert (offsets [i] >= current_offset);
1824 encode_value (offsets [i] - current_offset, p, &p);
1826 current_offset = offsets [i];
1829 if (ngroups && index_offsets [ngroups - 1] < 65000)
1830 index_entry_size = 2;
1831 else
1832 index_entry_size = 4;
1834 /* Emit the header */
1835 emit_int32 (acfg, noffsets);
1836 emit_int32 (acfg, group_size);
1837 emit_int32 (acfg, ngroups);
1838 emit_int32 (acfg, index_entry_size);
1840 /* Emit the index */
1841 for (i = 0; i < ngroups; ++i) {
1842 if (index_entry_size == 2)
1843 emit_int16 (acfg, index_offsets [i]);
1844 else
1845 emit_int32 (acfg, index_offsets [i]);
1848 /* Emit the data */
1849 emit_bytes (acfg, buf, p - buf);
1851 return (int)(p - buf) + (ngroups * 4);
1854 static guint32
1855 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1857 guint32 index;
1859 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1860 if (index)
1861 return index - 1;
1862 else {
1863 index = g_hash_table_size (cfg->image_hash);
1864 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1865 g_ptr_array_add (cfg->image_table, image);
1866 return index;
1870 static guint32
1871 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1873 int i;
1874 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1876 /* FIXME: Search referenced images as well */
1877 if (!acfg->typespec_classes) {
1878 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1879 for (i = 0; i < len; ++i) {
1880 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1883 for (i = 0; i < len; ++i) {
1884 if (acfg->typespec_classes [i] == klass)
1885 break;
1888 if (i < len)
1889 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1890 else
1891 return 0;
1894 static void
1895 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1897 static void
1898 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1900 static void
1901 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1903 static void
1904 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1906 static void
1907 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1909 guint8 *p = buf;
1912 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1913 * information.
1916 if (klass->generic_class) {
1917 guint32 token;
1918 g_assert (klass->type_token);
1920 /* Find a typespec for a class if possible */
1921 token = find_typespec_for_class (acfg, klass);
1922 if (token) {
1923 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1924 encode_value (token, p, &p);
1925 } else {
1926 MonoClass *gclass = klass->generic_class->container_class;
1927 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1928 static int count = 0;
1929 guint8 *p1 = p;
1931 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1932 encode_klass_ref (acfg, gclass, p, &p);
1933 encode_ginst (acfg, inst, p, &p);
1935 count += p - p1;
1937 } else if (klass->type_token) {
1938 int iindex = get_image_index (acfg, klass->image);
1940 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1941 if (iindex == 0) {
1942 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1943 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1944 } else {
1945 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1946 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1947 encode_value (get_image_index (acfg, klass->image), p, &p);
1949 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1950 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1951 MonoGenericParam *par = klass->byval_arg.data.generic_param;
1953 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1954 encode_value (klass->byval_arg.type, p, &p);
1955 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1957 encode_value (container ? 1 : 0, p, &p);
1958 if (container) {
1959 encode_value (container->is_method, p, &p);
1960 g_assert (par->serial == 0);
1961 if (container->is_method)
1962 encode_method_ref (acfg, container->owner.method, p, &p);
1963 else
1964 encode_klass_ref (acfg, container->owner.klass, p, &p);
1965 } else {
1966 encode_value (par->serial, p, &p);
1968 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1969 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1970 encode_type (acfg, &klass->byval_arg, p, &p);
1971 } else {
1972 /* Array class */
1973 g_assert (klass->rank > 0);
1974 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1975 encode_value (klass->rank, p, &p);
1976 encode_klass_ref (acfg, klass->element_class, p, &p);
1978 *endbuf = p;
1982 * encode_klass_ref:
1984 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1985 * standard metadata encoding.
1987 static void
1988 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1990 gboolean shared = FALSE;
1993 * The encoding of generic instances is large so emit them only once.
1995 if (klass->generic_class) {
1996 guint32 token;
1997 g_assert (klass->type_token);
1999 /* Find a typespec for a class if possible */
2000 token = find_typespec_for_class (acfg, klass);
2001 if (!token)
2002 shared = TRUE;
2003 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2004 shared = TRUE;
2007 if (shared) {
2008 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2009 guint8 *buf2, *p;
2011 if (!offset) {
2012 buf2 = g_malloc (1024);
2013 p = buf2;
2015 encode_klass_ref_inner (acfg, klass, p, &p);
2016 g_assert (p - buf2 < 1024);
2018 offset = add_to_blob (acfg, buf2, p - buf2);
2019 g_free (buf2);
2021 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2022 } else {
2023 offset --;
2026 p = buf;
2027 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2028 encode_value (offset, p, &p);
2029 *endbuf = p;
2030 return;
2033 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2036 static void
2037 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2039 guint32 token = mono_get_field_token (field);
2040 guint8 *p = buf;
2042 encode_klass_ref (cfg, field->parent, p, &p);
2043 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2044 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2045 *endbuf = p;
2048 static void
2049 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2051 guint8 *p = buf;
2052 int i;
2054 encode_value (inst->type_argc, p, &p);
2055 for (i = 0; i < inst->type_argc; ++i)
2056 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2057 *endbuf = p;
2060 static void
2061 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2063 guint8 *p = buf;
2064 MonoGenericInst *inst;
2066 inst = context->class_inst;
2067 if (inst) {
2068 g_assert (inst->type_argc);
2069 encode_ginst (acfg, inst, p, &p);
2070 } else {
2071 encode_value (0, p, &p);
2073 inst = context->method_inst;
2074 if (inst) {
2075 g_assert (inst->type_argc);
2076 encode_ginst (acfg, inst, p, &p);
2077 } else {
2078 encode_value (0, p, &p);
2080 *endbuf = p;
2083 static void
2084 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2086 guint8 *p = buf;
2088 g_assert (t->num_mods == 0);
2089 /* t->attrs can be ignored */
2090 //g_assert (t->attrs == 0);
2092 if (t->pinned) {
2093 *p = MONO_TYPE_PINNED;
2094 ++p;
2096 if (t->byref) {
2097 *p = MONO_TYPE_BYREF;
2098 ++p;
2101 *p = t->type;
2102 p ++;
2104 switch (t->type) {
2105 case MONO_TYPE_VOID:
2106 case MONO_TYPE_BOOLEAN:
2107 case MONO_TYPE_CHAR:
2108 case MONO_TYPE_I1:
2109 case MONO_TYPE_U1:
2110 case MONO_TYPE_I2:
2111 case MONO_TYPE_U2:
2112 case MONO_TYPE_I4:
2113 case MONO_TYPE_U4:
2114 case MONO_TYPE_I8:
2115 case MONO_TYPE_U8:
2116 case MONO_TYPE_R4:
2117 case MONO_TYPE_R8:
2118 case MONO_TYPE_I:
2119 case MONO_TYPE_U:
2120 case MONO_TYPE_STRING:
2121 case MONO_TYPE_OBJECT:
2122 case MONO_TYPE_TYPEDBYREF:
2123 break;
2124 case MONO_TYPE_VALUETYPE:
2125 case MONO_TYPE_CLASS:
2126 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2127 break;
2128 case MONO_TYPE_SZARRAY:
2129 encode_klass_ref (acfg, t->data.klass, p, &p);
2130 break;
2131 case MONO_TYPE_PTR:
2132 encode_type (acfg, t->data.type, p, &p);
2133 break;
2134 case MONO_TYPE_GENERICINST: {
2135 MonoClass *gclass = t->data.generic_class->container_class;
2136 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2138 encode_klass_ref (acfg, gclass, p, &p);
2139 encode_ginst (acfg, inst, p, &p);
2140 break;
2142 case MONO_TYPE_ARRAY: {
2143 MonoArrayType *array = t->data.array;
2144 int i;
2146 encode_klass_ref (acfg, array->eklass, p, &p);
2147 encode_value (array->rank, p, &p);
2148 encode_value (array->numsizes, p, &p);
2149 for (i = 0; i < array->numsizes; ++i)
2150 encode_value (array->sizes [i], p, &p);
2151 encode_value (array->numlobounds, p, &p);
2152 for (i = 0; i < array->numlobounds; ++i)
2153 encode_value (array->lobounds [i], p, &p);
2154 break;
2156 default:
2157 g_assert_not_reached ();
2160 *endbuf = p;
2163 static void
2164 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2166 guint8 *p = buf;
2167 guint32 flags = 0;
2168 int i;
2170 /* Similar to the metadata encoding */
2171 if (sig->generic_param_count)
2172 flags |= 0x10;
2173 if (sig->hasthis)
2174 flags |= 0x20;
2175 if (sig->explicit_this)
2176 flags |= 0x40;
2177 flags |= (sig->call_convention & 0x0F);
2179 *p = flags;
2180 ++p;
2181 if (sig->generic_param_count)
2182 encode_value (sig->generic_param_count, p, &p);
2183 encode_value (sig->param_count, p, &p);
2185 encode_type (acfg, sig->ret, p, &p);
2186 for (i = 0; i < sig->param_count; ++i) {
2187 if (sig->sentinelpos == i) {
2188 *p = MONO_TYPE_SENTINEL;
2189 ++p;
2191 encode_type (acfg, sig->params [i], p, &p);
2194 *endbuf = p;
2197 #define MAX_IMAGE_INDEX 250
2199 static void
2200 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2202 guint32 image_index = get_image_index (acfg, method->klass->image);
2203 guint32 token = method->token;
2204 MonoJumpInfoToken *ji;
2205 guint8 *p = buf;
2208 * The encoding for most methods is as follows:
2209 * - image index encoded as a leb128
2210 * - token index encoded as a leb128
2211 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2212 * types of method encodings.
2215 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2217 /* Mark methods which can't use aot trampolines because they need the further
2218 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2220 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2221 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2222 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2224 if (method->wrapper_type) {
2225 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2227 encode_value (method->wrapper_type, p, &p);
2229 switch (method->wrapper_type) {
2230 case MONO_WRAPPER_REMOTING_INVOKE:
2231 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2232 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2233 MonoMethod *m;
2235 m = mono_marshal_method_from_wrapper (method);
2236 g_assert (m);
2237 encode_method_ref (acfg, m, p, &p);
2238 break;
2240 case MONO_WRAPPER_PROXY_ISINST:
2241 case MONO_WRAPPER_LDFLD:
2242 case MONO_WRAPPER_LDFLDA:
2243 case MONO_WRAPPER_STFLD:
2244 case MONO_WRAPPER_ISINST: {
2245 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2246 encode_klass_ref (acfg, proxy_class, p, &p);
2247 break;
2249 case MONO_WRAPPER_LDFLD_REMOTE:
2250 case MONO_WRAPPER_STFLD_REMOTE:
2251 break;
2252 case MONO_WRAPPER_ALLOC: {
2253 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2255 /* The GC name is saved once in MonoAotFileInfo */
2256 g_assert (info->alloc_type != -1);
2257 encode_value (info->alloc_type, p, &p);
2258 break;
2260 case MONO_WRAPPER_WRITE_BARRIER:
2261 break;
2262 case MONO_WRAPPER_STELEMREF: {
2263 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2265 g_assert (info);
2266 encode_value (info->subtype, p, &p);
2267 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2268 encode_value (info->d.virtual_stelemref.kind, p, &p);
2269 break;
2271 case MONO_WRAPPER_UNKNOWN: {
2272 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2274 g_assert (info);
2275 encode_value (info->subtype, p, &p);
2276 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2277 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2278 encode_klass_ref (acfg, method->klass, p, &p);
2279 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2280 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2281 break;
2283 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2284 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2286 g_assert (info);
2287 encode_value (info->subtype, p, &p);
2288 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2289 strcpy ((char*)p, method->name);
2290 p += strlen (method->name) + 1;
2291 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2292 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2293 } else {
2294 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2295 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2297 break;
2299 case MONO_WRAPPER_SYNCHRONIZED: {
2300 MonoMethod *m;
2302 m = mono_marshal_method_from_wrapper (method);
2303 g_assert (m);
2304 g_assert (m != method);
2305 encode_method_ref (acfg, m, p, &p);
2306 break;
2308 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2309 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2311 g_assert (info);
2312 encode_value (info->subtype, p, &p);
2314 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2315 encode_value (info->d.element_addr.rank, p, &p);
2316 encode_value (info->d.element_addr.elem_size, p, &p);
2317 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2318 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2319 } else {
2320 g_assert_not_reached ();
2322 break;
2324 case MONO_WRAPPER_CASTCLASS: {
2325 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2327 g_assert (info);
2328 encode_value (info->subtype, p, &p);
2329 break;
2331 case MONO_WRAPPER_RUNTIME_INVOKE: {
2332 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2334 if (info) {
2335 encode_value (info->subtype, p, &p);
2336 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2337 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2338 } else {
2339 MonoMethodSignature *sig;
2341 encode_value (0, p, &p);
2343 sig = mono_method_signature (method);
2344 encode_signature (acfg, sig, p, &p);
2346 break;
2348 case MONO_WRAPPER_DELEGATE_INVOKE:
2349 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2350 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2351 MonoMethodSignature *sig = mono_method_signature (method);
2352 encode_signature (acfg, sig, p, &p);
2353 break;
2355 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2356 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2358 g_assert (info);
2359 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2360 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2361 break;
2363 default:
2364 g_assert_not_reached ();
2366 } else if (mono_method_signature (method)->is_inflated) {
2368 * This is a generic method, find the original token which referenced it and
2369 * encode that.
2370 * Obtain the token from information recorded by the JIT.
2372 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2373 if (ji) {
2374 image_index = get_image_index (acfg, ji->image);
2375 g_assert (image_index < MAX_IMAGE_INDEX);
2376 token = ji->token;
2378 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2379 encode_value (image_index, p, &p);
2380 encode_value (token, p, &p);
2381 } else {
2382 MonoMethod *declaring;
2383 MonoGenericContext *context = mono_method_get_context (method);
2385 g_assert (method->is_inflated);
2386 declaring = ((MonoMethodInflated*)method)->declaring;
2389 * This might be a non-generic method of a generic instance, which
2390 * doesn't have a token since the reference is generated by the JIT
2391 * like Nullable:Box/Unbox, or by generic sharing.
2394 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2395 /* Encode the klass */
2396 encode_klass_ref (acfg, method->klass, p, &p);
2397 /* Encode the method */
2398 image_index = get_image_index (acfg, method->klass->image);
2399 g_assert (image_index < MAX_IMAGE_INDEX);
2400 g_assert (declaring->token);
2401 token = declaring->token;
2402 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2403 encode_value (image_index, p, &p);
2404 encode_value (token, p, &p);
2405 encode_generic_context (acfg, context, p, &p);
2407 } else if (token == 0) {
2408 /* This might be a method of a constructed type like int[,].Set */
2409 /* Obtain the token from information recorded by the JIT */
2410 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2411 if (ji) {
2412 image_index = get_image_index (acfg, ji->image);
2413 g_assert (image_index < MAX_IMAGE_INDEX);
2414 token = ji->token;
2416 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2417 encode_value (image_index, p, &p);
2418 encode_value (token, p, &p);
2419 } else {
2420 /* Array methods */
2421 g_assert (method->klass->rank);
2423 /* Encode directly */
2424 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2425 encode_klass_ref (acfg, method->klass, p, &p);
2426 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2427 encode_value (0, p, &p);
2428 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2429 encode_value (1, p, &p);
2430 else if (!strcmp (method->name, "Get"))
2431 encode_value (2, p, &p);
2432 else if (!strcmp (method->name, "Address"))
2433 encode_value (3, p, &p);
2434 else if (!strcmp (method->name, "Set"))
2435 encode_value (4, p, &p);
2436 else
2437 g_assert_not_reached ();
2439 } else {
2440 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2441 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2443 *endbuf = p;
2446 static gint
2447 compare_patches (gconstpointer a, gconstpointer b)
2449 int i, j;
2451 i = (*(MonoJumpInfo**)a)->ip.i;
2452 j = (*(MonoJumpInfo**)b)->ip.i;
2454 if (i < j)
2455 return -1;
2456 else
2457 if (i > j)
2458 return 1;
2459 else
2460 return 0;
2463 static G_GNUC_UNUSED char*
2464 patch_to_string (MonoJumpInfo *patch_info)
2466 GString *str;
2468 str = g_string_new ("");
2470 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2472 switch (patch_info->type) {
2473 case MONO_PATCH_INFO_VTABLE:
2474 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2475 break;
2476 default:
2477 break;
2479 g_string_append_printf (str, ")");
2480 return g_string_free (str, FALSE);
2484 * is_plt_patch:
2486 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2487 * PLT entry.
2489 static inline gboolean
2490 is_plt_patch (MonoJumpInfo *patch_info)
2492 switch (patch_info->type) {
2493 case MONO_PATCH_INFO_METHOD:
2494 case MONO_PATCH_INFO_INTERNAL_METHOD:
2495 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2496 case MONO_PATCH_INFO_ICALL_ADDR:
2497 case MONO_PATCH_INFO_CLASS_INIT:
2498 case MONO_PATCH_INFO_RGCTX_FETCH:
2499 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2500 case MONO_PATCH_INFO_MONITOR_ENTER:
2501 case MONO_PATCH_INFO_MONITOR_EXIT:
2502 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2503 return TRUE;
2504 default:
2505 return FALSE;
2510 * get_plt_symbol:
2512 * Return the symbol identifying the plt entry PLT_OFFSET.
2514 static char*
2515 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2517 #ifdef TARGET_MACH
2519 * The Apple linker reorganizes object files, so it doesn't like branches to local
2520 * labels, since those have no relocations.
2522 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2523 #else
2524 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2525 #endif
2529 * get_plt_entry:
2531 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2533 static MonoPltEntry*
2534 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2536 MonoPltEntry *res;
2538 if (!is_plt_patch (patch_info))
2539 return NULL;
2541 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2543 // FIXME: This breaks the calculation of final_got_size
2544 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2546 * Allocate a separate PLT slot for each such patch, since some plt
2547 * entries will refer to the method itself, and some will refer to the
2548 * wrapper.
2550 res = NULL;
2553 if (!res) {
2554 MonoJumpInfo *new_ji;
2556 g_assert (!acfg->final_got_size);
2558 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2560 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2561 res->plt_offset = acfg->plt_offset;
2562 res->ji = new_ji;
2563 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2564 if (acfg->aot_opts.write_symbols)
2565 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2566 if (res->debug_sym)
2567 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2568 else
2569 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2571 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2573 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2575 acfg->plt_offset ++;
2578 return res;
2582 * get_got_offset:
2584 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2585 * JI could be found if it exists, otherwise allocates a new one.
2587 static guint32
2588 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2590 guint32 got_offset;
2592 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2593 if (got_offset)
2594 return got_offset - 1;
2596 got_offset = acfg->got_offset;
2597 acfg->got_offset ++;
2599 if (acfg->final_got_size)
2600 g_assert (got_offset < acfg->final_got_size);
2602 acfg->stats.got_slots ++;
2603 acfg->stats.got_slot_types [ji->type] ++;
2605 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2606 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2607 g_ptr_array_add (acfg->got_patches, ji);
2609 return got_offset;
2612 /* Add a method to the list of methods which need to be emitted */
2613 static void
2614 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2616 g_assert (method);
2617 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2618 g_ptr_array_add (acfg->methods, method);
2619 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2620 acfg->nmethods = acfg->methods->len + 1;
2623 if (method->wrapper_type || extra)
2624 g_ptr_array_add (acfg->extra_methods, method);
2627 static guint32
2628 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2630 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2632 g_assert (index);
2634 return index - 1;
2637 static int
2638 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2640 int index;
2642 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2643 if (index)
2644 return index - 1;
2646 index = acfg->method_index;
2647 add_method_with_index (acfg, method, index, extra);
2649 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2651 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2653 acfg->method_index ++;
2655 return index;
2658 static int
2659 add_method (MonoAotCompile *acfg, MonoMethod *method)
2661 return add_method_full (acfg, method, FALSE, 0);
2664 static void
2665 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2667 add_method_full (acfg, method, TRUE, 0);
2670 static void
2671 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2673 if (acfg->aot_opts.log_generics)
2674 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2676 add_method_full (acfg, method, TRUE, depth);
2679 static void
2680 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2682 MonoAotCompile *acfg = user_data;
2683 MonoJitICallInfo *callinfo = value;
2684 MonoMethod *wrapper;
2685 char *name;
2687 if (!callinfo->sig)
2688 return;
2690 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2691 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2692 g_free (name);
2694 add_method (acfg, wrapper);
2697 static MonoMethod*
2698 get_runtime_invoke_sig (MonoMethodSignature *sig)
2700 MonoMethodBuilder *mb;
2701 MonoMethod *m;
2703 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2704 m = mono_mb_create_method (mb, sig, 16);
2705 return mono_marshal_get_runtime_invoke (m, FALSE);
2708 static gboolean
2709 can_marshal_struct (MonoClass *klass)
2711 MonoClassField *field;
2712 gboolean can_marshal = TRUE;
2713 gpointer iter = NULL;
2715 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2716 return FALSE;
2718 /* Only allow a few field types to avoid asserts in the marshalling code */
2719 while ((field = mono_class_get_fields (klass, &iter))) {
2720 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2721 continue;
2723 switch (field->type->type) {
2724 case MONO_TYPE_I4:
2725 case MONO_TYPE_U4:
2726 case MONO_TYPE_I1:
2727 case MONO_TYPE_U1:
2728 case MONO_TYPE_BOOLEAN:
2729 case MONO_TYPE_I2:
2730 case MONO_TYPE_U2:
2731 case MONO_TYPE_CHAR:
2732 case MONO_TYPE_I8:
2733 case MONO_TYPE_U8:
2734 case MONO_TYPE_I:
2735 case MONO_TYPE_U:
2736 case MONO_TYPE_PTR:
2737 case MONO_TYPE_R4:
2738 case MONO_TYPE_R8:
2739 case MONO_TYPE_STRING:
2740 break;
2741 case MONO_TYPE_VALUETYPE:
2742 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2743 can_marshal = FALSE;
2744 break;
2745 default:
2746 can_marshal = FALSE;
2747 break;
2751 /* Special cases */
2752 /* Its hard to compute whenever these can be marshalled or not */
2753 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
2754 return TRUE;
2756 return can_marshal;
2759 static void
2760 add_wrappers (MonoAotCompile *acfg)
2762 MonoMethod *method, *m;
2763 int i, j;
2764 MonoMethodSignature *sig, *csig;
2765 guint32 token;
2768 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2769 * so there is only one wrapper of a given type, or inlining their contents into their
2770 * callers.
2774 * FIXME: This depends on the fact that different wrappers have different
2775 * names.
2778 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2779 MonoMethod *method;
2780 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2781 gboolean skip = FALSE;
2783 method = mono_get_method (acfg->image, token, NULL);
2785 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2786 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2787 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2788 skip = TRUE;
2790 if (method->is_generic || method->klass->generic_container)
2791 skip = TRUE;
2793 /* Skip methods which can not be handled by get_runtime_invoke () */
2794 sig = mono_method_signature (method);
2795 if (!sig)
2796 continue;
2797 if ((sig->ret->type == MONO_TYPE_PTR) ||
2798 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2799 skip = TRUE;
2801 for (j = 0; j < sig->param_count; j++) {
2802 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2803 skip = TRUE;
2806 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2807 if (!method->klass->contextbound) {
2808 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2809 gboolean has_nullable = FALSE;
2811 for (j = 0; j < sig->param_count; j++) {
2812 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2813 has_nullable = TRUE;
2816 if (info && !has_nullable) {
2817 /* Supported by the dynamic runtime-invoke wrapper */
2818 skip = TRUE;
2819 g_free (info);
2822 #endif
2824 if (!skip) {
2825 //printf ("%s\n", mono_method_full_name (method, TRUE));
2826 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2830 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2831 #ifdef MONO_ARCH_HAVE_TLS_GET
2832 MonoMethodDesc *desc;
2833 MonoMethod *orig_method;
2834 int nallocators;
2835 #endif
2837 /* Runtime invoke wrappers */
2839 /* void runtime-invoke () [.cctor] */
2840 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2841 csig->ret = &mono_defaults.void_class->byval_arg;
2842 add_method (acfg, get_runtime_invoke_sig (csig));
2844 /* void runtime-invoke () [Finalize] */
2845 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2846 csig->hasthis = 1;
2847 csig->ret = &mono_defaults.void_class->byval_arg;
2848 add_method (acfg, get_runtime_invoke_sig (csig));
2850 /* void runtime-invoke (string) [exception ctor] */
2851 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2852 csig->hasthis = 1;
2853 csig->ret = &mono_defaults.void_class->byval_arg;
2854 csig->params [0] = &mono_defaults.string_class->byval_arg;
2855 add_method (acfg, get_runtime_invoke_sig (csig));
2857 /* void runtime-invoke (string, string) [exception ctor] */
2858 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2859 csig->hasthis = 1;
2860 csig->ret = &mono_defaults.void_class->byval_arg;
2861 csig->params [0] = &mono_defaults.string_class->byval_arg;
2862 csig->params [1] = &mono_defaults.string_class->byval_arg;
2863 add_method (acfg, get_runtime_invoke_sig (csig));
2865 /* string runtime-invoke () [Exception.ToString ()] */
2866 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2867 csig->hasthis = 1;
2868 csig->ret = &mono_defaults.string_class->byval_arg;
2869 add_method (acfg, get_runtime_invoke_sig (csig));
2871 /* void runtime-invoke (string, Exception) [exception ctor] */
2872 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2873 csig->hasthis = 1;
2874 csig->ret = &mono_defaults.void_class->byval_arg;
2875 csig->params [0] = &mono_defaults.string_class->byval_arg;
2876 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2877 add_method (acfg, get_runtime_invoke_sig (csig));
2879 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2880 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2881 csig->hasthis = 1;
2882 csig->ret = &(mono_class_from_name (
2883 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2884 csig->params [0] = &mono_defaults.string_class->byval_arg;
2885 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2886 add_method (acfg, get_runtime_invoke_sig (csig));
2888 /* runtime-invoke used by finalizers */
2889 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2891 /* This is used by mono_runtime_capture_context () */
2892 method = mono_get_context_capture_method ();
2893 if (method)
2894 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2896 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2897 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2898 #endif
2900 /* JIT icall wrappers */
2901 /* FIXME: locking */
2902 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2904 /* stelemref */
2905 add_method (acfg, mono_marshal_get_stelemref ());
2907 #ifdef MONO_ARCH_HAVE_TLS_GET
2908 /* Managed Allocators */
2909 nallocators = mono_gc_get_managed_allocator_types ();
2910 for (i = 0; i < nallocators; ++i) {
2911 m = mono_gc_get_managed_allocator_by_type (i);
2912 if (m)
2913 add_method (acfg, m);
2916 /* Monitor Enter/Exit */
2917 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2918 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2919 /* This is a v4 method */
2920 if (orig_method) {
2921 method = mono_monitor_get_fast_path (orig_method);
2922 if (method)
2923 add_method (acfg, method);
2925 mono_method_desc_free (desc);
2927 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2928 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2929 g_assert (orig_method);
2930 mono_method_desc_free (desc);
2931 method = mono_monitor_get_fast_path (orig_method);
2932 if (method)
2933 add_method (acfg, method);
2934 #endif
2936 /* Stelemref wrappers */
2937 /* There is only a constant number of these, iterating over all types should handle them all */
2938 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2939 MonoClass *klass;
2941 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2942 klass = mono_class_get (acfg->image, token);
2943 if (klass)
2944 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2945 else
2946 mono_loader_clear_error ();
2949 /* castclass_with_check wrapper */
2950 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2951 /* isinst_with_check wrapper */
2952 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2954 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2956 MonoMethodDesc *desc;
2957 MonoMethod *m;
2959 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2960 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2961 mono_method_desc_free (desc);
2962 if (m) {
2963 m = mono_monitor_get_fast_path (m);
2964 if (m)
2965 add_method (acfg, m);
2968 #endif
2972 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2973 * we use the original method instead at runtime.
2974 * Since full-aot doesn't support remoting, this is not a problem.
2976 #if 0
2977 /* remoting-invoke wrappers */
2978 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2979 MonoMethodSignature *sig;
2981 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2982 method = mono_get_method (acfg->image, token, NULL);
2984 sig = mono_method_signature (method);
2986 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2987 m = mono_marshal_get_remoting_invoke_with_check (method);
2989 add_method (acfg, m);
2992 #endif
2994 /* delegate-invoke wrappers */
2995 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2996 MonoClass *klass;
2997 MonoCustomAttrInfo *cattr;
2999 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3000 klass = mono_class_get (acfg->image, token);
3002 if (!klass) {
3003 mono_loader_clear_error ();
3004 continue;
3007 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
3008 method = mono_get_delegate_invoke (klass);
3010 m = mono_marshal_get_delegate_invoke (method, NULL);
3012 add_method (acfg, m);
3014 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3015 if (method)
3016 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3018 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3019 if (method)
3020 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3022 cattr = mono_custom_attrs_from_class (klass);
3024 if (cattr) {
3025 int j;
3027 for (j = 0; j < cattr->num_attrs; ++j)
3028 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3029 break;
3030 if (j < cattr->num_attrs)
3031 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3036 /* Synchronized wrappers */
3037 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3038 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3039 method = mono_get_method (acfg->image, token, NULL);
3041 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3042 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3045 /* pinvoke wrappers */
3046 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3047 MonoMethod *method;
3048 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3050 method = mono_get_method (acfg->image, token, NULL);
3052 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3053 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3054 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3058 /* native-to-managed wrappers */
3059 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3060 MonoMethod *method;
3061 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3062 MonoCustomAttrInfo *cattr;
3063 int j;
3065 method = mono_get_method (acfg->image, token, NULL);
3068 * Only generate native-to-managed wrappers for methods which have an
3069 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3070 * name to avoid defining a new assembly to contain it.
3072 cattr = mono_custom_attrs_from_method (method);
3074 if (cattr) {
3075 for (j = 0; j < cattr->num_attrs; ++j)
3076 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3077 break;
3078 if (j < cattr->num_attrs) {
3079 MonoCustomAttrEntry *e = &cattr->attrs [j];
3080 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3081 const char *p = (const char*)e->data;
3082 const char *named;
3083 int slen, num_named, named_type, data_type;
3084 char *n;
3085 MonoType *t;
3086 MonoClass *klass;
3087 char *export_name = NULL;
3088 MonoMethod *wrapper;
3090 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3091 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3092 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3093 mono_method_full_name (method, TRUE));
3094 exit (1);
3097 g_assert (sig->param_count == 1);
3098 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3101 * Decode the cattr manually since we can't create objects
3102 * during aot compilation.
3105 /* Skip prolog */
3106 p += 2;
3108 /* From load_cattr_value () in reflection.c */
3109 slen = mono_metadata_decode_value (p, &p);
3110 n = g_memdup (p, slen + 1);
3111 n [slen] = 0;
3112 t = mono_reflection_type_from_name (n, acfg->image);
3113 g_assert (t);
3114 g_free (n);
3116 klass = mono_class_from_mono_type (t);
3117 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3119 p += slen;
3121 num_named = read16 (p);
3122 p += 2;
3124 g_assert (num_named < 2);
3125 if (num_named == 1) {
3126 int name_len;
3127 char *name;
3128 MonoType *prop_type;
3130 /* parse ExportSymbol attribute */
3131 named = p;
3132 named_type = *named;
3133 named += 1;
3134 data_type = *named;
3135 named += 1;
3137 name_len = mono_metadata_decode_blob_size (named, &named);
3138 name = g_malloc (name_len + 1);
3139 memcpy (name, named, name_len);
3140 name [name_len] = 0;
3141 named += name_len;
3143 g_assert (named_type == 0x54);
3144 g_assert (!strcmp (name, "ExportSymbol"));
3146 prop_type = &mono_defaults.string_class->byval_arg;
3148 /* load_cattr_value (), string case */
3149 g_assert (*named != (char)0xff);
3150 slen = mono_metadata_decode_value (named, &named);
3151 export_name = g_malloc (slen + 1);
3152 memcpy (export_name, named, slen);
3153 export_name [slen] = 0;
3154 named += slen;
3157 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3158 add_method (acfg, wrapper);
3159 if (export_name)
3160 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3164 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3165 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3166 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3170 /* StructureToPtr/PtrToStructure wrappers */
3171 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3172 MonoClass *klass;
3174 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3175 klass = mono_class_get (acfg->image, token);
3177 if (!klass) {
3178 mono_loader_clear_error ();
3179 continue;
3182 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3183 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3184 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3189 static gboolean
3190 has_type_vars (MonoClass *klass)
3192 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3193 return TRUE;
3194 if (klass->rank)
3195 return has_type_vars (klass->element_class);
3196 if (klass->generic_class) {
3197 MonoGenericContext *context = &klass->generic_class->context;
3198 if (context->class_inst) {
3199 int i;
3201 for (i = 0; i < context->class_inst->type_argc; ++i)
3202 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3203 return TRUE;
3206 return FALSE;
3209 static gboolean
3210 method_has_type_vars (MonoMethod *method)
3212 if (has_type_vars (method->klass))
3213 return TRUE;
3215 if (method->is_inflated) {
3216 MonoGenericContext *context = mono_method_get_context (method);
3217 if (context->method_inst) {
3218 int i;
3220 for (i = 0; i < context->method_inst->type_argc; ++i)
3221 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3222 return TRUE;
3225 return FALSE;
3228 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3230 static void
3231 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3233 /* This might lead to a huge code blowup so only do it if neccesary */
3234 if (!acfg->aot_opts.full_aot && !force)
3235 return;
3237 add_generic_class_with_depth (acfg, klass, 0, ref);
3240 static gboolean
3241 check_type_depth (MonoType *t, int depth)
3243 int i;
3245 if (depth > 8)
3246 return TRUE;
3248 switch (t->type) {
3249 case MONO_TYPE_GENERICINST: {
3250 MonoGenericClass *gklass = t->data.generic_class;
3251 MonoGenericInst *ginst = gklass->context.class_inst;
3253 if (ginst) {
3254 for (i = 0; i < ginst->type_argc; ++i) {
3255 if (check_type_depth (ginst->type_argv [i], depth + 1))
3256 return TRUE;
3259 break;
3261 default:
3262 break;
3265 return FALSE;
3269 * add_generic_class:
3271 * Add all methods of a generic class.
3273 static void
3274 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3276 MonoMethod *method;
3277 MonoClassField *field;
3278 gpointer iter;
3280 if (!acfg->ginst_hash)
3281 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3283 mono_class_init (klass);
3285 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3286 return;
3288 if (has_type_vars (klass))
3289 return;
3291 if (!klass->generic_class && !klass->rank)
3292 return;
3294 if (!acfg->ginst_hash)
3295 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3297 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3298 return;
3300 if (check_type_depth (&klass->byval_arg, 0))
3301 return;
3303 if (acfg->aot_opts.log_generics)
3304 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3306 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3308 iter = NULL;
3309 while ((method = mono_class_get_methods (klass, &iter))) {
3310 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3311 /* Already added */
3312 continue;
3314 if (method->is_generic)
3315 /* FIXME: */
3316 continue;
3319 * FIXME: Instances which are referenced by these methods are not added,
3320 * for example Array.Resize<int> for List<int>.Add ().
3322 add_extra_method_with_depth (acfg, method, depth + 1);
3325 iter = NULL;
3326 while ((field = mono_class_get_fields (klass, &iter))) {
3327 if (field->type->type == MONO_TYPE_GENERICINST)
3328 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3331 if (klass->delegate) {
3332 method = mono_get_delegate_invoke (klass);
3334 method = mono_marshal_get_delegate_invoke (method, NULL);
3336 if (acfg->aot_opts.log_generics)
3337 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3339 add_method (acfg, method);
3342 /* Add superclasses */
3343 if (klass->parent)
3344 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3347 * For ICollection<T>, add instances of the helper methods
3348 * in Array, since a T[] could be cast to ICollection<T>.
3350 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3351 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3352 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3353 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3354 gpointer iter;
3355 char *name_prefix;
3357 if (!strcmp (klass->name, "IEnumerator`1"))
3358 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3359 else
3360 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3362 /* Add the T[]/InternalEnumerator class */
3363 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3364 MonoClass *nclass;
3366 iter = NULL;
3367 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3368 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3369 break;
3371 g_assert (nclass);
3372 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3373 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3376 iter = NULL;
3377 while ((method = mono_class_get_methods (array_class, &iter))) {
3378 if (strstr (method->name, name_prefix)) {
3379 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3381 add_extra_method_with_depth (acfg, m, depth);
3385 g_free (name_prefix);
3388 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3389 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3390 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3391 MonoClass *icomparable, *gcomparer;
3392 MonoGenericContext ctx;
3393 MonoType *args [16];
3395 memset (&ctx, 0, sizeof (ctx));
3397 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3398 g_assert (icomparable);
3399 args [0] = &tclass->byval_arg;
3400 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3402 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3403 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3404 g_assert (gcomparer);
3405 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3409 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3410 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3411 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3412 MonoClass *iface, *gcomparer;
3413 MonoGenericContext ctx;
3414 MonoType *args [16];
3416 memset (&ctx, 0, sizeof (ctx));
3418 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3419 g_assert (iface);
3420 args [0] = &tclass->byval_arg;
3421 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3423 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3424 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3425 g_assert (gcomparer);
3426 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3431 static void
3432 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3434 int i;
3435 MonoGenericContext ctx;
3436 MonoType *args [16];
3438 memset (&ctx, 0, sizeof (ctx));
3440 for (i = 0; i < ninsts; ++i) {
3441 args [0] = insts [i];
3442 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3443 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3447 static void
3448 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3450 MonoMethodHeader *header;
3451 MonoMethodSignature *sig;
3452 int j, depth;
3454 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3456 sig = mono_method_signature (method);
3458 if (sig) {
3459 for (j = 0; j < sig->param_count; ++j)
3460 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3461 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3464 header = mono_method_get_header (method);
3466 if (header) {
3467 for (j = 0; j < header->num_locals; ++j)
3468 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3469 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3474 * add_generic_instances:
3476 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3478 static void
3479 add_generic_instances (MonoAotCompile *acfg)
3481 int i;
3482 guint32 token;
3483 MonoMethod *method;
3484 MonoGenericContext *context;
3486 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3487 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3488 method = mono_get_method (acfg->image, token, NULL);
3490 if (!method)
3491 continue;
3493 if (method->klass->image != acfg->image)
3494 continue;
3496 context = mono_method_get_context (method);
3498 if (context && ((context->class_inst && context->class_inst->is_open)))
3499 continue;
3502 * For open methods, create an instantiation which can be passed to the JIT.
3503 * FIXME: Handle class_inst as well.
3505 if (context && context->method_inst && context->method_inst->is_open) {
3506 MonoGenericContext shared_context;
3507 MonoGenericInst *inst;
3508 MonoType **type_argv;
3509 int i;
3510 MonoMethod *declaring_method;
3511 gboolean supported = TRUE;
3513 /* Check that the context doesn't contain open constructed types */
3514 if (context->class_inst) {
3515 inst = context->class_inst;
3516 for (i = 0; i < inst->type_argc; ++i) {
3517 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)
3518 continue;
3519 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3520 supported = FALSE;
3523 if (context->method_inst) {
3524 inst = context->method_inst;
3525 for (i = 0; i < inst->type_argc; ++i) {
3526 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)
3527 continue;
3528 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3529 supported = FALSE;
3533 if (!supported)
3534 continue;
3536 memset (&shared_context, 0, sizeof (MonoGenericContext));
3538 inst = context->class_inst;
3539 if (inst) {
3540 type_argv = g_new0 (MonoType*, inst->type_argc);
3541 for (i = 0; i < inst->type_argc; ++i) {
3542 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)
3543 type_argv [i] = &mono_defaults.object_class->byval_arg;
3544 else
3545 type_argv [i] = inst->type_argv [i];
3548 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3549 g_free (type_argv);
3552 inst = context->method_inst;
3553 if (inst) {
3554 type_argv = g_new0 (MonoType*, inst->type_argc);
3555 for (i = 0; i < inst->type_argc; ++i) {
3556 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)
3557 type_argv [i] = &mono_defaults.object_class->byval_arg;
3558 else
3559 type_argv [i] = inst->type_argv [i];
3562 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3563 g_free (type_argv);
3566 if (method->is_generic || method->klass->generic_container)
3567 declaring_method = method;
3568 else
3569 declaring_method = mono_method_get_declaring_generic_method (method);
3571 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3575 * If the method is fully sharable, it was already added in place of its
3576 * generic definition.
3578 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3579 continue;
3582 * FIXME: Partially shared methods are not shared here, so we end up with
3583 * many identical methods.
3585 add_extra_method (acfg, method);
3588 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3589 MonoClass *klass;
3591 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3593 klass = mono_class_get (acfg->image, token);
3594 if (!klass || klass->rank) {
3595 mono_loader_clear_error ();
3596 continue;
3599 add_generic_class (acfg, klass, FALSE, "typespec");
3602 /* Add types of args/locals */
3603 for (i = 0; i < acfg->methods->len; ++i) {
3604 method = g_ptr_array_index (acfg->methods, i);
3605 add_types_from_method_header (acfg, method);
3608 if (acfg->image == mono_defaults.corlib) {
3609 MonoClass *klass;
3610 MonoType *insts [256];
3611 int ninsts = 0;
3613 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3614 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3615 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3616 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3617 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3618 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3619 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3620 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3621 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3622 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3623 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3624 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3626 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3627 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3628 if (klass)
3629 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3630 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3631 if (klass)
3632 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3634 /* Add instances of the array generic interfaces for primitive types */
3635 /* This will add instances of the InternalArray_ helper methods in Array too */
3636 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3637 if (klass)
3638 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3639 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3640 if (klass)
3641 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3642 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3643 if (klass)
3644 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3647 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3648 * used for all instances of GetGenericValueImpl by the AOT runtime.
3651 MonoGenericContext ctx;
3652 MonoType *args [16];
3653 MonoMethod *get_method;
3654 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3656 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3658 if (get_method) {
3659 memset (&ctx, 0, sizeof (ctx));
3660 args [0] = &mono_defaults.object_class->byval_arg;
3661 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3662 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3666 /* Same for CompareExchange<T>/Exchange<T> */
3668 MonoGenericContext ctx;
3669 MonoType *args [16];
3670 MonoMethod *m;
3671 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3672 gpointer iter = NULL;
3674 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3675 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3676 memset (&ctx, 0, sizeof (ctx));
3677 args [0] = &mono_defaults.object_class->byval_arg;
3678 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3679 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3687 * is_direct_callable:
3689 * Return whenever the method identified by JI is directly callable without
3690 * going through the PLT.
3692 static gboolean
3693 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3695 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3696 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3697 if (callee_cfg) {
3698 gboolean direct_callable = TRUE;
3700 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3701 direct_callable = FALSE;
3702 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3703 // FIXME: Maybe call the wrapper directly ?
3704 direct_callable = FALSE;
3706 if (acfg->aot_opts.soft_debug) {
3707 /* Disable this so all calls go through load_method (), see the
3708 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
3709 * mono_debugger_agent_init ().
3711 direct_callable = FALSE;
3714 if (direct_callable)
3715 return TRUE;
3717 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3718 if (acfg->aot_opts.direct_pinvoke)
3719 return TRUE;
3720 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3721 if (acfg->aot_opts.direct_icalls)
3722 return TRUE;
3723 return FALSE;
3726 return FALSE;
3729 static const char *
3730 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3732 MonoImage *image = method->klass->image;
3733 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3734 MonoTableInfo *tables = image->tables;
3735 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3736 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3737 guint32 im_cols [MONO_IMPLMAP_SIZE];
3738 char *import;
3740 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3741 if (import != NULL)
3742 return import;
3744 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3745 return NULL;
3747 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3749 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3750 return NULL;
3752 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3754 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3756 return import;
3760 * emit_and_reloc_code:
3762 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3763 * is true, calls are made through the GOT too. This is used for emitting trampolines
3764 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3765 * since trampolines are needed to make PTL work.
3767 static void
3768 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3770 int i, pindex, start_index, method_index;
3771 GPtrArray *patches;
3772 MonoJumpInfo *patch_info;
3773 MonoMethodHeader *header;
3774 gboolean skip, direct_call;
3775 guint32 got_slot;
3776 char direct_call_target [1024];
3777 const char *direct_pinvoke;
3779 if (method) {
3780 header = mono_method_get_header (method);
3782 method_index = get_method_index (acfg, method);
3785 /* Collect and sort relocations */
3786 patches = g_ptr_array_new ();
3787 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3788 g_ptr_array_add (patches, patch_info);
3789 g_ptr_array_sort (patches, compare_patches);
3791 start_index = 0;
3792 for (i = 0; i < code_len; i++) {
3793 patch_info = NULL;
3794 for (pindex = start_index; pindex < patches->len; ++pindex) {
3795 patch_info = g_ptr_array_index (patches, pindex);
3796 if (patch_info->ip.i >= i)
3797 break;
3800 #ifdef MONO_ARCH_AOT_SUPPORTED
3801 skip = FALSE;
3802 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3803 start_index = pindex;
3805 switch (patch_info->type) {
3806 case MONO_PATCH_INFO_NONE:
3807 break;
3808 case MONO_PATCH_INFO_GOT_OFFSET: {
3809 int code_size;
3811 arch_emit_got_offset (acfg, code + i, &code_size);
3812 i += code_size - 1;
3813 skip = TRUE;
3814 patch_info->type = MONO_PATCH_INFO_NONE;
3815 break;
3817 default: {
3819 * If this patch is a call, try emitting a direct call instead of
3820 * through a PLT entry. This is possible if the called method is in
3821 * the same assembly and requires no initialization.
3823 direct_call = FALSE;
3824 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3825 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3826 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3827 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3828 direct_call = TRUE;
3829 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3830 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3833 acfg->stats.all_calls ++;
3834 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3835 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3836 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
3837 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
3838 else
3839 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3840 if (direct_pinvoke) {
3841 const char*prefix;
3842 #if defined(TARGET_MACH)
3843 prefix = "_";
3844 #else
3845 prefix = "";
3846 #endif
3847 direct_call = TRUE;
3848 g_assert (strlen (direct_pinvoke) < 1000);
3849 sprintf (direct_call_target, "%s%s", prefix, direct_pinvoke);
3854 if (direct_call) {
3855 patch_info->type = MONO_PATCH_INFO_NONE;
3856 acfg->stats.direct_calls ++;
3859 if (!got_only && !direct_call) {
3860 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3861 if (plt_entry) {
3862 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3863 direct_call = TRUE;
3864 sprintf (direct_call_target, "%s", plt_entry->symbol);
3866 /* Nullify the patch */
3867 patch_info->type = MONO_PATCH_INFO_NONE;
3868 plt_entry->jit_used = TRUE;
3872 if (direct_call) {
3873 int call_size;
3875 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3876 i += call_size - 1;
3877 } else {
3878 int code_size;
3880 got_slot = get_got_offset (acfg, patch_info);
3882 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3883 i += code_size - 1;
3885 skip = TRUE;
3889 #endif /* MONO_ARCH_AOT_SUPPORTED */
3891 if (!skip) {
3892 /* Find next patch */
3893 patch_info = NULL;
3894 for (pindex = start_index; pindex < patches->len; ++pindex) {
3895 patch_info = g_ptr_array_index (patches, pindex);
3896 if (patch_info->ip.i >= i)
3897 break;
3900 /* Try to emit multiple bytes at once */
3901 if (pindex < patches->len && patch_info->ip.i > i) {
3902 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3903 i = patch_info->ip.i - 1;
3904 } else {
3905 emit_bytes (acfg, code + i, 1);
3912 * sanitize_symbol:
3914 * Modify SYMBOL so it only includes characters permissible in symbols.
3916 static void
3917 sanitize_symbol (char *symbol)
3919 int i, len = strlen (symbol);
3921 for (i = 0; i < len; ++i)
3922 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3923 symbol [i] = '_';
3926 static char*
3927 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3929 char *name1, *name2, *cached;
3930 int i, j, len, count;
3932 name1 = mono_method_full_name (method, TRUE);
3933 len = strlen (name1);
3934 name2 = malloc (strlen (prefix) + len + 16);
3935 memcpy (name2, prefix, strlen (prefix));
3936 j = strlen (prefix);
3937 for (i = 0; i < len; ++i) {
3938 if (isalnum (name1 [i])) {
3939 name2 [j ++] = name1 [i];
3940 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3941 i += 2;
3942 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3943 name2 [j ++] = '_';
3944 i++;
3945 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3946 } else
3947 name2 [j ++] = '_';
3949 name2 [j] = '\0';
3951 g_free (name1);
3953 count = 0;
3954 while (g_hash_table_lookup (cache, name2)) {
3955 sprintf (name2 + j, "_%d", count);
3956 count ++;
3959 cached = g_strdup (name2);
3960 g_hash_table_insert (cache, cached, cached);
3962 return name2;
3965 static void
3966 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3968 MonoMethod *method;
3969 int method_index;
3970 guint8 *code;
3971 char *debug_sym = NULL;
3972 char symbol [128];
3973 int func_alignment = AOT_FUNC_ALIGNMENT;
3974 MonoMethodHeader *header;
3975 char *export_name;
3977 method = cfg->orig_method;
3978 code = cfg->native_code;
3979 header = cfg->header;
3981 method_index = get_method_index (acfg, method);
3983 /* Make the labels local */
3984 sprintf (symbol, "%s", cfg->asm_symbol);
3986 emit_section_change (acfg, ".text", 0);
3987 emit_alignment (acfg, func_alignment);
3988 emit_label (acfg, symbol);
3990 if (acfg->aot_opts.write_symbols) {
3992 * Write a C style symbol for every method, this has two uses:
3993 * - it works on platforms where the dwarf debugging info is not
3994 * yet supported.
3995 * - it allows the setting of breakpoints of aot-ed methods.
3997 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3999 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
4000 if (acfg->need_no_dead_strip)
4001 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4002 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4003 emit_label (acfg, debug_sym);
4006 export_name = g_hash_table_lookup (acfg->export_names, method);
4007 if (export_name) {
4008 /* Emit a global symbol for the method */
4009 emit_global_inner (acfg, export_name, TRUE);
4010 emit_label (acfg, export_name);
4013 if (cfg->verbose_level > 0)
4014 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
4016 acfg->stats.code_size += cfg->code_len;
4018 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4020 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
4022 emit_line (acfg);
4024 if (acfg->aot_opts.write_symbols) {
4025 emit_symbol_size (acfg, debug_sym, ".");
4026 g_free (debug_sym);
4029 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
4030 emit_label (acfg, symbol);
4034 * encode_patch:
4036 * Encode PATCH_INFO into its disk representation.
4038 static void
4039 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4041 guint8 *p = buf;
4043 switch (patch_info->type) {
4044 case MONO_PATCH_INFO_NONE:
4045 break;
4046 case MONO_PATCH_INFO_IMAGE:
4047 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4048 break;
4049 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4050 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4051 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4052 break;
4053 case MONO_PATCH_INFO_METHOD_REL:
4054 encode_value ((gint)patch_info->data.offset, p, &p);
4055 break;
4056 case MONO_PATCH_INFO_SWITCH: {
4057 gpointer *table = (gpointer *)patch_info->data.table->table;
4058 int k;
4060 encode_value (patch_info->data.table->table_size, p, &p);
4061 for (k = 0; k < patch_info->data.table->table_size; k++)
4062 encode_value ((int)(gssize)table [k], p, &p);
4063 break;
4065 case MONO_PATCH_INFO_METHODCONST:
4066 case MONO_PATCH_INFO_METHOD:
4067 case MONO_PATCH_INFO_METHOD_JUMP:
4068 case MONO_PATCH_INFO_ICALL_ADDR:
4069 case MONO_PATCH_INFO_METHOD_RGCTX:
4070 encode_method_ref (acfg, patch_info->data.method, p, &p);
4071 break;
4072 case MONO_PATCH_INFO_INTERNAL_METHOD:
4073 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4074 guint32 len = strlen (patch_info->data.name);
4076 encode_value (len, p, &p);
4078 memcpy (p, patch_info->data.name, len);
4079 p += len;
4080 *p++ = '\0';
4081 break;
4083 case MONO_PATCH_INFO_LDSTR: {
4084 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4085 guint32 token = patch_info->data.token->token;
4086 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4087 encode_value (image_index, p, &p);
4088 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4089 break;
4091 case MONO_PATCH_INFO_RVA:
4092 case MONO_PATCH_INFO_DECLSEC:
4093 case MONO_PATCH_INFO_LDTOKEN:
4094 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4095 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4096 encode_value (patch_info->data.token->token, p, &p);
4097 encode_value (patch_info->data.token->has_context, p, &p);
4098 if (patch_info->data.token->has_context)
4099 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4100 break;
4101 case MONO_PATCH_INFO_EXC_NAME: {
4102 MonoClass *ex_class;
4104 ex_class =
4105 mono_class_from_name (mono_defaults.exception_class->image,
4106 "System", patch_info->data.target);
4107 g_assert (ex_class);
4108 encode_klass_ref (acfg, ex_class, p, &p);
4109 break;
4111 case MONO_PATCH_INFO_R4:
4112 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4113 break;
4114 case MONO_PATCH_INFO_R8:
4115 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4116 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4117 break;
4118 case MONO_PATCH_INFO_VTABLE:
4119 case MONO_PATCH_INFO_CLASS:
4120 case MONO_PATCH_INFO_IID:
4121 case MONO_PATCH_INFO_ADJUSTED_IID:
4122 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4123 break;
4124 case MONO_PATCH_INFO_CLASS_INIT:
4125 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4126 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4127 break;
4128 case MONO_PATCH_INFO_FIELD:
4129 case MONO_PATCH_INFO_SFLDA:
4130 encode_field_info (acfg, patch_info->data.field, p, &p);
4131 break;
4132 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4133 break;
4134 case MONO_PATCH_INFO_RGCTX_FETCH: {
4135 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4136 guint32 offset;
4137 guint8 *buf2, *p2;
4140 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4141 * reference the same method, so encode the method only once.
4143 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4144 if (!offset) {
4145 buf2 = g_malloc (1024);
4146 p2 = buf2;
4148 encode_method_ref (acfg, entry->method, p2, &p2);
4149 g_assert (p2 - buf2 < 1024);
4151 offset = add_to_blob (acfg, buf2, p2 - buf2);
4152 g_free (buf2);
4154 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4155 } else {
4156 offset --;
4159 encode_value (offset, p, &p);
4160 g_assert (entry->info_type < 256);
4161 g_assert (entry->data->type < 256);
4162 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4163 encode_patch (acfg, entry->data, p, &p);
4164 break;
4166 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4167 case MONO_PATCH_INFO_MONITOR_ENTER:
4168 case MONO_PATCH_INFO_MONITOR_EXIT:
4169 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4170 break;
4171 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4172 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4173 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4174 break;
4175 case MONO_PATCH_INFO_SIGNATURE:
4176 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4177 break;
4178 default:
4179 g_warning ("unable to handle jump info %d", patch_info->type);
4180 g_assert_not_reached ();
4183 *endbuf = p;
4186 static void
4187 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4189 guint8 *p = buf;
4190 guint32 pindex, offset;
4191 MonoJumpInfo *patch_info;
4193 encode_value (n_patches, p, &p);
4195 for (pindex = 0; pindex < patches->len; ++pindex) {
4196 patch_info = g_ptr_array_index (patches, pindex);
4198 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4199 /* Nothing to do */
4200 continue;
4202 offset = get_got_offset (acfg, patch_info);
4203 encode_value (offset, p, &p);
4206 *endbuf = p;
4209 static void
4210 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4212 MonoMethod *method;
4213 GList *l;
4214 int pindex, buf_size, n_patches;
4215 GPtrArray *patches;
4216 MonoJumpInfo *patch_info;
4217 MonoMethodHeader *header;
4218 guint32 method_index;
4219 guint8 *p, *buf;
4220 guint32 first_got_offset;
4222 method = cfg->orig_method;
4223 header = mono_method_get_header (method);
4225 method_index = get_method_index (acfg, method);
4227 /* Sort relocations */
4228 patches = g_ptr_array_new ();
4229 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4230 g_ptr_array_add (patches, patch_info);
4231 g_ptr_array_sort (patches, compare_patches);
4233 first_got_offset = acfg->cfgs [method_index]->got_offset;
4235 /**********************/
4236 /* Encode method info */
4237 /**********************/
4239 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4240 p = buf = g_malloc (buf_size);
4242 if (mono_class_get_cctor (method->klass))
4243 encode_klass_ref (acfg, method->klass, p, &p);
4244 else
4245 /* Not needed when loading the method */
4246 encode_value (0, p, &p);
4248 /* String table */
4249 if (cfg->opt & MONO_OPT_SHARED) {
4250 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4251 for (l = cfg->ldstr_list; l; l = l->next) {
4252 encode_value ((long)l->data, p, &p);
4255 else
4256 /* Used only in shared mode */
4257 g_assert (!cfg->ldstr_list);
4259 n_patches = 0;
4260 for (pindex = 0; pindex < patches->len; ++pindex) {
4261 patch_info = g_ptr_array_index (patches, pindex);
4263 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4264 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4265 patch_info->type = MONO_PATCH_INFO_NONE;
4266 /* Nothing to do */
4267 continue;
4270 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4271 /* Stored in a GOT slot initialized at module load time */
4272 patch_info->type = MONO_PATCH_INFO_NONE;
4273 continue;
4276 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4277 /* Stored in a GOT slot initialized at module load time */
4278 patch_info->type = MONO_PATCH_INFO_NONE;
4279 continue;
4282 if (is_plt_patch (patch_info)) {
4283 /* Calls are made through the PLT */
4284 patch_info->type = MONO_PATCH_INFO_NONE;
4285 continue;
4288 n_patches ++;
4291 if (n_patches)
4292 g_assert (cfg->has_got_slots);
4294 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4296 acfg->stats.info_size += p - buf;
4298 g_assert (p - buf < buf_size);
4300 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4301 g_free (buf);
4304 static guint32
4305 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4307 guint32 cache_index;
4308 guint32 offset;
4310 /* Reuse the unwind module to canonize and store unwind info entries */
4311 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4313 /* Use +/- 1 to distinguish 0s from missing entries */
4314 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4315 if (offset)
4316 return offset - 1;
4317 else {
4318 guint8 buf [16];
4319 guint8 *p;
4322 * It would be easier to use assembler symbols, but the caller needs an
4323 * offset now.
4325 offset = acfg->unwind_info_offset;
4326 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4327 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4329 p = buf;
4330 encode_value (encoded_len, p, &p);
4332 acfg->unwind_info_offset += encoded_len + (p - buf);
4333 return offset;
4337 static void
4338 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4340 MonoMethod *method;
4341 int i, k, buf_size, method_index;
4342 guint32 debug_info_size;
4343 guint8 *code;
4344 MonoMethodHeader *header;
4345 guint8 *p, *buf, *debug_info;
4346 MonoJitInfo *jinfo = cfg->jit_info;
4347 guint32 flags;
4348 gboolean use_unwind_ops = FALSE;
4349 MonoSeqPointInfo *seq_points;
4351 method = cfg->orig_method;
4352 code = cfg->native_code;
4353 header = cfg->header;
4355 method_index = get_method_index (acfg, method);
4357 if (!acfg->aot_opts.nodebug) {
4358 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4359 } else {
4360 debug_info = NULL;
4361 debug_info_size = 0;
4364 seq_points = cfg->seq_point_info;
4366 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4367 p = buf = g_malloc (buf_size);
4369 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4370 use_unwind_ops = cfg->unwind_ops != NULL;
4371 #endif
4373 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 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);
4375 encode_value (flags, p, &p);
4377 if (use_unwind_ops) {
4378 guint32 encoded_len;
4379 guint8 *encoded;
4382 * This is a duplicate of the data in the .debug_frame section, but that
4383 * section cannot be accessed using the dl interface.
4385 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4386 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4387 g_free (encoded);
4388 } else {
4389 encode_value (jinfo->used_regs, p, &p);
4392 /*Encode the number of holes before the number of clauses to make decoding easier*/
4393 if (jinfo->has_try_block_holes) {
4394 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4395 encode_value (table->num_holes, p, &p);
4398 /* Exception table */
4399 if (cfg->compile_llvm) {
4401 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4402 * since the information is only available to llc. Instead, we let llc save the data
4403 * into the LSDA, and read it from there at runtime.
4405 /* The assembly might be CIL stripped so emit the data ourselves */
4406 if (header->num_clauses)
4407 encode_value (header->num_clauses, p, &p);
4409 for (k = 0; k < header->num_clauses; ++k) {
4410 MonoExceptionClause *clause;
4412 clause = &header->clauses [k];
4414 encode_value (clause->flags, p, &p);
4415 if (clause->data.catch_class) {
4416 encode_value (1, p, &p);
4417 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4418 } else {
4419 encode_value (0, p, &p);
4422 /* Emit a list of nesting clauses */
4423 for (i = 0; i < header->num_clauses; ++i) {
4424 gint32 cindex1 = k;
4425 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4426 gint32 cindex2 = i;
4427 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4429 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4430 encode_value (i, p, &p);
4432 encode_value (-1, p, &p);
4434 } else {
4435 if (jinfo->num_clauses)
4436 encode_value (jinfo->num_clauses, p, &p);
4438 for (k = 0; k < jinfo->num_clauses; ++k) {
4439 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4441 encode_value (ei->flags, p, &p);
4442 encode_value (ei->exvar_offset, p, &p);
4444 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4445 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4446 else {
4447 if (ei->data.catch_class) {
4448 encode_value (1, p, &p);
4449 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4450 } else {
4451 encode_value (0, p, &p);
4455 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4456 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4457 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4461 if (jinfo->has_generic_jit_info) {
4462 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4463 guint8 *p1;
4465 p1 = p;
4466 encode_value (gi->nlocs, p, &p);
4467 if (gi->nlocs) {
4468 for (i = 0; i < gi->nlocs; ++i) {
4469 MonoDwarfLocListEntry *entry = &gi->locations [i];
4471 encode_value (entry->is_reg ? 1 : 0, p, &p);
4472 encode_value (entry->reg, p, &p);
4473 if (!entry->is_reg)
4474 encode_value (entry->offset, p, &p);
4475 if (i == 0)
4476 g_assert (entry->from == 0);
4477 else
4478 encode_value (entry->from, p, &p);
4479 encode_value (entry->to, p, &p);
4481 } else {
4482 if (!cfg->compile_llvm) {
4483 encode_value (gi->has_this ? 1 : 0, p, &p);
4484 encode_value (gi->this_reg, p, &p);
4485 encode_value (gi->this_offset, p, &p);
4490 * Need to encode jinfo->method too, since it is not equal to 'method'
4491 * when using generic sharing.
4493 encode_method_ref (acfg, jinfo->method, p, &p);
4496 if (jinfo->has_try_block_holes) {
4497 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4498 for (i = 0; i < table->num_holes; ++i) {
4499 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4500 encode_value (hole->clause, p, &p);
4501 encode_value (hole->length, p, &p);
4502 encode_value (hole->offset, p, &p);
4506 if (jinfo->has_arch_eh_info) {
4507 MonoArchEHJitInfo *eh_info;
4509 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4510 encode_value (eh_info->stack_size, p, &p);
4513 if (seq_points) {
4514 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4516 encode_value (seq_points->len, p, &p);
4517 last_il_offset = last_native_offset = 0;
4518 for (i = 0; i < seq_points->len; ++i) {
4519 SeqPoint *sp = &seq_points->seq_points [i];
4520 il_offset = sp->il_offset;
4521 native_offset = sp->native_offset;
4522 encode_value (il_offset - last_il_offset, p, &p);
4523 encode_value (native_offset - last_native_offset, p, &p);
4524 last_il_offset = il_offset;
4525 last_native_offset = native_offset;
4527 encode_value (sp->next_len, p, &p);
4528 for (j = 0; j < sp->next_len; ++j)
4529 encode_value (sp->next [j], p, &p);
4533 g_assert (debug_info_size < buf_size);
4535 encode_value (debug_info_size, p, &p);
4536 if (debug_info_size) {
4537 memcpy (p, debug_info, debug_info_size);
4538 p += debug_info_size;
4539 g_free (debug_info);
4542 /* GC Map */
4543 if (cfg->gc_map) {
4544 encode_value (cfg->gc_map_size, p, &p);
4545 /* The GC map requires 4 bytes of alignment */
4546 while ((gsize)p % 4)
4547 p ++;
4548 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4549 p += cfg->gc_map_size;
4552 acfg->stats.ex_info_size += p - buf;
4554 g_assert (p - buf < buf_size);
4556 /* Emit info */
4557 /* The GC Map requires 4 byte alignment */
4558 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4559 g_free (buf);
4562 static guint32
4563 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4565 MonoClass *klass = mono_class_get (acfg->image, token);
4566 guint8 *p, *buf;
4567 int i, buf_size, res;
4568 gboolean no_special_static, cant_encode;
4569 gpointer iter = NULL;
4571 if (!klass) {
4572 mono_loader_clear_error ();
4574 buf_size = 16;
4576 p = buf = g_malloc (buf_size);
4578 /* Mark as unusable */
4579 encode_value (-1, p, &p);
4581 res = add_to_blob (acfg, buf, p - buf);
4582 g_free (buf);
4584 return res;
4587 buf_size = 10240 + (klass->vtable_size * 16);
4588 p = buf = g_malloc (buf_size);
4590 g_assert (klass);
4592 mono_class_init (klass);
4594 mono_class_get_nested_types (klass, &iter);
4595 g_assert (klass->nested_classes_inited);
4597 mono_class_setup_vtable (klass);
4600 * Emit all the information which is required for creating vtables so
4601 * the runtime does not need to create the MonoMethod structures which
4602 * take up a lot of space.
4605 no_special_static = !mono_class_has_special_static_fields (klass);
4607 /* Check whenever we have enough info to encode the vtable */
4608 cant_encode = FALSE;
4609 for (i = 0; i < klass->vtable_size; ++i) {
4610 MonoMethod *cm = klass->vtable [i];
4612 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4613 cant_encode = TRUE;
4616 mono_class_has_finalizer (klass);
4618 if (klass->generic_container || cant_encode) {
4619 encode_value (-1, p, &p);
4620 } else {
4621 encode_value (klass->vtable_size, p, &p);
4622 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
4623 if (klass->has_cctor)
4624 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4625 if (klass->has_finalize)
4626 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4628 encode_value (klass->instance_size, p, &p);
4629 encode_value (mono_class_data_size (klass), p, &p);
4630 encode_value (klass->packing_size, p, &p);
4631 encode_value (klass->min_align, p, &p);
4633 for (i = 0; i < klass->vtable_size; ++i) {
4634 MonoMethod *cm = klass->vtable [i];
4636 if (cm)
4637 encode_method_ref (acfg, cm, p, &p);
4638 else
4639 encode_value (0, p, &p);
4643 acfg->stats.class_info_size += p - buf;
4645 g_assert (p - buf < buf_size);
4646 res = add_to_blob (acfg, buf, p - buf);
4647 g_free (buf);
4649 return res;
4652 static char*
4653 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4655 char *debug_sym = NULL;
4657 switch (ji->type) {
4658 case MONO_PATCH_INFO_METHOD:
4659 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4660 break;
4661 case MONO_PATCH_INFO_INTERNAL_METHOD:
4662 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4663 break;
4664 case MONO_PATCH_INFO_CLASS_INIT:
4665 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4666 sanitize_symbol (debug_sym);
4667 break;
4668 case MONO_PATCH_INFO_RGCTX_FETCH:
4669 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4670 break;
4671 case MONO_PATCH_INFO_ICALL_ADDR: {
4672 char *s = get_debug_sym (ji->data.method, "", cache);
4674 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4675 g_free (s);
4676 break;
4678 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4679 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4680 break;
4681 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4682 debug_sym = g_strdup_printf ("plt__generic_class_init");
4683 break;
4684 default:
4685 break;
4688 return debug_sym;
4692 * Calls made from AOTed code are routed through a table of jumps similar to the
4693 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4694 * control to the AOT runtime through a trampoline.
4696 static void
4697 emit_plt (MonoAotCompile *acfg)
4699 char symbol [128];
4700 int i;
4702 emit_line (acfg);
4703 sprintf (symbol, "plt");
4705 emit_section_change (acfg, ".text", 0);
4706 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4707 emit_label (acfg, symbol);
4708 emit_label (acfg, acfg->plt_symbol);
4710 for (i = 0; i < acfg->plt_offset; ++i) {
4711 char *debug_sym = NULL;
4712 MonoPltEntry *plt_entry = NULL;
4713 MonoJumpInfo *ji;
4715 if (i == 0)
4717 * The first plt entry is unused.
4719 continue;
4721 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4722 ji = plt_entry->ji;
4724 if (acfg->llvm) {
4726 * If the target is directly callable, alias the plt symbol to point to
4727 * the method code.
4728 * FIXME: Use this to simplify emit_and_reloc_code ().
4729 * FIXME: Avoid the got slot.
4730 * FIXME: Add support to the binary writer.
4732 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4733 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4735 if (callee_cfg) {
4736 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4737 /* LLVM calls the PLT entries using bl, so emit a stub */
4738 fprintf (acfg->fp, "\n.thumb_func\n");
4739 emit_label (acfg, plt_entry->llvm_symbol);
4740 fprintf (acfg->fp, "bx pc\n");
4741 fprintf (acfg->fp, "nop\n");
4742 fprintf (acfg->fp, ".arm\n");
4743 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4744 } else {
4745 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4747 continue;
4752 debug_sym = plt_entry->debug_sym;
4754 if (acfg->thumb_mixed && !plt_entry->jit_used)
4755 /* Emit only a thumb version */
4756 continue;
4758 if (!acfg->thumb_mixed)
4759 emit_label (acfg, plt_entry->llvm_symbol);
4761 if (debug_sym) {
4762 if (acfg->need_no_dead_strip)
4763 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4764 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4765 emit_label (acfg, debug_sym);
4768 emit_label (acfg, plt_entry->symbol);
4770 arch_emit_plt_entry (acfg, i);
4772 if (debug_sym)
4773 emit_symbol_size (acfg, debug_sym, ".");
4776 if (acfg->thumb_mixed) {
4777 /* Make sure the ARM symbols don't alias the thumb ones */
4778 emit_zero_bytes (acfg, 16);
4781 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4782 * code.
4784 for (i = 0; i < acfg->plt_offset; ++i) {
4785 char *debug_sym = NULL;
4786 MonoPltEntry *plt_entry = NULL;
4787 MonoJumpInfo *ji;
4789 if (i == 0)
4790 continue;
4792 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4793 ji = plt_entry->ji;
4795 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4796 continue;
4798 /* Skip plt entries not actually called by LLVM code */
4799 if (!plt_entry->llvm_used)
4800 continue;
4802 if (acfg->aot_opts.write_symbols) {
4803 if (plt_entry->debug_sym)
4804 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4807 if (debug_sym) {
4808 #if defined(TARGET_MACH)
4809 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4810 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4811 #endif
4812 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4813 emit_label (acfg, debug_sym);
4815 fprintf (acfg->fp, "\n.thumb_func\n");
4817 emit_label (acfg, plt_entry->llvm_symbol);
4819 arch_emit_llvm_plt_entry (acfg, i);
4821 if (debug_sym) {
4822 emit_symbol_size (acfg, debug_sym, ".");
4823 g_free (debug_sym);
4828 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4830 sprintf (symbol, "plt_end");
4831 emit_label (acfg, symbol);
4834 static G_GNUC_UNUSED void
4835 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4837 char start_symbol [256];
4838 char symbol [256];
4839 guint32 buf_size, info_offset;
4840 MonoJumpInfo *patch_info;
4841 guint8 *buf, *p;
4842 GPtrArray *patches;
4843 char *name;
4844 guint8 *code;
4845 guint32 code_size;
4846 MonoJumpInfo *ji;
4847 GSList *unwind_ops;
4849 name = info->name;
4850 code = info->code;
4851 code_size = info->code_size;
4852 ji = info->ji;
4853 unwind_ops = info->unwind_ops;
4855 #ifdef __native_client_codegen__
4856 mono_nacl_fix_patches (code, ji);
4857 #endif
4859 /* Emit code */
4861 sprintf (start_symbol, "%s", name);
4863 emit_section_change (acfg, ".text", 0);
4864 emit_global (acfg, start_symbol, TRUE);
4865 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4866 emit_label (acfg, start_symbol);
4868 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4869 emit_label (acfg, symbol);
4872 * The code should access everything through the GOT, so we pass
4873 * TRUE here.
4875 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4877 emit_symbol_size (acfg, start_symbol, ".");
4879 /* Emit info */
4881 /* Sort relocations */
4882 patches = g_ptr_array_new ();
4883 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4884 if (patch_info->type != MONO_PATCH_INFO_NONE)
4885 g_ptr_array_add (patches, patch_info);
4886 g_ptr_array_sort (patches, compare_patches);
4888 buf_size = patches->len * 128 + 128;
4889 buf = g_malloc (buf_size);
4890 p = buf;
4892 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4893 g_assert (p - buf < buf_size);
4895 sprintf (symbol, "%s_p", name);
4897 info_offset = add_to_blob (acfg, buf, p - buf);
4899 emit_section_change (acfg, RODATA_SECT, 0);
4900 emit_global (acfg, symbol, FALSE);
4901 emit_label (acfg, symbol);
4903 emit_int32 (acfg, info_offset);
4905 /* Emit debug info */
4906 if (unwind_ops) {
4907 char symbol2 [256];
4909 sprintf (symbol, "%s", name);
4910 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4912 if (acfg->dwarf)
4913 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4917 static void
4918 emit_trampolines (MonoAotCompile *acfg)
4920 char symbol [256];
4921 char end_symbol [256];
4922 int i, tramp_got_offset;
4923 MonoAotTrampoline ntype;
4924 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4925 int tramp_type;
4926 #endif
4928 if (!acfg->aot_opts.full_aot)
4929 return;
4931 g_assert (acfg->image->assembly);
4933 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4934 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4935 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4936 MonoTrampInfo *info;
4939 * Emit the generic trampolines.
4941 * We could save some code by treating the generic trampolines as a wrapper
4942 * method, but that approach has its own complexities, so we choose the simpler
4943 * method.
4945 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4946 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4947 emit_trampoline (acfg, acfg->got_offset, info);
4950 mono_arch_get_nullified_class_init_trampoline (&info);
4951 emit_trampoline (acfg, acfg->got_offset, info);
4952 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4953 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4954 emit_trampoline (acfg, acfg->got_offset, info);
4955 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4956 emit_trampoline (acfg, acfg->got_offset, info);
4957 #endif
4959 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4960 emit_trampoline (acfg, acfg->got_offset, info);
4962 /* Emit the exception related code pieces */
4963 mono_arch_get_restore_context (&info, TRUE);
4964 emit_trampoline (acfg, acfg->got_offset, info);
4965 mono_arch_get_call_filter (&info, TRUE);
4966 emit_trampoline (acfg, acfg->got_offset, info);
4967 mono_arch_get_throw_exception (&info, TRUE);
4968 emit_trampoline (acfg, acfg->got_offset, info);
4969 mono_arch_get_rethrow_exception (&info, TRUE);
4970 emit_trampoline (acfg, acfg->got_offset, info);
4971 mono_arch_get_throw_corlib_exception (&info, TRUE);
4972 emit_trampoline (acfg, acfg->got_offset, info);
4974 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4976 GSList *l = mono_arch_get_trampolines (TRUE);
4978 while (l) {
4979 MonoTrampInfo *info = l->data;
4981 emit_trampoline (acfg, acfg->got_offset, info);
4982 l = l->next;
4985 #endif
4987 for (i = 0; i < 128; ++i) {
4988 int offset;
4990 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4991 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4992 emit_trampoline (acfg, acfg->got_offset, info);
4994 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4995 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4996 emit_trampoline (acfg, acfg->got_offset, info);
5000 GSList *l;
5002 /* delegate_invoke_impl trampolines */
5003 l = mono_arch_get_delegate_invoke_impls ();
5004 while (l) {
5005 MonoTrampInfo *info = l->data;
5007 emit_trampoline (acfg, acfg->got_offset, info);
5008 l = l->next;
5012 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5014 /* Emit trampolines which are numerous */
5017 * These include the following:
5018 * - specific trampolines
5019 * - static rgctx invoke trampolines
5020 * - imt thunks
5021 * These trampolines have the same code, they are parameterized by GOT
5022 * slots.
5023 * They are defined in this file, in the arch_... routines instead of
5024 * in tramp-<ARCH>.c, since it is easier to do it this way.
5028 * When running in aot-only mode, we can't create specific trampolines at
5029 * runtime, so we create a few, and save them in the AOT file.
5030 * Normal trampolines embed their argument as a literal inside the
5031 * trampoline code, we can't do that here, so instead we embed an offset
5032 * which needs to be added to the trampoline address to get the address of
5033 * the GOT slot which contains the argument value.
5034 * The generated trampolines jump to the generic trampolines using another
5035 * GOT slot, which will be setup by the AOT loader to point to the
5036 * generic trampoline code of the given type.
5040 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5041 * each class).
5044 emit_section_change (acfg, ".text", 0);
5046 tramp_got_offset = acfg->got_offset;
5048 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5049 switch (ntype) {
5050 case MONO_AOT_TRAMP_SPECIFIC:
5051 sprintf (symbol, "specific_trampolines");
5052 break;
5053 case MONO_AOT_TRAMP_STATIC_RGCTX:
5054 sprintf (symbol, "static_rgctx_trampolines");
5055 break;
5056 case MONO_AOT_TRAMP_IMT_THUNK:
5057 sprintf (symbol, "imt_thunks");
5058 break;
5059 default:
5060 g_assert_not_reached ();
5063 sprintf (end_symbol, "%s_e", symbol);
5065 if (acfg->aot_opts.write_symbols)
5066 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5068 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5069 emit_label (acfg, symbol);
5071 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5073 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5074 int tramp_size = 0;
5076 switch (ntype) {
5077 case MONO_AOT_TRAMP_SPECIFIC:
5078 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5079 tramp_got_offset += 2;
5080 break;
5081 case MONO_AOT_TRAMP_STATIC_RGCTX:
5082 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5083 tramp_got_offset += 2;
5084 break;
5085 case MONO_AOT_TRAMP_IMT_THUNK:
5086 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5087 tramp_got_offset += 1;
5088 break;
5089 default:
5090 g_assert_not_reached ();
5092 #ifdef __native_client_codegen__
5093 /* align to avoid 32-byte boundary crossings */
5094 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5095 #endif
5097 if (!acfg->trampoline_size [ntype]) {
5098 g_assert (tramp_size);
5099 acfg->trampoline_size [ntype] = tramp_size;
5103 emit_label (acfg, end_symbol);
5106 /* Reserve some entries at the end of the GOT for our use */
5107 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5110 acfg->got_offset += acfg->num_trampoline_got_entries;
5113 static gboolean
5114 str_begins_with (const char *str1, const char *str2)
5116 int len = strlen (str2);
5117 return strncmp (str1, str2, len) == 0;
5120 void*
5121 mono_aot_readonly_field_override (MonoClassField *field)
5123 ReadOnlyValue *rdv;
5124 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5125 char *p = rdv->name;
5126 int len;
5127 len = strlen (field->parent->name_space);
5128 if (strncmp (p, field->parent->name_space, len))
5129 continue;
5130 p += len;
5131 if (*p++ != '.')
5132 continue;
5133 len = strlen (field->parent->name);
5134 if (strncmp (p, field->parent->name, len))
5135 continue;
5136 p += len;
5137 if (*p++ != '.')
5138 continue;
5139 if (strcmp (p, field->name))
5140 continue;
5141 switch (rdv->type) {
5142 case MONO_TYPE_I1:
5143 return &rdv->value.i1;
5144 case MONO_TYPE_I2:
5145 return &rdv->value.i2;
5146 case MONO_TYPE_I4:
5147 return &rdv->value.i4;
5148 default:
5149 break;
5152 return NULL;
5155 static void
5156 add_readonly_value (MonoAotOptions *opts, const char *val)
5158 ReadOnlyValue *rdv;
5159 const char *fval;
5160 const char *tval;
5161 /* the format of val is:
5162 * namespace.typename.fieldname=type/value
5163 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5165 fval = strrchr (val, '/');
5166 if (!fval) {
5167 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5168 exit (1);
5170 tval = strrchr (val, '=');
5171 if (!tval) {
5172 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5173 exit (1);
5175 rdv = g_new0 (ReadOnlyValue, 1);
5176 rdv->name = g_malloc0 (tval - val + 1);
5177 memcpy (rdv->name, val, tval - val);
5178 tval++;
5179 fval++;
5180 if (strncmp (tval, "i1", 2) == 0) {
5181 rdv->value.i1 = atoi (fval);
5182 rdv->type = MONO_TYPE_I1;
5183 } else if (strncmp (tval, "i2", 2) == 0) {
5184 rdv->value.i2 = atoi (fval);
5185 rdv->type = MONO_TYPE_I2;
5186 } else if (strncmp (tval, "i4", 2) == 0) {
5187 rdv->value.i4 = atoi (fval);
5188 rdv->type = MONO_TYPE_I4;
5189 } else {
5190 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5191 exit (1);
5193 rdv->next = readonly_values;
5194 readonly_values = rdv;
5197 static void
5198 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5200 gchar **args, **ptr;
5202 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5203 for (ptr = args; ptr && *ptr; ptr ++) {
5204 const char *arg = *ptr;
5206 if (str_begins_with (arg, "outfile=")) {
5207 opts->outfile = g_strdup (arg + strlen ("outfile="));
5208 } else if (str_begins_with (arg, "save-temps")) {
5209 opts->save_temps = TRUE;
5210 } else if (str_begins_with (arg, "keep-temps")) {
5211 opts->save_temps = TRUE;
5212 } else if (str_begins_with (arg, "write-symbols")) {
5213 opts->write_symbols = TRUE;
5214 } else if (str_begins_with (arg, "no-write-symbols")) {
5215 opts->write_symbols = FALSE;
5216 } else if (str_begins_with (arg, "metadata-only")) {
5217 opts->metadata_only = TRUE;
5218 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5219 opts->bind_to_runtime_version = TRUE;
5220 } else if (str_begins_with (arg, "full")) {
5221 opts->full_aot = TRUE;
5222 } else if (str_begins_with (arg, "threads=")) {
5223 opts->nthreads = atoi (arg + strlen ("threads="));
5224 } else if (str_begins_with (arg, "static")) {
5225 opts->static_link = TRUE;
5226 opts->no_dlsym = TRUE;
5227 } else if (str_begins_with (arg, "asmonly")) {
5228 opts->asm_only = TRUE;
5229 } else if (str_begins_with (arg, "asmwriter")) {
5230 opts->asm_writer = TRUE;
5231 } else if (str_begins_with (arg, "nodebug")) {
5232 opts->nodebug = TRUE;
5233 } else if (str_begins_with (arg, "ntrampolines=")) {
5234 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5235 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5236 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5237 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5238 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5239 } else if (str_begins_with (arg, "autoreg")) {
5240 opts->autoreg = TRUE;
5241 } else if (str_begins_with (arg, "tool-prefix=")) {
5242 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5243 } else if (str_begins_with (arg, "soft-debug")) {
5244 opts->soft_debug = TRUE;
5245 } else if (str_begins_with (arg, "direct-pinvoke")) {
5246 opts->direct_pinvoke = TRUE;
5247 } else if (str_begins_with (arg, "direct-icalls")) {
5248 opts->direct_icalls = TRUE;
5249 #if defined(TARGET_ARM)
5250 } else if (str_begins_with (arg, "iphone-abi")) {
5251 // older full-aot users did depend on this.
5252 #endif
5253 } else if (str_begins_with (arg, "print-skipped")) {
5254 opts->print_skipped_methods = TRUE;
5255 } else if (str_begins_with (arg, "stats")) {
5256 opts->stats = TRUE;
5257 } else if (str_begins_with (arg, "log-generics")) {
5258 opts->log_generics = TRUE;
5259 } else if (str_begins_with (arg, "mtriple=")) {
5260 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5261 } else if (str_begins_with (arg, "llvm-path=")) {
5262 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5263 } else if (str_begins_with (arg, "readonly-value=")) {
5264 add_readonly_value (opts, arg + strlen ("readonly-value="));
5265 } else if (str_begins_with (arg, "info")) {
5266 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5267 exit (0);
5268 } else if (str_begins_with (arg, "gc-maps")) {
5269 mini_gc_enable_gc_maps_for_aot ();
5270 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5271 printf ("Supported options for --aot:\n");
5272 printf (" outfile=\n");
5273 printf (" save-temps\n");
5274 printf (" keep-temps\n");
5275 printf (" write-symbols\n");
5276 printf (" metadata-only\n");
5277 printf (" bind-to-runtime-version\n");
5278 printf (" full\n");
5279 printf (" threads=\n");
5280 printf (" static\n");
5281 printf (" asmonly\n");
5282 printf (" asmwriter\n");
5283 printf (" nodebug\n");
5284 printf (" ntrampolines=\n");
5285 printf (" nrgctx-trampolines=\n");
5286 printf (" nimt-trampolines=\n");
5287 printf (" autoreg\n");
5288 printf (" tool-prefix=\n");
5289 printf (" readonly-value=\n");
5290 printf (" soft-debug\n");
5291 printf (" gc-maps\n");
5292 printf (" print-skipped\n");
5293 printf (" stats\n");
5294 printf (" info\n");
5295 printf (" help/?\n");
5296 exit (0);
5297 } else {
5298 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5299 exit (1);
5303 g_strfreev (args);
5306 static void
5307 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5309 MonoMethod *method = (MonoMethod*)key;
5310 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5311 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5312 MonoAotCompile *acfg = user_data;
5314 new_ji->image = ji->image;
5315 new_ji->token = ji->token;
5316 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5319 static gboolean
5320 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5322 if (klass->type_token)
5323 return TRUE;
5324 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5325 return TRUE;
5326 if (klass->rank)
5327 return can_encode_class (acfg, klass->element_class);
5328 return FALSE;
5331 static gboolean
5332 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5334 switch (patch_info->type) {
5335 case MONO_PATCH_INFO_METHOD:
5336 case MONO_PATCH_INFO_METHODCONST: {
5337 MonoMethod *method = patch_info->data.method;
5339 if (method->wrapper_type) {
5340 switch (method->wrapper_type) {
5341 case MONO_WRAPPER_NONE:
5342 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5343 case MONO_WRAPPER_XDOMAIN_INVOKE:
5344 case MONO_WRAPPER_STFLD:
5345 case MONO_WRAPPER_LDFLD:
5346 case MONO_WRAPPER_LDFLDA:
5347 case MONO_WRAPPER_LDFLD_REMOTE:
5348 case MONO_WRAPPER_STFLD_REMOTE:
5349 case MONO_WRAPPER_STELEMREF:
5350 case MONO_WRAPPER_ISINST:
5351 case MONO_WRAPPER_PROXY_ISINST:
5352 case MONO_WRAPPER_ALLOC:
5353 case MONO_WRAPPER_REMOTING_INVOKE:
5354 case MONO_WRAPPER_UNKNOWN:
5355 case MONO_WRAPPER_WRITE_BARRIER:
5356 break;
5357 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5358 case MONO_WRAPPER_CASTCLASS: {
5359 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5361 if (info)
5362 return TRUE;
5363 else
5364 return FALSE;
5365 break;
5367 default:
5368 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5369 return FALSE;
5371 } else {
5372 if (!method->token) {
5373 /* The method is part of a constructed type like Int[,].Set (). */
5374 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5375 if (method->klass->rank)
5376 return TRUE;
5377 return FALSE;
5381 break;
5383 case MONO_PATCH_INFO_VTABLE:
5384 case MONO_PATCH_INFO_CLASS_INIT:
5385 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5386 case MONO_PATCH_INFO_CLASS:
5387 case MONO_PATCH_INFO_IID:
5388 case MONO_PATCH_INFO_ADJUSTED_IID:
5389 if (!can_encode_class (acfg, patch_info->data.klass)) {
5390 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5391 return FALSE;
5393 break;
5394 case MONO_PATCH_INFO_RGCTX_FETCH: {
5395 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5397 if (!can_encode_patch (acfg, entry->data))
5398 return FALSE;
5399 break;
5401 default:
5402 break;
5405 return TRUE;
5409 * compile_method:
5411 * AOT compile a given method.
5412 * This function might be called by multiple threads, so it must be thread-safe.
5414 static void
5415 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5417 MonoCompile *cfg;
5418 MonoJumpInfo *patch_info;
5419 gboolean skip;
5420 int index, depth;
5421 MonoMethod *wrapped;
5423 if (acfg->aot_opts.metadata_only)
5424 return;
5426 mono_acfg_lock (acfg);
5427 index = get_method_index (acfg, method);
5428 mono_acfg_unlock (acfg);
5430 /* fixme: maybe we can also precompile wrapper methods */
5431 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5432 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5433 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5434 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5435 return;
5438 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5439 return;
5441 wrapped = mono_marshal_method_from_wrapper (method);
5442 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5443 // FIXME: The wrapper should be generic too, but it is not
5444 return;
5446 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5447 return;
5449 InterlockedIncrement (&acfg->stats.mcount);
5451 #if 0
5452 if (method->is_generic || method->klass->generic_container) {
5453 InterlockedIncrement (&acfg->stats.genericcount);
5454 return;
5456 #endif
5458 //acfg->aot_opts.print_skipped_methods = TRUE;
5461 * Since these methods are the only ones which are compiled with
5462 * AOT support, and they are not used by runtime startup/shutdown code,
5463 * the runtime will not see AOT methods during AOT compilation,so it
5464 * does not need to support them by creating a fake GOT etc.
5466 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5467 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5468 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5469 InterlockedIncrement (&acfg->stats.genericcount);
5470 return;
5472 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5473 if (acfg->aot_opts.print_skipped_methods)
5474 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5475 /* Let the exception happen at runtime */
5476 return;
5479 if (cfg->disable_aot) {
5480 if (acfg->aot_opts.print_skipped_methods)
5481 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5482 InterlockedIncrement (&acfg->stats.ocount);
5483 mono_destroy_compile (cfg);
5484 return;
5487 /* Nullify patches which need no aot processing */
5488 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5489 switch (patch_info->type) {
5490 case MONO_PATCH_INFO_LABEL:
5491 case MONO_PATCH_INFO_BB:
5492 patch_info->type = MONO_PATCH_INFO_NONE;
5493 break;
5494 default:
5495 break;
5499 /* Collect method->token associations from the cfg */
5500 mono_acfg_lock (acfg);
5501 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5502 mono_acfg_unlock (acfg);
5505 * Check for absolute addresses.
5507 skip = FALSE;
5508 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5509 switch (patch_info->type) {
5510 case MONO_PATCH_INFO_ABS:
5511 /* unable to handle this */
5512 skip = TRUE;
5513 break;
5514 default:
5515 break;
5519 if (skip) {
5520 if (acfg->aot_opts.print_skipped_methods)
5521 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5522 InterlockedIncrement (&acfg->stats.abscount);
5523 mono_destroy_compile (cfg);
5524 return;
5527 /* Lock for the rest of the code */
5528 mono_acfg_lock (acfg);
5531 * Check for methods/klasses we can't encode.
5533 skip = FALSE;
5534 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5535 if (!can_encode_patch (acfg, patch_info))
5536 skip = TRUE;
5539 if (skip) {
5540 if (acfg->aot_opts.print_skipped_methods)
5541 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5542 acfg->stats.ocount++;
5543 mono_destroy_compile (cfg);
5544 mono_acfg_unlock (acfg);
5545 return;
5548 /* Adds generic instances referenced by this method */
5550 * The depth is used to avoid infinite loops when generic virtual recursion is
5551 * encountered.
5553 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5554 if (depth < 32) {
5555 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5556 switch (patch_info->type) {
5557 case MONO_PATCH_INFO_METHOD: {
5558 MonoMethod *m = patch_info->data.method;
5559 if (m->is_inflated) {
5560 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5561 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5562 !method_has_type_vars (m)) {
5563 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5564 if (acfg->aot_opts.full_aot)
5565 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5566 } else {
5567 add_extra_method_with_depth (acfg, m, depth + 1);
5568 add_types_from_method_header (acfg, m);
5571 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5573 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5574 add_extra_method_with_depth (acfg, m, depth + 1);
5575 break;
5577 case MONO_PATCH_INFO_VTABLE: {
5578 MonoClass *klass = patch_info->data.klass;
5580 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5581 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5582 break;
5584 case MONO_PATCH_INFO_SFLDA: {
5585 MonoClass *klass = patch_info->data.field->parent;
5587 /* The .cctor needs to run at runtime. */
5588 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5589 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5590 break;
5592 default:
5593 break;
5598 /* Determine whenever the method has GOT slots */
5599 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5600 switch (patch_info->type) {
5601 case MONO_PATCH_INFO_GOT_OFFSET:
5602 case MONO_PATCH_INFO_NONE:
5603 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5604 break;
5605 case MONO_PATCH_INFO_IMAGE:
5606 /* The assembly is stored in GOT slot 0 */
5607 if (patch_info->data.image != acfg->image)
5608 cfg->has_got_slots = TRUE;
5609 break;
5610 default:
5611 if (!is_plt_patch (patch_info))
5612 cfg->has_got_slots = TRUE;
5613 break;
5617 if (!cfg->has_got_slots)
5618 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5621 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5623 /* Make a copy of the patch info which is in the mempool */
5625 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5627 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5628 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5630 if (!patches)
5631 patches = new_patch_info;
5632 else
5633 patches_end->next = new_patch_info;
5634 patches_end = new_patch_info;
5636 cfg->patch_info = patches;
5638 /* Make a copy of the unwind info */
5640 GSList *l, *unwind_ops;
5641 MonoUnwindOp *op;
5643 unwind_ops = NULL;
5644 for (l = cfg->unwind_ops; l; l = l->next) {
5645 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5646 memcpy (op, l->data, sizeof (MonoUnwindOp));
5647 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5649 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5651 /* Make a copy of the argument/local info */
5653 MonoInst **args, **locals;
5654 MonoMethodSignature *sig;
5655 MonoMethodHeader *header;
5656 int i;
5658 sig = mono_method_signature (method);
5659 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5660 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5661 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5662 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5664 cfg->args = args;
5666 header = mono_method_get_header (method);
5667 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5668 for (i = 0; i < header->num_locals; ++i) {
5669 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5670 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5672 cfg->locals = locals;
5675 /* Free some fields used by cfg to conserve memory */
5676 mono_mempool_destroy (cfg->mempool);
5677 cfg->mempool = NULL;
5678 g_free (cfg->varinfo);
5679 cfg->varinfo = NULL;
5680 g_free (cfg->vars);
5681 cfg->vars = NULL;
5682 if (cfg->rs) {
5683 mono_regstate_free (cfg->rs);
5684 cfg->rs = NULL;
5687 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5689 while (index >= acfg->cfgs_size) {
5690 MonoCompile **new_cfgs;
5691 int new_size;
5693 new_size = acfg->cfgs_size * 2;
5694 new_cfgs = g_new0 (MonoCompile*, new_size);
5695 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5696 g_free (acfg->cfgs);
5697 acfg->cfgs = new_cfgs;
5698 acfg->cfgs_size = new_size;
5700 acfg->cfgs [index] = cfg;
5702 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5705 if (cfg->orig_method->wrapper_type)
5706 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5709 mono_acfg_unlock (acfg);
5711 InterlockedIncrement (&acfg->stats.ccount);
5714 static void
5715 compile_thread_main (gpointer *user_data)
5717 MonoDomain *domain = user_data [0];
5718 MonoAotCompile *acfg = user_data [1];
5719 GPtrArray *methods = user_data [2];
5720 int i;
5722 mono_thread_attach (domain);
5724 for (i = 0; i < methods->len; ++i)
5725 compile_method (acfg, g_ptr_array_index (methods, i));
5728 static void
5729 load_profile_files (MonoAotCompile *acfg)
5731 FILE *infile;
5732 char *tmp;
5733 int file_index, res, method_index, i;
5734 char ver [256];
5735 guint32 token;
5736 GList *unordered, *l;
5737 gboolean found;
5739 file_index = 0;
5740 while (TRUE) {
5741 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5743 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5744 g_free (tmp);
5745 break;
5748 infile = fopen (tmp, "r");
5749 g_assert (infile);
5751 printf ("Using profile data file '%s'\n", tmp);
5752 g_free (tmp);
5754 file_index ++;
5756 res = fscanf (infile, "%32s\n", ver);
5757 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5758 printf ("Profile file has wrong version or invalid.\n");
5759 fclose (infile);
5760 continue;
5763 while (TRUE) {
5764 char name [1024];
5765 MonoMethodDesc *desc;
5766 MonoMethod *method;
5768 if (fgets (name, 1023, infile) == NULL)
5769 break;
5771 /* Kill the newline */
5772 if (strlen (name) > 0)
5773 name [strlen (name) - 1] = '\0';
5775 desc = mono_method_desc_new (name, TRUE);
5777 method = mono_method_desc_search_in_image (desc, acfg->image);
5779 if (method && mono_method_get_token (method)) {
5780 token = mono_method_get_token (method);
5781 method_index = mono_metadata_token_index (token) - 1;
5783 found = FALSE;
5784 for (i = 0; i < acfg->method_order->len; ++i) {
5785 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5786 found = TRUE;
5787 break;
5790 if (!found)
5791 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5792 } else {
5793 //printf ("No method found matching '%s'.\n", name);
5796 fclose (infile);
5799 /* Add missing methods */
5800 unordered = NULL;
5801 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5802 found = FALSE;
5803 for (i = 0; i < acfg->method_order->len; ++i) {
5804 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5805 found = TRUE;
5806 break;
5809 if (!found)
5810 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5812 unordered = g_list_reverse (unordered);
5813 for (l = unordered; l; l = l->next)
5814 g_ptr_array_add (acfg->method_order, l->data);
5817 /* Used by the LLVM backend */
5818 guint32
5819 mono_aot_get_got_offset (MonoJumpInfo *ji)
5821 return get_got_offset (llvm_acfg, ji);
5824 char*
5825 mono_aot_get_method_name (MonoCompile *cfg)
5827 if (llvm_acfg->aot_opts.static_link)
5828 /* Include the assembly name too to avoid duplicate symbol errors */
5829 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5830 else
5831 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5834 char*
5835 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5837 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5838 MonoPltEntry *plt_entry;
5840 ji->type = type;
5841 ji->data.target = data;
5843 if (!can_encode_patch (llvm_acfg, ji))
5844 return NULL;
5846 plt_entry = get_plt_entry (llvm_acfg, ji);
5847 plt_entry->llvm_used = TRUE;
5849 #if defined(TARGET_MACH)
5850 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5851 #else
5852 return g_strdup_printf (plt_entry->llvm_symbol);
5853 #endif
5856 MonoJumpInfo*
5857 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5859 MonoJumpInfo *res;
5861 mono_acfg_lock (llvm_acfg);
5862 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5863 mono_acfg_unlock (llvm_acfg);
5865 return res;
5868 #ifdef ENABLE_LLVM
5871 * emit_llvm_file:
5873 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5874 * tools.
5876 static void
5877 emit_llvm_file (MonoAotCompile *acfg)
5879 char *command, *opts, *tempbc;
5880 int i;
5881 MonoJumpInfo *patch_info;
5884 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5885 * to it.
5888 /* Compute the final size of the got */
5889 for (i = 0; i < acfg->nmethods; ++i) {
5890 if (acfg->cfgs [i]) {
5891 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5892 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5893 if (!is_plt_patch (patch_info))
5894 get_got_offset (acfg, patch_info);
5895 else
5896 get_plt_entry (acfg, patch_info);
5902 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5904 if (acfg->aot_opts.full_aot) {
5905 int ntype;
5908 * Need to add the got entries used by the trampolines.
5909 * This is only a conservative approximation.
5911 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5912 /* For the generic + rgctx trampolines */
5913 acfg->final_got_size += 200;
5914 /* For the specific trampolines */
5915 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5916 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5921 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
5922 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
5923 g_free (tempbc);
5926 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5927 * a lot of time, and doesn't seem to save much space.
5928 * The following optimizations cannot be enabled:
5929 * - 'tailcallelim'
5930 * - 'jump-threading' changes our blockaddress references to int constants.
5931 * - 'basiccg' fails because it contains:
5932 * if (CS && !isa<IntrinsicInst>(II)) {
5933 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5934 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5935 * The opt list below was produced by taking the output of:
5936 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5937 * then removing tailcallelim + the global opts, and adding a second gvn.
5939 opts = g_strdup ("-instcombine -simplifycfg");
5940 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5941 #if 1
5942 command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
5943 printf ("Executing opt: %s\n", command);
5944 if (system (command) != 0) {
5945 exit (1);
5947 #endif
5948 g_free (opts);
5950 if (!acfg->llc_args)
5951 acfg->llc_args = g_string_new ("");
5953 /* Verbose asm slows down llc greatly */
5954 g_string_append (acfg->llc_args, " -asm-verbose=false");
5956 if (acfg->aot_opts.mtriple)
5957 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5959 if (llvm_acfg->aot_opts.static_link)
5960 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5961 else
5962 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5963 unlink (acfg->tmpfname);
5965 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s %s.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
5967 printf ("Executing llc: %s\n", command);
5969 if (system (command) != 0) {
5970 exit (1);
5973 #endif
5975 static void
5976 emit_code (MonoAotCompile *acfg)
5978 int oindex, i, prev_index;
5979 char symbol [256];
5980 char end_symbol [256];
5982 #if defined(TARGET_POWERPC64)
5983 sprintf (symbol, ".Lgot_addr");
5984 emit_section_change (acfg, ".text", 0);
5985 emit_alignment (acfg, 8);
5986 emit_label (acfg, symbol);
5987 emit_pointer (acfg, acfg->got_symbol);
5988 #endif
5991 * This global symbol is used to compute the address of each method using the
5992 * code_offsets array. It is also used to compute the memory ranges occupied by
5993 * AOT code, so it must be equal to the address of the first emitted method.
5995 sprintf (symbol, "methods");
5996 emit_section_change (acfg, ".text", 0);
5997 emit_alignment (acfg, 8);
5998 if (acfg->llvm) {
5999 for (i = 0; i < acfg->nmethods; ++i) {
6000 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6001 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6002 break;
6005 if (i == acfg->nmethods)
6006 /* No LLVM compiled methods */
6007 emit_label (acfg, symbol);
6008 } else {
6009 emit_label (acfg, symbol);
6013 * Emit some padding so the local symbol for the first method doesn't have the
6014 * same address as 'methods'.
6016 #if defined(__default_codegen__)
6017 emit_zero_bytes (acfg, 16);
6018 #elif defined(__native_client_codegen__)
6020 const int kPaddingSize = 16;
6021 guint8 pad_buffer[kPaddingSize];
6022 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6023 emit_bytes (acfg, pad_buffer, kPaddingSize);
6025 #endif
6027 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6028 MonoCompile *cfg;
6029 MonoMethod *method;
6031 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6033 cfg = acfg->cfgs [i];
6035 if (!cfg)
6036 continue;
6038 method = cfg->orig_method;
6040 /* Emit unbox trampoline */
6041 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6042 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6044 emit_section_change (acfg, ".text", 0);
6045 #ifdef __native_client_codegen__
6046 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6047 #endif
6049 if (acfg->thumb_mixed && cfg->compile_llvm)
6050 fprintf (acfg->fp, "\n.thumb_func\n");
6052 emit_label (acfg, symbol);
6054 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6057 if (cfg->compile_llvm)
6058 acfg->stats.llvm_count ++;
6059 else
6060 emit_method_code (acfg, cfg);
6063 sprintf (symbol, "methods_end");
6064 emit_section_change (acfg, ".text", 0);
6065 emit_alignment (acfg, 8);
6066 emit_label (acfg, symbol);
6069 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6070 * from optimizing them away, since it doesn't see that code_offsets references them.
6071 * JITted methods don't need this since they are referenced using assembler local
6072 * symbols.
6073 * FIXME: This is why write-symbols doesn't work on OSX ?
6075 if (acfg->llvm && acfg->need_no_dead_strip) {
6076 fprintf (acfg->fp, "\n");
6077 for (i = 0; i < acfg->nmethods; ++i) {
6078 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6079 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6083 sprintf (symbol, "code_offsets");
6084 emit_section_change (acfg, RODATA_SECT, 1);
6085 emit_alignment (acfg, 8);
6086 emit_label (acfg, symbol);
6088 acfg->stats.offsets_size += acfg->nmethods * 4;
6090 sprintf (end_symbol, "methods");
6091 for (i = 0; i < acfg->nmethods; ++i) {
6092 if (acfg->cfgs [i]) {
6093 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6094 } else {
6095 emit_int32 (acfg, 0xffffffff);
6098 emit_line (acfg);
6100 /* Emit a sorted table mapping methods to their unbox trampolines */
6101 sprintf (symbol, "unbox_trampolines");
6102 emit_section_change (acfg, RODATA_SECT, 1);
6103 emit_alignment (acfg, 8);
6104 emit_label (acfg, symbol);
6106 sprintf (end_symbol, "methods");
6107 prev_index = -1;
6108 for (i = 0; i < acfg->nmethods; ++i) {
6109 MonoCompile *cfg;
6110 MonoMethod *method;
6111 int index;
6113 cfg = acfg->cfgs [i];
6114 if (!cfg)
6115 continue;
6117 method = cfg->orig_method;
6119 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6120 index = get_method_index (acfg, method);
6121 sprintf (symbol, "ut_%d", index);
6123 emit_int32 (acfg, index);
6124 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6125 /* Make sure the table is sorted by index */
6126 g_assert (index > prev_index);
6127 prev_index = index;
6130 sprintf (symbol, "unbox_trampolines_end");
6131 emit_label (acfg, symbol);
6134 static void
6135 emit_info (MonoAotCompile *acfg)
6137 int oindex, i;
6138 char symbol [256];
6139 gint32 *offsets;
6141 offsets = g_new0 (gint32, acfg->nmethods);
6143 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6144 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6146 if (acfg->cfgs [i]) {
6147 emit_method_info (acfg, acfg->cfgs [i]);
6148 offsets [i] = acfg->cfgs [i]->method_info_offset;
6149 } else {
6150 offsets [i] = 0;
6154 sprintf (symbol, "method_info_offsets");
6155 emit_section_change (acfg, RODATA_SECT, 1);
6156 emit_alignment (acfg, 8);
6157 emit_label (acfg, symbol);
6159 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6161 g_free (offsets);
6164 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6166 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6167 #define mix(a,b,c) { \
6168 a -= c; a ^= rot(c, 4); c += b; \
6169 b -= a; b ^= rot(a, 6); a += c; \
6170 c -= b; c ^= rot(b, 8); b += a; \
6171 a -= c; a ^= rot(c,16); c += b; \
6172 b -= a; b ^= rot(a,19); a += c; \
6173 c -= b; c ^= rot(b, 4); b += a; \
6175 #define final(a,b,c) { \
6176 c ^= b; c -= rot(b,14); \
6177 a ^= c; a -= rot(c,11); \
6178 b ^= a; b -= rot(a,25); \
6179 c ^= b; c -= rot(b,16); \
6180 a ^= c; a -= rot(c,4); \
6181 b ^= a; b -= rot(a,14); \
6182 c ^= b; c -= rot(b,24); \
6185 static guint
6186 mono_aot_type_hash (MonoType *t1)
6188 guint hash = t1->type;
6190 hash |= t1->byref << 6; /* do not collide with t1->type values */
6191 switch (t1->type) {
6192 case MONO_TYPE_VALUETYPE:
6193 case MONO_TYPE_CLASS:
6194 case MONO_TYPE_SZARRAY:
6195 /* check if the distribution is good enough */
6196 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6197 case MONO_TYPE_PTR:
6198 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6199 case MONO_TYPE_ARRAY:
6200 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6201 case MONO_TYPE_GENERICINST:
6202 return ((hash << 5) - hash) ^ 0;
6203 default:
6204 return hash;
6209 * mono_aot_method_hash:
6211 * Return a hash code for methods which only depends on metadata.
6213 guint32
6214 mono_aot_method_hash (MonoMethod *method)
6216 MonoMethodSignature *sig;
6217 MonoClass *klass;
6218 int i, hindex;
6219 int hashes_count;
6220 guint32 *hashes_start, *hashes;
6221 guint32 a, b, c;
6222 MonoGenericInst *ginst = NULL;
6224 /* Similar to the hash in mono_method_get_imt_slot () */
6226 sig = mono_method_signature (method);
6228 if (method->is_inflated)
6229 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6231 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6232 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6233 hashes = hashes_start;
6235 /* Some wrappers are assigned to random classes */
6236 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6237 klass = method->klass;
6238 else
6239 klass = mono_defaults.object_class;
6241 if (!method->wrapper_type) {
6242 char *full_name = mono_type_full_name (&klass->byval_arg);
6244 hashes [0] = mono_metadata_str_hash (full_name);
6245 hashes [1] = 0;
6246 g_free (full_name);
6247 } else {
6248 hashes [0] = mono_metadata_str_hash (klass->name);
6249 hashes [1] = mono_metadata_str_hash (klass->name_space);
6251 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6252 /* The method name includes a stringified pointer */
6253 hashes [2] = 0;
6254 else
6255 hashes [2] = mono_metadata_str_hash (method->name);
6256 hashes [3] = method->wrapper_type;
6257 hashes [4] = mono_aot_type_hash (sig->ret);
6258 hindex = 5;
6259 for (i = 0; i < sig->param_count; i++) {
6260 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6262 if (ginst) {
6263 for (i = 0; i < ginst->type_argc; ++i)
6264 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6266 g_assert (hindex == hashes_count);
6268 /* Setup internal state */
6269 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6271 /* Handle most of the hashes */
6272 while (hashes_count > 3) {
6273 a += hashes [0];
6274 b += hashes [1];
6275 c += hashes [2];
6276 mix (a,b,c);
6277 hashes_count -= 3;
6278 hashes += 3;
6281 /* Handle the last 3 hashes (all the case statements fall through) */
6282 switch (hashes_count) {
6283 case 3 : c += hashes [2];
6284 case 2 : b += hashes [1];
6285 case 1 : a += hashes [0];
6286 final (a,b,c);
6287 case 0: /* nothing left to add */
6288 break;
6291 free (hashes_start);
6293 return c;
6295 #undef rot
6296 #undef mix
6297 #undef final
6300 * mono_aot_wrapper_name:
6302 * Return a string which uniqely identifies the given wrapper method.
6304 char*
6305 mono_aot_wrapper_name (MonoMethod *method)
6307 char *name, *tmpsig, *klass_desc;
6309 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6311 switch (method->wrapper_type) {
6312 case MONO_WRAPPER_RUNTIME_INVOKE:
6313 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6314 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6315 else
6316 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6317 break;
6318 default:
6319 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6320 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6321 g_free (klass_desc);
6322 break;
6325 g_free (tmpsig);
6327 return name;
6331 * mono_aot_get_array_helper_from_wrapper;
6333 * Get the helper method in Array called by an array wrapper method.
6335 MonoMethod*
6336 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6338 MonoMethod *m;
6339 const char *prefix;
6340 MonoGenericContext ctx;
6341 MonoType *args [16];
6342 char *mname, *iname, *s, *s2, *helper_name = NULL;
6344 prefix = "System.Collections.Generic";
6345 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6346 s2 = strstr (s, "`1.");
6347 g_assert (s2);
6348 s2 [0] = '\0';
6349 iname = s;
6350 mname = s2 + 3;
6352 //printf ("X: %s %s\n", iname, mname);
6354 if (!strcmp (iname, "IList"))
6355 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6356 else
6357 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6358 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6359 g_assert (m);
6360 g_free (helper_name);
6361 g_free (s);
6363 if (m->is_generic) {
6364 memset (&ctx, 0, sizeof (ctx));
6365 args [0] = &method->klass->element_class->byval_arg;
6366 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6367 m = mono_class_inflate_generic_method (m, &ctx);
6370 return m;
6373 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6375 typedef struct HashEntry {
6376 guint32 key, value, index;
6377 struct HashEntry *next;
6378 } HashEntry;
6381 * emit_extra_methods:
6383 * Emit methods which are not in the METHOD table, like wrappers.
6385 static void
6386 emit_extra_methods (MonoAotCompile *acfg)
6388 int i, table_size, buf_size;
6389 char symbol [256];
6390 guint8 *p, *buf;
6391 guint32 *info_offsets;
6392 guint32 hash;
6393 GPtrArray *table;
6394 HashEntry *entry, *new_entry;
6395 int nmethods, max_chain_length;
6396 int *chain_lengths;
6398 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6400 /* Emit method info */
6401 nmethods = 0;
6402 for (i = 0; i < acfg->extra_methods->len; ++i) {
6403 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6404 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6406 if (!cfg)
6407 continue;
6409 buf_size = 10240;
6410 p = buf = g_malloc (buf_size);
6412 nmethods ++;
6414 method = cfg->method_to_register;
6416 encode_method_ref (acfg, method, p, &p);
6418 g_assert ((p - buf) < buf_size);
6420 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6421 g_free (buf);
6425 * Construct a chained hash table for mapping indexes in extra_method_info to
6426 * method indexes.
6428 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6429 table = g_ptr_array_sized_new (table_size);
6430 for (i = 0; i < table_size; ++i)
6431 g_ptr_array_add (table, NULL);
6432 chain_lengths = g_new0 (int, table_size);
6433 max_chain_length = 0;
6434 for (i = 0; i < acfg->extra_methods->len; ++i) {
6435 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6436 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6437 guint32 key, value;
6439 if (!cfg)
6440 continue;
6442 key = info_offsets [i];
6443 value = get_method_index (acfg, method);
6445 hash = mono_aot_method_hash (method) % table_size;
6447 chain_lengths [hash] ++;
6448 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6450 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6451 new_entry->key = key;
6452 new_entry->value = value;
6454 entry = g_ptr_array_index (table, hash);
6455 if (entry == NULL) {
6456 new_entry->index = hash;
6457 g_ptr_array_index (table, hash) = new_entry;
6458 } else {
6459 while (entry->next)
6460 entry = entry->next;
6462 entry->next = new_entry;
6463 new_entry->index = table->len;
6464 g_ptr_array_add (table, new_entry);
6468 //printf ("MAX: %d\n", max_chain_length);
6470 /* Emit the table */
6471 sprintf (symbol, "extra_method_table");
6472 emit_section_change (acfg, RODATA_SECT, 0);
6473 emit_alignment (acfg, 8);
6474 emit_label (acfg, symbol);
6476 emit_int32 (acfg, table_size);
6477 for (i = 0; i < table->len; ++i) {
6478 HashEntry *entry = g_ptr_array_index (table, i);
6480 if (entry == NULL) {
6481 emit_int32 (acfg, 0);
6482 emit_int32 (acfg, 0);
6483 emit_int32 (acfg, 0);
6484 } else {
6485 //g_assert (entry->key > 0);
6486 emit_int32 (acfg, entry->key);
6487 emit_int32 (acfg, entry->value);
6488 if (entry->next)
6489 emit_int32 (acfg, entry->next->index);
6490 else
6491 emit_int32 (acfg, 0);
6496 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6497 * This is used by mono_aot_find_jit_info ().
6499 sprintf (symbol, "extra_method_info_offsets");
6500 emit_section_change (acfg, RODATA_SECT, 0);
6501 emit_alignment (acfg, 8);
6502 emit_label (acfg, symbol);
6504 emit_int32 (acfg, acfg->extra_methods->len);
6505 for (i = 0; i < acfg->extra_methods->len; ++i) {
6506 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6508 emit_int32 (acfg, get_method_index (acfg, method));
6509 emit_int32 (acfg, info_offsets [i]);
6513 static void
6514 emit_exception_info (MonoAotCompile *acfg)
6516 int i;
6517 char symbol [256];
6518 gint32 *offsets;
6520 offsets = g_new0 (gint32, acfg->nmethods);
6521 for (i = 0; i < acfg->nmethods; ++i) {
6522 if (acfg->cfgs [i]) {
6523 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6524 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6525 } else {
6526 offsets [i] = 0;
6530 sprintf (symbol, "ex_info_offsets");
6531 emit_section_change (acfg, RODATA_SECT, 1);
6532 emit_alignment (acfg, 8);
6533 emit_label (acfg, symbol);
6535 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6536 g_free (offsets);
6539 static void
6540 emit_unwind_info (MonoAotCompile *acfg)
6542 int i;
6543 char symbol [128];
6546 * The unwind info contains a lot of duplicates so we emit each unique
6547 * entry once, and only store the offset from the start of the table in the
6548 * exception info.
6551 sprintf (symbol, "unwind_info");
6552 emit_section_change (acfg, RODATA_SECT, 1);
6553 emit_alignment (acfg, 8);
6554 emit_label (acfg, symbol);
6556 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6557 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6558 guint8 *unwind_info;
6559 guint32 unwind_info_len;
6560 guint8 buf [16];
6561 guint8 *p;
6563 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6565 p = buf;
6566 encode_value (unwind_info_len, p, &p);
6567 emit_bytes (acfg, buf, p - buf);
6568 emit_bytes (acfg, unwind_info, unwind_info_len);
6570 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6574 static void
6575 emit_class_info (MonoAotCompile *acfg)
6577 int i;
6578 char symbol [256];
6579 gint32 *offsets;
6581 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6582 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6583 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6585 sprintf (symbol, "class_info_offsets");
6586 emit_section_change (acfg, RODATA_SECT, 1);
6587 emit_alignment (acfg, 8);
6588 emit_label (acfg, symbol);
6590 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6591 g_free (offsets);
6594 typedef struct ClassNameTableEntry {
6595 guint32 token, index;
6596 struct ClassNameTableEntry *next;
6597 } ClassNameTableEntry;
6599 static void
6600 emit_class_name_table (MonoAotCompile *acfg)
6602 int i, table_size;
6603 guint32 token, hash;
6604 MonoClass *klass;
6605 GPtrArray *table;
6606 char *full_name;
6607 char symbol [256];
6608 ClassNameTableEntry *entry, *new_entry;
6611 * Construct a chained hash table for mapping class names to typedef tokens.
6613 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6614 table = g_ptr_array_sized_new (table_size);
6615 for (i = 0; i < table_size; ++i)
6616 g_ptr_array_add (table, NULL);
6617 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6618 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6619 klass = mono_class_get (acfg->image, token);
6620 if (!klass) {
6621 mono_loader_clear_error ();
6622 continue;
6624 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6625 hash = mono_metadata_str_hash (full_name) % table_size;
6626 g_free (full_name);
6628 /* FIXME: Allocate from the mempool */
6629 new_entry = g_new0 (ClassNameTableEntry, 1);
6630 new_entry->token = token;
6632 entry = g_ptr_array_index (table, hash);
6633 if (entry == NULL) {
6634 new_entry->index = hash;
6635 g_ptr_array_index (table, hash) = new_entry;
6636 } else {
6637 while (entry->next)
6638 entry = entry->next;
6640 entry->next = new_entry;
6641 new_entry->index = table->len;
6642 g_ptr_array_add (table, new_entry);
6646 /* Emit the table */
6647 sprintf (symbol, "class_name_table");
6648 emit_section_change (acfg, RODATA_SECT, 0);
6649 emit_alignment (acfg, 8);
6650 emit_label (acfg, symbol);
6652 /* FIXME: Optimize memory usage */
6653 g_assert (table_size < 65000);
6654 emit_int16 (acfg, table_size);
6655 g_assert (table->len < 65000);
6656 for (i = 0; i < table->len; ++i) {
6657 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6659 if (entry == NULL) {
6660 emit_int16 (acfg, 0);
6661 emit_int16 (acfg, 0);
6662 } else {
6663 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6664 if (entry->next)
6665 emit_int16 (acfg, entry->next->index);
6666 else
6667 emit_int16 (acfg, 0);
6672 static void
6673 emit_image_table (MonoAotCompile *acfg)
6675 int i;
6676 char symbol [256];
6679 * The image table is small but referenced in a lot of places.
6680 * So we emit it at once, and reference its elements by an index.
6683 sprintf (symbol, "image_table");
6684 emit_section_change (acfg, RODATA_SECT, 1);
6685 emit_alignment (acfg, 8);
6686 emit_label (acfg, symbol);
6688 emit_int32 (acfg, acfg->image_table->len);
6689 for (i = 0; i < acfg->image_table->len; i++) {
6690 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6691 MonoAssemblyName *aname = &image->assembly->aname;
6693 /* FIXME: Support multi-module assemblies */
6694 g_assert (image->assembly->image == image);
6696 emit_string (acfg, image->assembly_name);
6697 emit_string (acfg, image->guid);
6698 emit_string (acfg, aname->culture ? aname->culture : "");
6699 emit_string (acfg, (const char*)aname->public_key_token);
6701 emit_alignment (acfg, 8);
6702 emit_int32 (acfg, aname->flags);
6703 emit_int32 (acfg, aname->major);
6704 emit_int32 (acfg, aname->minor);
6705 emit_int32 (acfg, aname->build);
6706 emit_int32 (acfg, aname->revision);
6710 static void
6711 emit_got_info (MonoAotCompile *acfg)
6713 char symbol [256];
6714 int i, first_plt_got_patch, buf_size;
6715 guint8 *p, *buf;
6716 guint32 *got_info_offsets;
6718 /* Add the patches needed by the PLT to the GOT */
6719 acfg->plt_got_offset_base = acfg->got_offset;
6720 first_plt_got_patch = acfg->got_patches->len;
6721 for (i = 1; i < acfg->plt_offset; ++i) {
6722 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6724 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6726 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6729 acfg->got_offset += acfg->plt_offset;
6732 * FIXME:
6733 * - optimize offsets table.
6734 * - reduce number of exported symbols.
6735 * - emit info for a klass only once.
6736 * - determine when a method uses a GOT slot which is guaranteed to be already
6737 * initialized.
6738 * - clean up and document the code.
6739 * - use String.Empty in class libs.
6742 /* Encode info required to decode shared GOT entries */
6743 buf_size = acfg->got_patches->len * 128;
6744 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6745 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6746 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6747 /* Unused */
6748 if (acfg->plt_offset)
6749 acfg->plt_got_info_offsets [0] = 0;
6750 for (i = 0; i < acfg->got_patches->len; ++i) {
6751 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6752 guint8 *p2;
6754 p = buf;
6756 encode_value (ji->type, p, &p);
6757 p2 = p;
6758 encode_patch (acfg, ji, p, &p);
6759 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6760 g_assert (p - buf <= buf_size);
6761 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6763 if (i >= first_plt_got_patch)
6764 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6765 acfg->stats.got_info_size += p - buf;
6768 /* Emit got_info_offsets table */
6769 sprintf (symbol, "got_info_offsets");
6770 emit_section_change (acfg, RODATA_SECT, 1);
6771 emit_alignment (acfg, 8);
6772 emit_label (acfg, symbol);
6774 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6775 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6778 static void
6779 emit_got (MonoAotCompile *acfg)
6781 char symbol [256];
6783 if (!acfg->llvm) {
6784 /* Don't make GOT global so accesses to it don't need relocations */
6785 sprintf (symbol, "%s", acfg->got_symbol);
6786 emit_section_change (acfg, ".bss", 0);
6787 emit_alignment (acfg, 8);
6788 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6789 emit_label (acfg, symbol);
6790 if (acfg->got_offset > 0)
6791 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6793 sprintf (symbol, "got_end");
6794 emit_label (acfg, symbol);
6798 typedef struct GlobalsTableEntry {
6799 guint32 value, index;
6800 struct GlobalsTableEntry *next;
6801 } GlobalsTableEntry;
6803 static void
6804 emit_globals (MonoAotCompile *acfg)
6806 int i, table_size;
6807 guint32 hash;
6808 GPtrArray *table;
6809 char symbol [256];
6810 GlobalsTableEntry *entry, *new_entry;
6812 if (!acfg->aot_opts.static_link)
6813 return;
6816 * When static linking, we emit a table containing our globals.
6820 * Construct a chained hash table for mapping global names to their index in
6821 * the globals table.
6823 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6824 table = g_ptr_array_sized_new (table_size);
6825 for (i = 0; i < table_size; ++i)
6826 g_ptr_array_add (table, NULL);
6827 for (i = 0; i < acfg->globals->len; ++i) {
6828 char *name = g_ptr_array_index (acfg->globals, i);
6830 hash = mono_metadata_str_hash (name) % table_size;
6832 /* FIXME: Allocate from the mempool */
6833 new_entry = g_new0 (GlobalsTableEntry, 1);
6834 new_entry->value = i;
6836 entry = g_ptr_array_index (table, hash);
6837 if (entry == NULL) {
6838 new_entry->index = hash;
6839 g_ptr_array_index (table, hash) = new_entry;
6840 } else {
6841 while (entry->next)
6842 entry = entry->next;
6844 entry->next = new_entry;
6845 new_entry->index = table->len;
6846 g_ptr_array_add (table, new_entry);
6850 /* Emit the table */
6851 sprintf (symbol, ".Lglobals_hash");
6852 emit_section_change (acfg, RODATA_SECT, 0);
6853 emit_alignment (acfg, 8);
6854 emit_label (acfg, symbol);
6856 /* FIXME: Optimize memory usage */
6857 g_assert (table_size < 65000);
6858 emit_int16 (acfg, table_size);
6859 for (i = 0; i < table->len; ++i) {
6860 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6862 if (entry == NULL) {
6863 emit_int16 (acfg, 0);
6864 emit_int16 (acfg, 0);
6865 } else {
6866 emit_int16 (acfg, entry->value + 1);
6867 if (entry->next)
6868 emit_int16 (acfg, entry->next->index);
6869 else
6870 emit_int16 (acfg, 0);
6874 /* Emit the names */
6875 for (i = 0; i < acfg->globals->len; ++i) {
6876 char *name = g_ptr_array_index (acfg->globals, i);
6878 sprintf (symbol, "name_%d", i);
6879 emit_section_change (acfg, RODATA_SECT, 1);
6880 #ifdef TARGET_MACH
6881 emit_alignment (acfg, 4);
6882 #endif
6883 emit_label (acfg, symbol);
6884 emit_string (acfg, name);
6887 /* Emit the globals table */
6888 sprintf (symbol, "globals");
6889 emit_section_change (acfg, ".data", 0);
6890 /* This is not a global, since it is accessed by the init function */
6891 emit_alignment (acfg, 8);
6892 emit_label (acfg, symbol);
6894 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6895 emit_pointer (acfg, symbol);
6897 for (i = 0; i < acfg->globals->len; ++i) {
6898 char *name = g_ptr_array_index (acfg->globals, i);
6900 sprintf (symbol, "name_%d", i);
6901 emit_pointer (acfg, symbol);
6903 sprintf (symbol, "%s", name);
6904 emit_pointer (acfg, symbol);
6906 /* Null terminate the table */
6907 emit_int32 (acfg, 0);
6908 emit_int32 (acfg, 0);
6911 static void
6912 emit_autoreg (MonoAotCompile *acfg)
6914 char *symbol;
6917 * Emit a function into the .ctor section which will be called by the ELF
6918 * loader to register this module with the runtime.
6920 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6921 return;
6923 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6925 arch_emit_autoreg (acfg, symbol);
6927 g_free (symbol);
6930 static void
6931 emit_mem_end (MonoAotCompile *acfg)
6933 char symbol [128];
6935 sprintf (symbol, "mem_end");
6936 emit_section_change (acfg, ".text", 1);
6937 emit_alignment (acfg, 8);
6938 emit_label (acfg, symbol);
6942 * Emit a structure containing all the information not stored elsewhere.
6944 static void
6945 emit_file_info (MonoAotCompile *acfg)
6947 char symbol [256];
6948 int i;
6949 int gc_name_offset;
6950 const char *gc_name;
6951 char *build_info;
6953 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6955 if (acfg->aot_opts.bind_to_runtime_version) {
6956 build_info = mono_get_runtime_build_info ();
6957 emit_string_symbol (acfg, "runtime_version", build_info);
6958 g_free (build_info);
6959 } else {
6960 emit_string_symbol (acfg, "runtime_version", "");
6963 /* Emit a string holding the assembly name */
6964 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6967 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6968 * in another.
6970 gc_name = mono_gc_get_gc_name ();
6971 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6973 sprintf (symbol, "mono_aot_file_info");
6974 emit_section_change (acfg, ".data", 0);
6975 emit_alignment (acfg, 8);
6976 emit_label (acfg, symbol);
6977 if (!acfg->aot_opts.static_link)
6978 emit_global (acfg, symbol, FALSE);
6980 /* The data emitted here must match MonoAotFileInfo. */
6982 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6983 emit_int32 (acfg, 0);
6986 * We emit pointers to our data structures instead of emitting global symbols which
6987 * point to them, to reduce the number of globals, and because using globals leads to
6988 * various problems (i.e. arm/thumb).
6990 emit_pointer (acfg, acfg->got_symbol);
6991 emit_pointer (acfg, "methods");
6992 if (acfg->llvm) {
6994 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6996 emit_pointer (acfg, "mono_eh_frame");
6997 } else {
6998 emit_pointer (acfg, NULL);
7000 emit_pointer (acfg, "blob");
7001 emit_pointer (acfg, "class_name_table");
7002 emit_pointer (acfg, "class_info_offsets");
7003 emit_pointer (acfg, "method_info_offsets");
7004 emit_pointer (acfg, "ex_info_offsets");
7005 emit_pointer (acfg, "code_offsets");
7006 emit_pointer (acfg, "extra_method_info_offsets");
7007 emit_pointer (acfg, "extra_method_table");
7008 emit_pointer (acfg, "got_info_offsets");
7009 emit_pointer (acfg, "methods_end");
7010 emit_pointer (acfg, "unwind_info");
7011 emit_pointer (acfg, "mem_end");
7012 emit_pointer (acfg, "image_table");
7013 emit_pointer (acfg, "plt");
7014 emit_pointer (acfg, "plt_end");
7015 emit_pointer (acfg, "assembly_guid");
7016 emit_pointer (acfg, "runtime_version");
7017 if (acfg->num_trampoline_got_entries) {
7018 emit_pointer (acfg, "specific_trampolines");
7019 emit_pointer (acfg, "static_rgctx_trampolines");
7020 emit_pointer (acfg, "imt_thunks");
7021 } else {
7022 emit_pointer (acfg, NULL);
7023 emit_pointer (acfg, NULL);
7024 emit_pointer (acfg, NULL);
7026 if (acfg->thumb_mixed) {
7027 emit_pointer (acfg, "thumb_end");
7028 } else {
7029 emit_pointer (acfg, NULL);
7031 if (acfg->aot_opts.static_link) {
7032 emit_pointer (acfg, "globals");
7033 } else {
7034 emit_pointer (acfg, NULL);
7036 emit_pointer (acfg, "assembly_name");
7037 emit_pointer (acfg, "unbox_trampolines");
7038 emit_pointer (acfg, "unbox_trampolines_end");
7040 emit_int32 (acfg, acfg->plt_got_offset_base);
7041 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7042 emit_int32 (acfg, acfg->plt_offset);
7043 emit_int32 (acfg, acfg->nmethods);
7044 emit_int32 (acfg, acfg->flags);
7045 emit_int32 (acfg, acfg->opts);
7046 emit_int32 (acfg, acfg->simd_opts);
7047 emit_int32 (acfg, gc_name_offset);
7049 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7050 emit_int32 (acfg, acfg->num_trampolines [i]);
7051 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7052 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7053 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7054 emit_int32 (acfg, acfg->trampoline_size [i]);
7056 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7058 MonoType t;
7059 int align = 0;
7061 t.type = MONO_TYPE_R8;
7062 mono_type_size (&t, &align);
7064 emit_int32 (acfg, align);
7066 t.type = MONO_TYPE_I8;
7067 mono_type_size (&t, &align);
7069 emit_int32 (acfg, align);
7071 #else
7072 emit_int32 (acfg, __alignof__ (double));
7073 emit_int32 (acfg, __alignof__ (gint64));
7074 #endif
7076 if (acfg->aot_opts.static_link) {
7077 char *p;
7080 * Emit a global symbol which can be passed by an embedding app to
7081 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7082 * structure.
7084 #if defined(TARGET_MACH) && !defined(__native_client_codegen__)
7085 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7086 #else
7087 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7088 #endif
7090 /* Get rid of characters which cannot occur in symbols */
7091 p = symbol;
7092 for (p = symbol; *p; ++p) {
7093 if (!(isalnum (*p) || *p == '_'))
7094 *p = '_';
7096 acfg->static_linking_symbol = g_strdup (symbol);
7097 emit_global_inner (acfg, symbol, FALSE);
7098 emit_label (acfg, symbol);
7099 emit_pointer (acfg, "mono_aot_file_info");
7103 static void
7104 emit_blob (MonoAotCompile *acfg)
7106 char symbol [128];
7108 sprintf (symbol, "blob");
7109 emit_section_change (acfg, RODATA_SECT, 1);
7110 emit_alignment (acfg, 8);
7111 emit_label (acfg, symbol);
7113 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7116 static void
7117 emit_dwarf_info (MonoAotCompile *acfg)
7119 #ifdef EMIT_DWARF_INFO
7120 int i;
7121 char symbol [128], symbol2 [128];
7123 /* DIEs for methods */
7124 for (i = 0; i < acfg->nmethods; ++i) {
7125 MonoCompile *cfg = acfg->cfgs [i];
7127 if (!cfg)
7128 continue;
7130 // FIXME: LLVM doesn't define .Lme_...
7131 if (cfg->compile_llvm)
7132 continue;
7134 sprintf (symbol, "%s", cfg->asm_symbol);
7135 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7137 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
7139 #endif
7142 static void
7143 collect_methods (MonoAotCompile *acfg)
7145 int i;
7146 MonoImage *image = acfg->image;
7148 /* Collect methods */
7149 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7150 MonoMethod *method;
7151 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7153 method = mono_get_method (acfg->image, token, NULL);
7155 if (!method) {
7156 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7157 exit (1);
7160 /* Load all methods eagerly to skip the slower lazy loading code */
7161 mono_class_setup_methods (method->klass);
7163 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7164 /* Compile the wrapper instead */
7165 /* We do this here instead of add_wrappers () because it is easy to do it here */
7166 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7167 method = wrapper;
7170 /* FIXME: Some mscorlib methods don't have debug info */
7172 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7173 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7174 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7175 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7176 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7177 if (!mono_debug_lookup_method (method)) {
7178 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7179 exit (1);
7185 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7186 add_method_with_index (acfg, method, i, FALSE);
7187 acfg->method_index ++;
7190 add_generic_instances (acfg);
7192 if (acfg->aot_opts.full_aot)
7193 add_wrappers (acfg);
7196 static void
7197 compile_methods (MonoAotCompile *acfg)
7199 int i, methods_len;
7201 if (acfg->aot_opts.nthreads > 0) {
7202 GPtrArray *frag;
7203 int len, j;
7204 GPtrArray *threads;
7205 HANDLE handle;
7206 gpointer *user_data;
7207 MonoMethod **methods;
7209 methods_len = acfg->methods->len;
7211 len = acfg->methods->len / acfg->aot_opts.nthreads;
7212 g_assert (len > 0);
7214 * Partition the list of methods into fragments, and hand it to threads to
7215 * process.
7217 threads = g_ptr_array_new ();
7218 /* Make a copy since acfg->methods is modified by compile_method () */
7219 methods = g_new0 (MonoMethod*, methods_len);
7220 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7221 for (i = 0; i < methods_len; ++i)
7222 methods [i] = g_ptr_array_index (acfg->methods, i);
7223 i = 0;
7224 while (i < methods_len) {
7225 frag = g_ptr_array_new ();
7226 for (j = 0; j < len; ++j) {
7227 if (i < methods_len) {
7228 g_ptr_array_add (frag, methods [i]);
7229 i ++;
7233 user_data = g_new0 (gpointer, 3);
7234 user_data [0] = mono_domain_get ();
7235 user_data [1] = acfg;
7236 user_data [2] = frag;
7238 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7239 g_ptr_array_add (threads, handle);
7241 g_free (methods);
7243 for (i = 0; i < threads->len; ++i) {
7244 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7246 } else {
7247 methods_len = 0;
7250 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7251 for (i = methods_len; i < acfg->methods->len; ++i) {
7252 /* This can new methods to acfg->methods */
7253 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7257 static int
7258 compile_asm (MonoAotCompile *acfg)
7260 char *command, *objfile;
7261 char *outfile_name, *tmp_outfile_name;
7262 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7264 #if defined(TARGET_AMD64)
7265 #define AS_OPTIONS "--64"
7266 #elif defined(TARGET_POWERPC64)
7267 #define AS_OPTIONS "-a64 -mppc64"
7268 #define LD_OPTIONS "-m elf64ppc"
7269 #elif defined(sparc) && SIZEOF_VOID_P == 8
7270 #define AS_OPTIONS "-xarch=v9"
7271 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7272 #define AS_OPTIONS "-arch i386 -W"
7273 #else
7274 #define AS_OPTIONS ""
7275 #endif
7277 #ifdef __native_client_codegen__
7278 #if defined(TARGET_AMD64)
7279 #define AS_NAME "nacl64-as"
7280 #else
7281 #define AS_NAME "nacl-as"
7282 #endif
7283 #else
7284 #define AS_NAME "as"
7285 #endif
7287 #ifndef LD_OPTIONS
7288 #define LD_OPTIONS ""
7289 #endif
7291 #define EH_LD_OPTIONS ""
7293 if (acfg->aot_opts.asm_only) {
7294 printf ("Output file: '%s'.\n", acfg->tmpfname);
7295 if (acfg->aot_opts.static_link)
7296 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7297 return 0;
7300 if (acfg->aot_opts.static_link) {
7301 if (acfg->aot_opts.outfile)
7302 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7303 else
7304 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7305 } else {
7306 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7308 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
7309 printf ("Executing the native assembler: %s\n", command);
7310 if (system (command) != 0) {
7311 g_free (command);
7312 g_free (objfile);
7313 return 1;
7316 g_free (command);
7318 if (acfg->aot_opts.static_link) {
7319 printf ("Output file: '%s'.\n", objfile);
7320 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7321 g_free (objfile);
7322 return 0;
7325 if (acfg->aot_opts.outfile)
7326 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7327 else
7328 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7330 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7332 #if defined(sparc)
7333 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7334 #elif defined(__ppc__) && defined(TARGET_MACH)
7335 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7336 #elif defined(HOST_WIN32)
7337 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7338 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7339 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7340 #else
7341 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7342 #endif
7343 printf ("Executing the native linker: %s\n", command);
7344 if (system (command) != 0) {
7345 g_free (tmp_outfile_name);
7346 g_free (outfile_name);
7347 g_free (command);
7348 g_free (objfile);
7349 return 1;
7352 g_free (command);
7354 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7355 printf ("Stripping the binary: %s\n", com);
7356 system (com);
7357 g_free (com);*/
7359 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
7361 * gas generates 'mapping symbols' each time code and data is mixed, which
7362 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7364 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7365 printf ("Stripping the binary: %s\n", command);
7366 if (system (command) != 0) {
7367 g_free (tmp_outfile_name);
7368 g_free (outfile_name);
7369 g_free (command);
7370 g_free (objfile);
7371 return 1;
7373 #endif
7375 rename (tmp_outfile_name, outfile_name);
7377 #if defined(TARGET_MACH)
7378 command = g_strdup_printf ("dsymutil %s", outfile_name);
7379 printf ("Generating debug symbols: %s\n", command);
7380 if (system (command) != 0) {
7381 return 1;
7383 #endif
7385 if (!acfg->aot_opts.save_temps)
7386 unlink (objfile);
7388 g_free (tmp_outfile_name);
7389 g_free (outfile_name);
7390 g_free (objfile);
7392 if (acfg->aot_opts.save_temps)
7393 printf ("Retained input file.\n");
7394 else
7395 unlink (acfg->tmpfname);
7397 return 0;
7400 static MonoAotCompile*
7401 acfg_create (MonoAssembly *ass, guint32 opts)
7403 MonoImage *image = ass->image;
7404 MonoAotCompile *acfg;
7405 int i;
7407 acfg = g_new0 (MonoAotCompile, 1);
7408 acfg->methods = g_ptr_array_new ();
7409 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7410 acfg->method_depth = g_hash_table_new (NULL, NULL);
7411 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7412 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7413 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7414 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7415 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7416 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7417 acfg->got_patches = g_ptr_array_new ();
7418 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7419 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7420 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7421 acfg->image_hash = g_hash_table_new (NULL, NULL);
7422 acfg->image_table = g_ptr_array_new ();
7423 acfg->globals = g_ptr_array_new ();
7424 acfg->image = image;
7425 acfg->opts = opts;
7426 /* TODO: Write out set of SIMD instructions used, rather than just those available */
7427 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
7428 acfg->mempool = mono_mempool_new ();
7429 acfg->extra_methods = g_ptr_array_new ();
7430 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7431 acfg->unwind_ops = g_ptr_array_new ();
7432 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7433 acfg->method_order = g_ptr_array_new ();
7434 acfg->export_names = g_hash_table_new (NULL, NULL);
7435 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7436 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7437 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7438 InitializeCriticalSection (&acfg->mutex);
7440 return acfg;
7443 static void
7444 acfg_free (MonoAotCompile *acfg)
7446 int i;
7448 img_writer_destroy (acfg->w);
7449 for (i = 0; i < acfg->nmethods; ++i)
7450 if (acfg->cfgs [i])
7451 g_free (acfg->cfgs [i]);
7452 g_free (acfg->cfgs);
7453 g_free (acfg->static_linking_symbol);
7454 g_free (acfg->got_symbol);
7455 g_free (acfg->plt_symbol);
7456 g_ptr_array_free (acfg->methods, TRUE);
7457 g_ptr_array_free (acfg->got_patches, TRUE);
7458 g_ptr_array_free (acfg->image_table, TRUE);
7459 g_ptr_array_free (acfg->globals, TRUE);
7460 g_ptr_array_free (acfg->unwind_ops, TRUE);
7461 g_hash_table_destroy (acfg->method_indexes);
7462 g_hash_table_destroy (acfg->method_depth);
7463 g_hash_table_destroy (acfg->plt_offset_to_entry);
7464 g_hash_table_destroy (acfg->patch_to_plt_entry);
7465 g_hash_table_destroy (acfg->patch_to_got_offset);
7466 g_hash_table_destroy (acfg->method_to_cfg);
7467 g_hash_table_destroy (acfg->token_info_hash);
7468 g_hash_table_destroy (acfg->method_to_pinvoke_import);
7469 g_hash_table_destroy (acfg->image_hash);
7470 g_hash_table_destroy (acfg->unwind_info_offsets);
7471 g_hash_table_destroy (acfg->method_label_hash);
7472 g_hash_table_destroy (acfg->export_names);
7473 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7474 g_hash_table_destroy (acfg->klass_blob_hash);
7475 g_hash_table_destroy (acfg->method_blob_hash);
7476 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7477 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7478 g_free (acfg->patch_to_got_offset_by_type);
7479 mono_mempool_destroy (acfg->mempool);
7480 g_free (acfg);
7484 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7486 MonoImage *image = ass->image;
7487 int i, res;
7488 MonoAotCompile *acfg;
7489 char *outfile_name, *tmp_outfile_name, *p;
7490 TV_DECLARE (atv);
7491 TV_DECLARE (btv);
7493 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7495 acfg = acfg_create (ass, opts);
7497 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7498 acfg->aot_opts.write_symbols = TRUE;
7499 acfg->aot_opts.ntrampolines = 1024;
7500 acfg->aot_opts.nrgctx_trampolines = 1024;
7501 acfg->aot_opts.nimt_trampolines = 128;
7502 acfg->aot_opts.llvm_path = g_strdup ("");
7504 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7506 if (acfg->aot_opts.static_link)
7507 acfg->aot_opts.autoreg = TRUE;
7509 //acfg->aot_opts.print_skipped_methods = TRUE;
7511 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7512 if (acfg->aot_opts.full_aot) {
7513 printf ("--aot=full is not supported on this platform.\n");
7514 return 1;
7516 #endif
7518 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7519 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7520 exit (1);
7523 if (acfg->aot_opts.static_link)
7524 acfg->aot_opts.asm_writer = TRUE;
7526 if (acfg->aot_opts.soft_debug) {
7527 MonoDebugOptions *opt = mini_get_debug_options ();
7529 opt->mdb_optimizations = TRUE;
7530 opt->gen_seq_points = TRUE;
7532 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7533 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7534 return 1;
7536 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7539 if (mono_use_llvm) {
7540 acfg->llvm = TRUE;
7541 acfg->aot_opts.asm_writer = TRUE;
7542 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7544 if (acfg->aot_opts.soft_debug) {
7545 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7546 exit (1);
7550 if (acfg->aot_opts.full_aot)
7551 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7553 load_profile_files (acfg);
7555 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7556 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7557 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7558 #endif
7559 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7561 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7563 arch_init (acfg);
7565 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7566 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7567 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7569 /* Get rid of characters which cannot occur in symbols */
7570 for (p = acfg->got_symbol_base; *p; ++p) {
7571 if (!(isalnum (*p) || *p == '_'))
7572 *p = '_';
7574 for (p = acfg->plt_symbol; *p; ++p) {
7575 if (!(isalnum (*p) || *p == '_'))
7576 *p = '_';
7578 for (p = acfg->assembly_name_sym; *p; ++p) {
7579 if (!(isalnum (*p) || *p == '_'))
7580 *p = '_';
7583 acfg->method_index = 1;
7585 collect_methods (acfg);
7587 acfg->cfgs_size = acfg->methods->len + 32;
7588 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7590 /* PLT offset 0 is reserved for the PLT trampoline */
7591 acfg->plt_offset = 1;
7593 #ifdef ENABLE_LLVM
7594 if (acfg->llvm) {
7595 llvm_acfg = acfg;
7596 mono_llvm_create_aot_module (acfg->got_symbol_base);
7598 #endif
7600 /* GOT offset 0 is reserved for the address of the current assembly */
7602 MonoJumpInfo *ji;
7604 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7605 ji->type = MONO_PATCH_INFO_IMAGE;
7606 ji->data.image = acfg->image;
7608 get_got_offset (acfg, ji);
7610 /* Slot 1 is reserved for the mscorlib got addr */
7611 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7612 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7613 get_got_offset (acfg, ji);
7615 /* This is very common */
7616 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7617 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7618 get_got_offset (acfg, ji);
7621 TV_GETTIME (atv);
7623 compile_methods (acfg);
7625 TV_GETTIME (btv);
7627 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7629 TV_GETTIME (atv);
7631 #ifdef ENABLE_LLVM
7632 if (acfg->llvm) {
7633 if (acfg->aot_opts.asm_only) {
7634 if (acfg->aot_opts.outfile)
7635 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7636 else
7637 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7638 } else {
7639 acfg->tmpfname = g_strdup ("temp.s");
7642 emit_llvm_file (acfg);
7644 #endif
7646 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7647 if (acfg->aot_opts.outfile)
7648 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7649 else
7650 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7653 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7654 * it might be in another file system so the rename () won't work.
7656 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7658 acfg->fp = fopen (tmp_outfile_name, "w");
7659 if (!acfg->fp) {
7660 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7661 return 1;
7664 acfg->w = img_writer_create (acfg->fp, TRUE);
7665 acfg->use_bin_writer = TRUE;
7666 } else {
7667 if (acfg->llvm) {
7668 /* Append to the .s file created by llvm */
7669 /* FIXME: Use multiple files instead */
7670 acfg->fp = fopen (acfg->tmpfname, "a+");
7671 } else {
7672 if (acfg->aot_opts.asm_only) {
7673 if (acfg->aot_opts.outfile)
7674 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7675 else
7676 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7677 acfg->fp = fopen (acfg->tmpfname, "w+");
7678 } else {
7679 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7680 acfg->fp = fdopen (i, "w+");
7682 if (acfg->fp == 0) {
7683 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7684 return 1;
7687 acfg->w = img_writer_create (acfg->fp, FALSE);
7689 tmp_outfile_name = NULL;
7690 outfile_name = NULL;
7693 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7695 /* Compute symbols for methods */
7696 for (i = 0; i < acfg->nmethods; ++i) {
7697 if (acfg->cfgs [i]) {
7698 MonoCompile *cfg = acfg->cfgs [i];
7699 int method_index = get_method_index (acfg, cfg->orig_method);
7701 if (COMPILE_LLVM (cfg))
7702 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7703 else
7704 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7708 if (!acfg->aot_opts.nodebug)
7709 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7711 img_writer_emit_start (acfg->w);
7713 if (acfg->dwarf)
7714 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7716 if (acfg->thumb_mixed) {
7717 char symbol [256];
7719 * This global symbol marks the end of THUMB code, and the beginning of ARM
7720 * code generated by our JIT.
7722 sprintf (symbol, "thumb_end");
7723 emit_section_change (acfg, ".text", 0);
7724 emit_alignment (acfg, 8);
7725 emit_label (acfg, symbol);
7726 emit_zero_bytes (acfg, 16);
7728 fprintf (acfg->fp, ".arm\n");
7731 emit_code (acfg);
7733 emit_info (acfg);
7735 emit_extra_methods (acfg);
7737 emit_trampolines (acfg);
7739 emit_class_name_table (acfg);
7741 emit_got_info (acfg);
7743 emit_exception_info (acfg);
7745 emit_unwind_info (acfg);
7747 emit_class_info (acfg);
7749 emit_plt (acfg);
7751 emit_image_table (acfg);
7753 emit_got (acfg);
7755 emit_file_info (acfg);
7757 emit_blob (acfg);
7759 emit_globals (acfg);
7761 emit_autoreg (acfg);
7763 if (acfg->dwarf) {
7764 emit_dwarf_info (acfg);
7765 mono_dwarf_writer_close (acfg->dwarf);
7768 emit_mem_end (acfg);
7770 if (acfg->need_pt_gnu_stack) {
7771 /* This is required so the .so doesn't have an executable stack */
7772 /* The bin writer already emits this */
7773 if (!acfg->use_bin_writer)
7774 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7777 TV_GETTIME (btv);
7779 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7781 if (acfg->llvm)
7782 g_assert (acfg->got_offset <= acfg->final_got_size);
7784 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
7785 printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
7786 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
7787 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
7788 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7789 if (acfg->stats.genericcount)
7790 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7791 if (acfg->stats.abscount)
7792 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7793 if (acfg->stats.lmfcount)
7794 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7795 if (acfg->stats.ocount)
7796 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7797 if (acfg->llvm)
7798 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7800 TV_GETTIME (atv);
7801 res = img_writer_emit_writeout (acfg->w);
7802 if (res != 0) {
7803 acfg_free (acfg);
7804 return res;
7806 if (acfg->use_bin_writer) {
7807 int err = rename (tmp_outfile_name, outfile_name);
7809 if (err) {
7810 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7811 return 1;
7813 } else {
7814 res = compile_asm (acfg);
7815 if (res != 0) {
7816 acfg_free (acfg);
7817 return res;
7820 TV_GETTIME (btv);
7821 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7823 if (acfg->aot_opts.stats) {
7824 int i;
7826 printf ("GOT slot distribution:\n");
7827 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7828 if (acfg->stats.got_slot_types [i])
7829 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7832 printf ("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);
7834 acfg_free (acfg);
7836 return 0;
7839 #else
7841 /* AOT disabled */
7843 void*
7844 mono_aot_readonly_field_override (MonoClassField *field)
7846 return NULL;
7850 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7852 return 0;
7855 #endif