2010-04-19 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / mini / aot-compiler.c
bloba62bcd583021514a93ea5699ea9eef3024d159f2
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 */
11 /* Remaining AOT-only work:
12 * - optimize the trampolines, generate more code in the arch files.
13 * - make things more consistent with how elf works, for example, use ELF
14 * relocations.
15 * Remaining generics sharing work:
16 * - optimize the size of the data which is encoded.
17 * - optimize the runtime loading of data:
18 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
19 * which loads the debugging+exception handling info for the method. This is a
20 * huge waste of time and code, since the rgctx structure is currently empty.
21 * - every shared method has a MonoGenericJitInfo structure which is only really
22 * used for handling catch clauses with open types, not a very common use case.
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"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #ifdef TARGET_WIN32
76 #define SHARED_EXT ".dll"
77 #elif defined(__ppc__) && defined(__MACH__)
78 #define SHARED_EXT ".dylib"
79 #else
80 #define SHARED_EXT ".so"
81 #endif
83 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
84 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
85 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
87 typedef struct MonoAotOptions {
88 char *outfile;
89 gboolean save_temps;
90 gboolean write_symbols;
91 gboolean metadata_only;
92 gboolean bind_to_runtime_version;
93 gboolean full_aot;
94 gboolean no_dlsym;
95 gboolean static_link;
96 gboolean asm_only;
97 gboolean asm_writer;
98 gboolean nodebug;
99 gboolean soft_debug;
100 int nthreads;
101 int ntrampolines;
102 int nrgctx_trampolines;
103 int nimt_trampolines;
104 gboolean print_skipped_methods;
105 gboolean stats;
106 char *tool_prefix;
107 gboolean autoreg;
108 } MonoAotOptions;
110 typedef struct MonoAotStats {
111 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
112 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
113 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
114 int got_slots, offsets_size;
115 int got_slot_types [MONO_PATCH_INFO_NONE];
116 int jit_time, gen_time, link_time;
117 } MonoAotStats;
119 typedef struct MonoAotCompile {
120 MonoImage *image;
121 GPtrArray *methods;
122 GHashTable *method_indexes;
123 GHashTable *method_depth;
124 MonoCompile **cfgs;
125 int cfgs_size;
126 GHashTable *patch_to_plt_offset;
127 GHashTable *plt_offset_to_patch;
128 GHashTable *patch_to_got_offset;
129 GHashTable **patch_to_got_offset_by_type;
130 GPtrArray *got_patches;
131 GHashTable *image_hash;
132 GHashTable *method_to_cfg;
133 GHashTable *token_info_hash;
134 GPtrArray *extra_methods;
135 GPtrArray *image_table;
136 GPtrArray *globals;
137 GList *method_order;
138 guint32 *plt_got_info_offsets;
139 guint32 got_offset, plt_offset, plt_got_offset_base;
140 guint32 final_got_size;
141 /* Number of GOT entries reserved for trampolines */
142 guint32 num_trampoline_got_entries;
144 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
145 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
146 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
148 MonoAotOptions aot_opts;
149 guint32 nmethods;
150 guint32 opts;
151 MonoMemPool *mempool;
152 MonoAotStats stats;
153 int method_index;
154 char *static_linking_symbol;
155 CRITICAL_SECTION mutex;
156 gboolean use_bin_writer;
157 MonoImageWriter *w;
158 MonoDwarfWriter *dwarf;
159 FILE *fp;
160 char *tmpfname;
161 GSList *cie_program;
162 GHashTable *unwind_info_offsets;
163 GPtrArray *unwind_ops;
164 guint32 unwind_info_offset;
165 char *got_symbol_base;
166 char *got_symbol;
167 char *plt_symbol;
168 GHashTable *method_label_hash;
169 const char *temp_prefix;
170 const char *llvm_label_prefix;
171 guint32 label_generator;
172 gboolean llvm;
173 MonoAotFileFlags flags;
174 MonoDynamicStream blob;
175 } MonoAotCompile;
177 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
178 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
180 /* This points to the current acfg in LLVM mode */
181 static MonoAotCompile *llvm_acfg;
183 #ifdef HAVE_ARRAY_ELEM_INIT
184 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
185 #define MSGSTRFIELD1(line) str##line
186 static const struct msgstr_t {
187 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
188 #include "patch-info.h"
189 #undef PATCH_INFO
190 } opstr = {
191 #define PATCH_INFO(a,b) b,
192 #include "patch-info.h"
193 #undef PATCH_INFO
195 static const gint16 opidx [] = {
196 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
197 #include "patch-info.h"
198 #undef PATCH_INFO
201 static G_GNUC_UNUSED const char*
202 get_patch_name (int info)
204 return (const char*)&opstr + opidx [info];
207 #else
208 #define PATCH_INFO(a,b) b,
209 static const char* const
210 patch_types [MONO_PATCH_INFO_NUM + 1] = {
211 #include "patch-info.h"
212 NULL
215 static G_GNUC_UNUSED const char*
216 get_patch_name (int info)
218 return patch_types [info];
221 #endif
223 /* Wrappers around the image writer functions */
225 static inline void
226 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
228 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
231 static inline void
232 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
234 img_writer_emit_push_section (acfg->w, section_name, subsection);
237 static inline void
238 emit_pop_section (MonoAotCompile *acfg)
240 img_writer_emit_pop_section (acfg->w);
243 static inline void
244 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
246 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
249 static inline void
250 emit_label (MonoAotCompile *acfg, const char *name)
252 img_writer_emit_label (acfg->w, name);
255 static inline void
256 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
258 img_writer_emit_bytes (acfg->w, buf, size);
261 static inline void
262 emit_string (MonoAotCompile *acfg, const char *value)
264 img_writer_emit_string (acfg->w, value);
267 static inline void
268 emit_line (MonoAotCompile *acfg)
270 img_writer_emit_line (acfg->w);
273 static inline void
274 emit_alignment (MonoAotCompile *acfg, int size)
276 img_writer_emit_alignment (acfg->w, size);
279 static inline void
280 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
282 img_writer_emit_pointer_unaligned (acfg->w, target);
285 static inline void
286 emit_pointer (MonoAotCompile *acfg, const char *target)
288 img_writer_emit_pointer (acfg->w, target);
291 static inline void
292 emit_int16 (MonoAotCompile *acfg, int value)
294 img_writer_emit_int16 (acfg->w, value);
297 static inline void
298 emit_int32 (MonoAotCompile *acfg, int value)
300 img_writer_emit_int32 (acfg->w, value);
303 static inline void
304 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
306 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
309 static inline void
310 emit_zero_bytes (MonoAotCompile *acfg, int num)
312 img_writer_emit_zero_bytes (acfg->w, num);
315 static inline void
316 emit_byte (MonoAotCompile *acfg, guint8 val)
318 img_writer_emit_byte (acfg->w, val);
321 static G_GNUC_UNUSED void
322 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
324 img_writer_emit_global (acfg->w, name, func);
327 static void
328 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
330 if (acfg->aot_opts.no_dlsym) {
331 g_ptr_array_add (acfg->globals, g_strdup (name));
332 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
333 } else {
334 img_writer_emit_global (acfg->w, name, func);
338 static void
339 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
341 img_writer_emit_symbol_size (acfg->w, name, end_label);
344 static void
345 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
347 img_writer_emit_section_change (acfg->w, ".text", 1);
348 emit_global (acfg, name, FALSE);
349 img_writer_emit_label (acfg->w, name);
350 img_writer_emit_string (acfg->w, value);
353 static G_GNUC_UNUSED void
354 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
356 do {
357 guint8 b = value & 0x7f;
358 value >>= 7;
359 if (value != 0) /* more bytes to come */
360 b |= 0x80;
361 emit_byte (acfg, b);
362 } while (value);
365 static G_GNUC_UNUSED void
366 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
368 gboolean more = 1;
369 gboolean negative = (value < 0);
370 guint32 size = 64;
371 guint8 byte;
373 while (more) {
374 byte = value & 0x7f;
375 value >>= 7;
376 /* the following is unnecessary if the
377 * implementation of >>= uses an arithmetic rather
378 * than logical shift for a signed left operand
380 if (negative)
381 /* sign extend */
382 value |= - ((gint64)1 <<(size - 7));
383 /* sign bit of byte is second high order bit (0x40) */
384 if ((value == 0 && !(byte & 0x40)) ||
385 (value == -1 && (byte & 0x40)))
386 more = 0;
387 else
388 byte |= 0x80;
389 emit_byte (acfg, byte);
393 static G_GNUC_UNUSED void
394 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
396 guint8 *p = buf;
398 do {
399 guint8 b = value & 0x7f;
400 value >>= 7;
401 if (value != 0) /* more bytes to come */
402 b |= 0x80;
403 *p ++ = b;
404 } while (value);
406 *endbuf = p;
409 static G_GNUC_UNUSED void
410 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
412 gboolean more = 1;
413 gboolean negative = (value < 0);
414 guint32 size = 32;
415 guint8 byte;
416 guint8 *p = buf;
418 while (more) {
419 byte = value & 0x7f;
420 value >>= 7;
421 /* the following is unnecessary if the
422 * implementation of >>= uses an arithmetic rather
423 * than logical shift for a signed left operand
425 if (negative)
426 /* sign extend */
427 value |= - (1 <<(size - 7));
428 /* sign bit of byte is second high order bit (0x40) */
429 if ((value == 0 && !(byte & 0x40)) ||
430 (value == -1 && (byte & 0x40)))
431 more = 0;
432 else
433 byte |= 0x80;
434 *p ++= byte;
437 *endbuf = p;
440 /* ARCHITECTURE SPECIFIC CODE */
442 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
443 #define EMIT_DWARF_INFO 1
444 #endif
446 #if defined(TARGET_ARM)
447 #define AOT_FUNC_ALIGNMENT 4
448 #else
449 #define AOT_FUNC_ALIGNMENT 16
450 #endif
452 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
453 #define PPC_LD_OP "ld"
454 #define PPC_LDX_OP "ldx"
455 #else
456 #define PPC_LD_OP "lwz"
457 #define PPC_LDX_OP "lwzx"
458 #endif
460 //#define TARGET_ARM
462 #ifdef TARGET_ARM
463 #define LLVM_LABEL_PREFIX "_"
464 #else
465 #define LLVM_LABEL_PREFIX ""
466 #endif
468 #ifdef TARGET_ARM
469 /* iphone */
470 #define LLC_TARGET_ARGS "-march=arm -mattr=+v6 -mtriple=arm-apple-darwin"
471 /* ELF */
472 //#define LLC_TARGET_ARGS "-march=arm -mtriple=arm-linux-gnueabi -soft-float"
473 #else
474 #define LLC_TARGET_ARGS ""
475 #endif
478 * arch_emit_direct_call:
480 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
481 * calling code.
483 static void
484 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
486 #if defined(TARGET_X86) || defined(TARGET_AMD64)
487 /* Need to make sure this is exactly 5 bytes long */
488 emit_byte (acfg, '\xe8');
489 emit_symbol_diff (acfg, target, ".", -4);
490 *call_size = 5;
491 #elif defined(TARGET_ARM)
492 if (acfg->use_bin_writer) {
493 guint8 buf [4];
494 guint8 *code;
496 code = buf;
497 ARM_BL (code, 0);
499 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
500 emit_bytes (acfg, buf, 4);
501 } else {
502 img_writer_emit_unset_mode (acfg->w);
503 fprintf (acfg->fp, "bl %s\n", target);
505 *call_size = 4;
506 #elif defined(TARGET_POWERPC)
507 if (acfg->use_bin_writer) {
508 g_assert_not_reached ();
509 } else {
510 img_writer_emit_unset_mode (acfg->w);
511 fprintf (acfg->fp, "bl %s\n", target);
512 *call_size = 4;
514 #else
515 g_assert_not_reached ();
516 #endif
520 * PPC32 design:
521 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
522 * the GOT pointer.
523 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
524 * in in the 2. slot of every GOT, and require every method to place the GOT
525 * address in r30, even when it doesn't access the GOT otherwise. This way,
526 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
530 * PPC64 design:
531 * PPC64 uses function descriptors which greatly complicate all code, since
532 * these are used very inconsistently in the runtime. Some functions like
533 * mono_compile_method () return ftn descriptors, while others like the
534 * trampoline creation functions do not.
535 * We assume that all GOT slots contain function descriptors, and create
536 * descriptors in aot-runtime.c when needed.
537 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
538 * from function descriptors, we could do the same, but it would require
539 * rewriting all the ppc/aot code to handle function descriptors properly.
540 * So instead, we use the same approach as on PPC32.
541 * This is a horrible mess, but fixing it would probably lead to an even bigger
542 * one.
545 #ifdef MONO_ARCH_AOT_SUPPORTED
547 * arch_emit_got_offset:
549 * The memory pointed to by CODE should hold native code for computing the GOT
550 * address. Emit this code while patching it with the offset between code and
551 * the GOT. CODE_SIZE is set to the number of bytes emitted.
553 static void
554 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
556 #if defined(TARGET_POWERPC64)
557 g_assert (!acfg->use_bin_writer);
558 img_writer_emit_unset_mode (acfg->w);
560 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
561 * unsupported relocations. So we store the got address into the .Lgot_addr
562 * symbol which is in the text segment, compute its address, and load it.
564 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
565 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
566 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
567 fprintf (acfg->fp, "add 30, 30, 0\n");
568 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
569 acfg->label_generator ++;
570 *code_size = 16;
571 #elif defined(TARGET_POWERPC)
572 g_assert (!acfg->use_bin_writer);
573 img_writer_emit_unset_mode (acfg->w);
574 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
575 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
576 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
577 acfg->label_generator ++;
578 *code_size = 8;
579 #else
580 guint32 offset = mono_arch_get_patch_offset (code);
581 emit_bytes (acfg, code, offset);
582 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
584 *code_size = offset + 4;
585 #endif
589 * arch_emit_got_access:
591 * The memory pointed to by CODE should hold native code for loading a GOT
592 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
593 * CODE_SIZE is set to the number of bytes emitted.
595 static void
596 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
598 /* Emit beginning of instruction */
599 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
601 /* Emit the offset */
602 #ifdef TARGET_AMD64
603 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
604 *code_size = mono_arch_get_patch_offset (code) + 4;
605 #elif defined(TARGET_X86)
606 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
607 *code_size = mono_arch_get_patch_offset (code) + 4;
608 #elif defined(TARGET_ARM)
609 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
610 *code_size = mono_arch_get_patch_offset (code) + 4;
611 #elif defined(TARGET_POWERPC)
613 guint8 buf [32];
614 guint8 *code;
616 code = buf;
617 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
618 g_assert (code - buf == 8);
619 emit_bytes (acfg, buf, code - buf);
620 *code_size = code - buf;
622 #else
623 g_assert_not_reached ();
624 #endif
627 #endif
630 * arch_emit_plt_entry:
632 * Emit code for the PLT entry with index INDEX.
634 static void
635 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
637 #if defined(TARGET_X86)
638 if (index == 0) {
639 /* It is filled up during loading by the AOT loader. */
640 emit_zero_bytes (acfg, 16);
641 } else {
642 /* Need to make sure this is 9 bytes long */
643 emit_byte (acfg, '\xe9');
644 emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
645 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
647 #elif defined(TARGET_AMD64)
649 * We can't emit jumps because they are 32 bits only so they can't be patched.
650 * So we make indirect calls through GOT entries which are patched by the AOT
651 * loader to point to .Lpd entries.
653 /* jmpq *<offset>(%rip) */
654 emit_byte (acfg, '\xff');
655 emit_byte (acfg, '\x25');
656 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
657 /* Used by mono_aot_get_plt_info_offset */
658 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
659 #elif defined(TARGET_ARM)
660 guint8 buf [256];
661 guint8 *code;
663 /* FIXME:
664 * - optimize OP_AOTCONST implementation
665 * - optimize the PLT entries
666 * - optimize SWITCH AOT implementation
668 code = buf;
669 if (acfg->use_bin_writer && FALSE) {
670 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
671 /* We only emit 1 relocation since we implement it ourselves anyway */
672 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
673 /* FIXME: A 2 instruction encoding is sufficient in most cases */
674 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
675 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
676 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
677 emit_bytes (acfg, buf, code - buf);
678 /* Used by mono_aot_get_plt_info_offset */
679 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
680 } else {
681 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
682 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
683 emit_bytes (acfg, buf, code - buf);
684 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
685 /* Used by mono_aot_get_plt_info_offset */
686 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
689 * The plt_got_info_offset is computed automatically by
690 * mono_aot_get_plt_info_offset (), so no need to save it here.
692 #elif defined(TARGET_POWERPC)
693 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
695 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
696 g_assert (!acfg->use_bin_writer);
697 img_writer_emit_unset_mode (acfg->w);
698 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
699 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
700 fprintf (acfg->fp, "add 11, 11, 30\n");
701 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
702 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
703 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
704 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
705 #endif
706 fprintf (acfg->fp, "mtctr 11\n");
707 fprintf (acfg->fp, "bctr\n");
708 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
709 #else
710 g_assert_not_reached ();
711 #endif
715 * arch_emit_specific_trampoline:
717 * Emit code for a specific trampoline. OFFSET is the offset of the first of
718 * two GOT slots which contain the generic trampoline address and the trampoline
719 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
721 static void
722 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
725 * The trampolines created here are variations of the specific
726 * trampolines created in mono_arch_create_specific_trampoline (). The
727 * differences are:
728 * - the generic trampoline address is taken from a got slot.
729 * - the offset of the got slot where the trampoline argument is stored
730 * is embedded in the instruction stream, and the generic trampoline
731 * can load the argument by loading the offset, adding it to the
732 * address of the trampoline to get the address of the got slot, and
733 * loading the argument from there.
734 * - all the trampolines should be of the same length.
736 #if defined(TARGET_AMD64)
737 /* This should be exactly 16 bytes long */
738 *tramp_size = 16;
739 /* call *<offset>(%rip) */
740 emit_byte (acfg, '\x41');
741 emit_byte (acfg, '\xff');
742 emit_byte (acfg, '\x15');
743 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
744 /* This should be relative to the start of the trampoline */
745 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
746 emit_zero_bytes (acfg, 5);
747 #elif defined(TARGET_ARM)
748 guint8 buf [128];
749 guint8 *code;
751 /* This should be exactly 20 bytes long */
752 *tramp_size = 20;
753 code = buf;
754 ARM_PUSH (code, 0x5fff);
755 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
756 /* Load the value from the GOT */
757 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
758 /* Branch to it */
759 ARM_BLX_REG (code, ARMREG_R1);
761 g_assert (code - buf == 16);
763 /* Emit it */
764 emit_bytes (acfg, buf, code - buf);
766 * Only one offset is needed, since the second one would be equal to the
767 * first one.
769 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
770 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
771 #elif defined(TARGET_POWERPC)
772 guint8 buf [128];
773 guint8 *code;
775 *tramp_size = 4;
776 code = buf;
778 g_assert (!acfg->use_bin_writer);
781 * PPC has no ip relative addressing, so we need to compute the address
782 * of the mscorlib got. That is slow and complex, so instead, we store it
783 * in the second got slot of every aot image. The caller already computed
784 * the address of its got and placed it into r30.
786 img_writer_emit_unset_mode (acfg->w);
787 /* Load mscorlib got address */
788 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
789 /* Load generic trampoline address */
790 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
791 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
792 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
793 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
794 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
795 #endif
796 fprintf (acfg->fp, "mtctr 11\n");
797 /* Load trampoline argument */
798 /* On ppc, we pass it normally to the generic trampoline */
799 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
800 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
801 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
802 /* Branch to generic trampoline */
803 fprintf (acfg->fp, "bctr\n");
805 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
806 *tramp_size = 10 * 4;
807 #else
808 *tramp_size = 9 * 4;
809 #endif
810 #else
811 g_assert_not_reached ();
812 #endif
816 * arch_emit_unbox_trampoline:
818 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
819 * CALL_TARGET is the symbol pointing to the native code of METHOD.
821 static void
822 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
824 #if defined(TARGET_AMD64)
825 guint8 buf [32];
826 guint8 *code;
827 int this_reg;
829 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
830 code = buf;
831 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
833 emit_bytes (acfg, buf, code - buf);
834 /* jump <method> */
835 emit_byte (acfg, '\xe9');
836 emit_symbol_diff (acfg, call_target, ".", -4);
837 #elif defined(TARGET_ARM)
838 guint8 buf [128];
839 guint8 *code;
840 int this_pos = 0;
842 code = buf;
844 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
845 this_pos = 1;
847 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
849 emit_bytes (acfg, buf, code - buf);
850 /* jump to method */
851 if (acfg->use_bin_writer) {
852 guint8 buf [4];
853 guint8 *code;
855 code = buf;
856 ARM_B (code, 0);
858 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
859 emit_bytes (acfg, buf, 4);
860 } else {
861 fprintf (acfg->fp, "\n\tb %s\n", call_target);
863 #elif defined(TARGET_POWERPC)
864 int this_pos = 3;
866 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
867 this_pos = 4;
869 g_assert (!acfg->use_bin_writer);
871 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
872 fprintf (acfg->fp, "\n\tb %s\n", call_target);
873 #else
874 g_assert_not_reached ();
875 #endif
879 * arch_emit_static_rgctx_trampoline:
881 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
882 * two GOT slots which contain the rgctx argument, and the method to jump to.
883 * TRAMP_SIZE is set to the size of the emitted trampoline.
884 * These kinds of trampolines cannot be enumerated statically, since there could
885 * be one trampoline per method instantiation, so we emit the same code for all
886 * trampolines, and parameterize them using two GOT slots.
888 static void
889 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
891 #if defined(TARGET_AMD64)
892 /* This should be exactly 13 bytes long */
893 *tramp_size = 13;
895 /* mov <OFFSET>(%rip), %r10 */
896 emit_byte (acfg, '\x4d');
897 emit_byte (acfg, '\x8b');
898 emit_byte (acfg, '\x15');
899 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
901 /* jmp *<offset>(%rip) */
902 emit_byte (acfg, '\xff');
903 emit_byte (acfg, '\x25');
904 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
905 #elif defined(TARGET_ARM)
906 guint8 buf [128];
907 guint8 *code;
909 /* This should be exactly 24 bytes long */
910 *tramp_size = 24;
911 code = buf;
912 /* Load rgctx value */
913 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
914 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
915 /* Load branch addr + branch */
916 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
917 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
919 g_assert (code - buf == 16);
921 /* Emit it */
922 emit_bytes (acfg, buf, code - buf);
923 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
924 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
925 #elif defined(TARGET_POWERPC)
926 guint8 buf [128];
927 guint8 *code;
929 *tramp_size = 4;
930 code = buf;
932 g_assert (!acfg->use_bin_writer);
935 * PPC has no ip relative addressing, so we need to compute the address
936 * of the mscorlib got. That is slow and complex, so instead, we store it
937 * in the second got slot of every aot image. The caller already computed
938 * the address of its got and placed it into r30.
940 img_writer_emit_unset_mode (acfg->w);
941 /* Load mscorlib got address */
942 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
943 /* Load rgctx */
944 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
945 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
946 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
947 /* Load target address */
948 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
949 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
950 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
951 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
952 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
953 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
954 #endif
955 fprintf (acfg->fp, "mtctr 11\n");
956 /* Branch to the target address */
957 fprintf (acfg->fp, "bctr\n");
959 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
960 *tramp_size = 11 * 4;
961 #else
962 *tramp_size = 9 * 4;
963 #endif
965 #else
966 g_assert_not_reached ();
967 #endif
971 * arch_emit_imt_thunk:
973 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
974 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
975 * key is the IMT key, and ptr holds the address of a memory location holding
976 * the address to branch to if the IMT arg matches the key. The array is
977 * terminated by a pair whose key is NULL, and whose ptr is the address of the
978 * fail_tramp.
979 * TRAMP_SIZE is set to the size of the emitted trampoline.
981 static void
982 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
984 #if defined(TARGET_AMD64)
985 guint8 *buf, *code;
986 guint8 *labels [3];
988 code = buf = g_malloc (256);
990 /* FIXME: Optimize this, i.e. use binary search etc. */
991 /* Maybe move the body into a separate function (slower, but much smaller) */
993 /* R10 is a free register */
995 labels [0] = code;
996 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
997 labels [1] = code;
998 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1000 /* Check key */
1001 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
1002 labels [2] = code;
1003 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1005 /* Loop footer */
1006 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
1007 amd64_jump_code (code, labels [0]);
1009 /* Match */
1010 mono_amd64_patch (labels [2], code);
1011 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
1012 amd64_jump_membase (code, AMD64_R10, 0);
1014 /* No match */
1015 /* FIXME: */
1016 mono_amd64_patch (labels [1], code);
1017 x86_breakpoint (code);
1019 /* mov <OFFSET>(%rip), %r10 */
1020 emit_byte (acfg, '\x4d');
1021 emit_byte (acfg, '\x8b');
1022 emit_byte (acfg, '\x15');
1023 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1025 emit_bytes (acfg, buf, code - buf);
1027 *tramp_size = code - buf + 7;
1028 #elif defined(TARGET_ARM)
1029 guint8 buf [128];
1030 guint8 *code, *code2, *labels [16];
1032 code = buf;
1034 /* The IMT method is in v5 */
1036 /* Need at least two free registers, plus a slot for storing the pc */
1037 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1038 labels [0] = code;
1039 /* Load the parameter from the GOT */
1040 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1041 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1043 labels [1] = code;
1044 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1045 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1046 labels [2] = code;
1047 ARM_B_COND (code, ARMCOND_EQ, 0);
1049 /* End-of-loop check */
1050 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1051 labels [3] = code;
1052 ARM_B_COND (code, ARMCOND_EQ, 0);
1054 /* Loop footer */
1055 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1056 labels [4] = code;
1057 ARM_B (code, 0);
1058 arm_patch (labels [4], labels [1]);
1060 /* Match */
1061 arm_patch (labels [2], code);
1062 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1063 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1064 /* Save it to the third stack slot */
1065 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1066 /* Restore the registers and branch */
1067 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1069 /* No match */
1070 arm_patch (labels [3], code);
1071 ARM_DBRK (code);
1073 /* Fixup offset */
1074 code2 = labels [0];
1075 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1077 emit_bytes (acfg, buf, code - buf);
1078 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1080 *tramp_size = code - buf + 4;
1081 #elif defined(TARGET_POWERPC)
1082 guint8 buf [128];
1083 guint8 *code, *labels [16];
1085 code = buf;
1087 /* Load the mscorlib got address */
1088 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1089 /* Load the parameter from the GOT */
1090 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1091 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1093 /* Load and check key */
1094 labels [1] = code;
1095 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1096 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1097 labels [2] = code;
1098 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1100 /* End-of-loop check */
1101 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1102 labels [3] = code;
1103 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1105 /* Loop footer */
1106 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1107 labels [4] = code;
1108 ppc_b (code, 0);
1109 mono_ppc_patch (labels [4], labels [1]);
1111 /* Match */
1112 mono_ppc_patch (labels [2], code);
1113 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1114 /* r11 now contains the value of the vtable slot */
1115 /* this is not a function descriptor on ppc64 */
1116 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1117 ppc_mtctr (code, ppc_r11);
1118 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1120 /* Fail */
1121 mono_ppc_patch (labels [3], code);
1122 /* FIXME: */
1123 ppc_break (code);
1125 *tramp_size = code - buf;
1127 emit_bytes (acfg, buf, code - buf);
1128 #else
1129 g_assert_not_reached ();
1130 #endif
1133 static void
1134 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1136 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1137 /* Based on code generated by gcc */
1138 img_writer_emit_unset_mode (acfg->w);
1140 fprintf (acfg->fp,
1141 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1142 ".section .ctors,\"aw\",@progbits\n"
1143 ".align 2\n"
1144 ".globl %s\n"
1145 ".long %s\n"
1146 ".section .opd,\"aw\"\n"
1147 ".align 2\n"
1148 "%s:\n"
1149 ".long .%s,.TOC.@tocbase32\n"
1150 ".size %s,.-%s\n"
1151 ".section .text\n"
1152 ".type .%s,@function\n"
1153 ".align 2\n"
1154 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1155 #else
1156 ".section .ctors,\"aw\",@progbits\n"
1157 ".align 2\n"
1158 ".globl %1$s\n"
1159 ".long %1$s\n"
1160 ".section .opd,\"aw\"\n"
1161 ".align 2\n"
1162 "%1$s:\n"
1163 ".long .%1$s,.TOC.@tocbase32\n"
1164 ".size %1$s,.-%1$s\n"
1165 ".section .text\n"
1166 ".type .%1$s,@function\n"
1167 ".align 2\n"
1168 ".%1$s:\n", symbol);
1169 #endif
1172 fprintf (acfg->fp,
1173 "stdu 1,-128(1)\n"
1174 "mflr 0\n"
1175 "std 31,120(1)\n"
1176 "std 0,144(1)\n"
1178 ".Lautoreg:\n"
1179 "lis 3, .Lglobals@h\n"
1180 "ori 3, 3, .Lglobals@l\n"
1181 "bl .mono_aot_register_module\n"
1182 "ld 11,0(1)\n"
1183 "ld 0,16(11)\n"
1184 "mtlr 0\n"
1185 "ld 31,-8(11)\n"
1186 "mr 1,11\n"
1187 "blr\n"
1189 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1190 fprintf (acfg->fp,
1191 ".size .%s,.-.%s\n", symbol, symbol);
1192 #else
1193 fprintf (acfg->fp,
1194 ".size .%1$s,.-.%1$s\n", symbol);
1195 #endif
1196 #else
1197 #endif
1200 /* END OF ARCH SPECIFIC CODE */
1202 static guint32
1203 mono_get_field_token (MonoClassField *field)
1205 MonoClass *klass = field->parent;
1206 int i;
1208 for (i = 0; i < klass->field.count; ++i) {
1209 if (field == &klass->fields [i])
1210 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1213 g_assert_not_reached ();
1214 return 0;
1217 static inline void
1218 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1220 guint8 *p = buf;
1222 //printf ("ENCODE: %d 0x%x.\n", value, value);
1225 * Same encoding as the one used in the metadata, extended to handle values
1226 * greater than 0x1fffffff.
1228 if ((value >= 0) && (value <= 127))
1229 *p++ = value;
1230 else if ((value >= 0) && (value <= 16383)) {
1231 p [0] = 0x80 | (value >> 8);
1232 p [1] = value & 0xff;
1233 p += 2;
1234 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1235 p [0] = (value >> 24) | 0xc0;
1236 p [1] = (value >> 16) & 0xff;
1237 p [2] = (value >> 8) & 0xff;
1238 p [3] = value & 0xff;
1239 p += 4;
1241 else {
1242 p [0] = 0xff;
1243 p [1] = (value >> 24) & 0xff;
1244 p [2] = (value >> 16) & 0xff;
1245 p [3] = (value >> 8) & 0xff;
1246 p [4] = value & 0xff;
1247 p += 5;
1249 if (endbuf)
1250 *endbuf = p;
1253 static void
1254 stream_init (MonoDynamicStream *sh)
1256 sh->index = 0;
1257 sh->alloc_size = 4096;
1258 sh->data = g_malloc (4096);
1260 /* So offsets are > 0 */
1261 sh->index ++;
1264 static void
1265 make_room_in_stream (MonoDynamicStream *stream, int size)
1267 if (size <= stream->alloc_size)
1268 return;
1270 while (stream->alloc_size <= size) {
1271 if (stream->alloc_size < 4096)
1272 stream->alloc_size = 4096;
1273 else
1274 stream->alloc_size *= 2;
1277 stream->data = g_realloc (stream->data, stream->alloc_size);
1280 static guint32
1281 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1283 guint32 idx;
1285 make_room_in_stream (stream, stream->index + len);
1286 memcpy (stream->data + stream->index, data, len);
1287 idx = stream->index;
1288 stream->index += len;
1289 return idx;
1293 * add_to_blob:
1295 * Add data to the binary blob inside the aot image. Returns the offset inside the
1296 * blob where the data was stored.
1298 static guint32
1299 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1301 if (acfg->blob.alloc_size == 0)
1302 stream_init (&acfg->blob);
1304 return add_stream_data (&acfg->blob, (char*)data, data_len);
1308 * emit_offset_table:
1310 * Emit a table of increasing offsets in a compact form using differential encoding.
1311 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1312 * group size, the more compact the table becomes, but the slower it becomes to compute
1313 * a given entry. Returns the size of the table.
1315 static guint32
1316 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1318 gint32 current_offset;
1319 int i, buf_size, ngroups, index_entry_size;
1320 guint8 *p, *buf;
1321 guint32 *index_offsets;
1323 ngroups = (noffsets + (group_size - 1)) / group_size;
1325 index_offsets = g_new0 (guint32, ngroups);
1327 buf_size = noffsets * 4;
1328 p = buf = g_malloc0 (buf_size);
1330 current_offset = 0;
1331 for (i = 0; i < noffsets; ++i) {
1332 //printf ("D: %d -> %d\n", i, offsets [i]);
1333 if ((i % group_size) == 0) {
1334 index_offsets [i / group_size] = p - buf;
1335 /* Emit the full value for these entries */
1336 encode_value (offsets [i], p, &p);
1337 } else {
1338 /* The offsets are allowed to be non-increasing */
1339 //g_assert (offsets [i] >= current_offset);
1340 encode_value (offsets [i] - current_offset, p, &p);
1342 current_offset = offsets [i];
1345 if (ngroups && index_offsets [ngroups - 1] < 65000)
1346 index_entry_size = 2;
1347 else
1348 index_entry_size = 4;
1350 /* Emit the header */
1351 emit_int32 (acfg, noffsets);
1352 emit_int32 (acfg, group_size);
1353 emit_int32 (acfg, ngroups);
1354 emit_int32 (acfg, index_entry_size);
1356 /* Emit the index */
1357 for (i = 0; i < ngroups; ++i) {
1358 if (index_entry_size == 2)
1359 emit_int16 (acfg, index_offsets [i]);
1360 else
1361 emit_int32 (acfg, index_offsets [i]);
1364 /* Emit the data */
1365 emit_bytes (acfg, buf, p - buf);
1367 return (int)(p - buf) + (ngroups * 4);
1370 static guint32
1371 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1373 guint32 index;
1375 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1376 if (index)
1377 return index - 1;
1378 else {
1379 index = g_hash_table_size (cfg->image_hash);
1380 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1381 g_ptr_array_add (cfg->image_table, image);
1382 return index;
1386 static guint32
1387 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1389 int i;
1390 MonoClass *k = NULL;
1392 /* FIXME: Search referenced images as well */
1393 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1394 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1395 if (k == klass)
1396 break;
1399 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1400 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1401 else
1402 return 0;
1405 static void
1406 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1409 * encode_klass_ref:
1411 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1412 * standard metadata encoding.
1414 static void
1415 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1417 guint8 *p = buf;
1419 if (klass->generic_class) {
1420 guint32 token;
1421 g_assert (klass->type_token);
1423 /* Find a typespec for a class if possible */
1424 token = find_typespec_for_class (acfg, klass);
1425 if (token) {
1426 encode_value (token, p, &p);
1427 encode_value (get_image_index (acfg, acfg->image), p, &p);
1428 } else {
1429 MonoClass *gclass = klass->generic_class->container_class;
1430 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1431 int i;
1433 /* Encode it ourselves */
1434 /* Marker */
1435 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1436 encode_value (MONO_TYPE_GENERICINST, p, &p);
1437 encode_klass_ref (acfg, gclass, p, &p);
1438 encode_value (inst->type_argc, p, &p);
1439 for (i = 0; i < inst->type_argc; ++i)
1440 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1442 } else if (klass->type_token) {
1443 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1444 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1445 encode_value (get_image_index (acfg, klass->image), p, &p);
1446 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1447 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1448 g_assert (container);
1450 /* Marker */
1451 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1452 encode_value (klass->byval_arg.type, p, &p);
1454 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1456 encode_value (container->is_method, p, &p);
1457 if (container->is_method)
1458 encode_method_ref (acfg, container->owner.method, p, &p);
1459 else
1460 encode_klass_ref (acfg, container->owner.klass, p, &p);
1461 } else {
1462 /* Array class */
1463 g_assert (klass->rank > 0);
1464 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1465 encode_value (get_image_index (acfg, klass->image), p, &p);
1466 encode_value (klass->rank, p, &p);
1467 encode_klass_ref (acfg, klass->element_class, p, &p);
1469 *endbuf = p;
1472 static void
1473 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1475 guint32 token = mono_get_field_token (field);
1476 guint8 *p = buf;
1478 encode_klass_ref (cfg, field->parent, p, &p);
1479 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1480 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1481 *endbuf = p;
1484 static void
1485 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1487 guint8 *p = buf;
1488 int i;
1489 MonoGenericInst *inst;
1491 /* Encode the context */
1492 inst = context->class_inst;
1493 encode_value (inst ? 1 : 0, p, &p);
1494 if (inst) {
1495 encode_value (inst->type_argc, p, &p);
1496 for (i = 0; i < inst->type_argc; ++i)
1497 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1499 inst = context->method_inst;
1500 encode_value (inst ? 1 : 0, p, &p);
1501 if (inst) {
1502 encode_value (inst->type_argc, p, &p);
1503 for (i = 0; i < inst->type_argc; ++i)
1504 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1507 *endbuf = p;
1510 #define MAX_IMAGE_INDEX 250
1512 static void
1513 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1515 guint32 image_index = get_image_index (acfg, method->klass->image);
1516 guint32 token = method->token;
1517 MonoJumpInfoToken *ji;
1518 guint8 *p = buf;
1519 char *name;
1522 * The encoding for most methods is as follows:
1523 * - image index encoded as a leb128
1524 * - token index encoded as a leb128
1525 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1526 * types of method encodings.
1529 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1531 /* Mark methods which can't use aot trampolines because they need the further
1532 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1534 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1535 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1536 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1539 * Some wrapper methods are shared using their signature, encode their
1540 * stringified signature instead.
1541 * FIXME: Optimize disk usage
1543 name = NULL;
1544 if (method->wrapper_type) {
1545 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1546 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1547 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1548 name = mono_aot_wrapper_name (method);
1549 } else if (mono_marshal_method_from_wrapper (method) != method) {
1550 /* Direct wrapper, encode it normally */
1551 } else {
1552 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1554 g_free (tmpsig);
1555 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1556 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1557 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1558 g_free (tmpsig);
1559 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1560 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1561 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1562 g_free (tmpsig);
1563 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1564 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1565 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1566 g_free (tmpsig);
1570 if (name) {
1571 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1572 strcpy ((char*)p, name);
1573 p += strlen (name) + 1;
1574 g_free (name);
1575 } else if (method->wrapper_type) {
1576 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1578 encode_value (method->wrapper_type, p, &p);
1580 switch (method->wrapper_type) {
1581 case MONO_WRAPPER_REMOTING_INVOKE:
1582 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1583 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1584 MonoMethod *m;
1586 m = mono_marshal_method_from_wrapper (method);
1587 g_assert (m);
1588 encode_method_ref (acfg, m, p, &p);
1589 break;
1591 case MONO_WRAPPER_PROXY_ISINST:
1592 case MONO_WRAPPER_LDFLD:
1593 case MONO_WRAPPER_LDFLDA:
1594 case MONO_WRAPPER_STFLD:
1595 case MONO_WRAPPER_ISINST: {
1596 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1597 encode_klass_ref (acfg, proxy_class, p, &p);
1598 break;
1600 case MONO_WRAPPER_LDFLD_REMOTE:
1601 case MONO_WRAPPER_STFLD_REMOTE:
1602 break;
1603 case MONO_WRAPPER_ALLOC: {
1604 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1606 g_assert (info->alloc_type != -1);
1607 encode_value (info->alloc_type, p, &p);
1608 break;
1610 case MONO_WRAPPER_WRITE_BARRIER:
1611 break;
1612 case MONO_WRAPPER_STELEMREF:
1613 break;
1614 case MONO_WRAPPER_UNKNOWN:
1615 if (strcmp (method->name, "FastMonitorEnter") == 0)
1616 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1617 else if (strcmp (method->name, "FastMonitorExit") == 0)
1618 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1619 else
1620 g_assert_not_reached ();
1621 break;
1622 case MONO_WRAPPER_SYNCHRONIZED:
1623 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1624 case MONO_WRAPPER_RUNTIME_INVOKE: {
1625 MonoMethod *m;
1627 m = mono_marshal_method_from_wrapper (method);
1628 g_assert (m);
1629 g_assert (m != method);
1630 encode_method_ref (acfg, m, p, &p);
1631 break;
1633 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1634 if (!strcmp (method->name, "ElementAddr")) {
1635 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1637 g_assert (info);
1638 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1639 encode_value (info->rank, p, &p);
1640 encode_value (info->elem_size, p, &p);
1641 } else {
1642 g_assert_not_reached ();
1644 break;
1645 default:
1646 g_assert_not_reached ();
1648 } else if (mono_method_signature (method)->is_inflated) {
1650 * This is a generic method, find the original token which referenced it and
1651 * encode that.
1652 * Obtain the token from information recorded by the JIT.
1654 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1655 if (ji) {
1656 image_index = get_image_index (acfg, ji->image);
1657 g_assert (image_index < MAX_IMAGE_INDEX);
1658 token = ji->token;
1660 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1661 encode_value (image_index, p, &p);
1662 encode_value (token, p, &p);
1663 } else {
1664 MonoMethod *declaring;
1665 MonoGenericContext *context = mono_method_get_context (method);
1667 g_assert (method->is_inflated);
1668 declaring = ((MonoMethodInflated*)method)->declaring;
1671 * This might be a non-generic method of a generic instance, which
1672 * doesn't have a token since the reference is generated by the JIT
1673 * like Nullable:Box/Unbox, or by generic sharing.
1676 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1677 /* Encode the klass */
1678 encode_klass_ref (acfg, method->klass, p, &p);
1679 /* Encode the method */
1680 image_index = get_image_index (acfg, method->klass->image);
1681 g_assert (image_index < MAX_IMAGE_INDEX);
1682 g_assert (declaring->token);
1683 token = declaring->token;
1684 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1685 encode_value (image_index, p, &p);
1686 encode_value (token, p, &p);
1687 encode_generic_context (acfg, context, p, &p);
1689 } else if (token == 0) {
1690 /* This might be a method of a constructed type like int[,].Set */
1691 /* Obtain the token from information recorded by the JIT */
1692 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1693 if (ji) {
1694 image_index = get_image_index (acfg, ji->image);
1695 g_assert (image_index < MAX_IMAGE_INDEX);
1696 token = ji->token;
1698 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1699 encode_value (image_index, p, &p);
1700 encode_value (token, p, &p);
1701 } else {
1702 /* Array methods */
1703 g_assert (method->klass->rank);
1705 /* Encode directly */
1706 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1707 encode_klass_ref (acfg, method->klass, p, &p);
1708 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1709 encode_value (0, p, &p);
1710 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1711 encode_value (1, p, &p);
1712 else if (!strcmp (method->name, "Get"))
1713 encode_value (2, p, &p);
1714 else if (!strcmp (method->name, "Address"))
1715 encode_value (3, p, &p);
1716 else if (!strcmp (method->name, "Set"))
1717 encode_value (4, p, &p);
1718 else
1719 g_assert_not_reached ();
1721 } else {
1722 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1723 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1725 *endbuf = p;
1728 static gint
1729 compare_patches (gconstpointer a, gconstpointer b)
1731 int i, j;
1733 i = (*(MonoJumpInfo**)a)->ip.i;
1734 j = (*(MonoJumpInfo**)b)->ip.i;
1736 if (i < j)
1737 return -1;
1738 else
1739 if (i > j)
1740 return 1;
1741 else
1742 return 0;
1746 * is_plt_patch:
1748 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1749 * PLT entry.
1751 static inline gboolean
1752 is_plt_patch (MonoJumpInfo *patch_info)
1754 switch (patch_info->type) {
1755 case MONO_PATCH_INFO_METHOD:
1756 case MONO_PATCH_INFO_INTERNAL_METHOD:
1757 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1758 case MONO_PATCH_INFO_ICALL_ADDR:
1759 case MONO_PATCH_INFO_CLASS_INIT:
1760 case MONO_PATCH_INFO_RGCTX_FETCH:
1761 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1762 case MONO_PATCH_INFO_MONITOR_ENTER:
1763 case MONO_PATCH_INFO_MONITOR_EXIT:
1764 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1765 return TRUE;
1766 default:
1767 return FALSE;
1771 static int
1772 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1774 int res = -1;
1776 if (is_plt_patch (patch_info)) {
1777 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1779 // FIXME: This breaks the calculation of final_got_size
1780 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1782 * Allocate a separate PLT slot for each such patch, since some plt
1783 * entries will refer to the method itself, and some will refer to the
1784 * wrapper.
1786 idx = 0;
1789 if (idx) {
1790 res = idx;
1791 } else {
1792 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1794 g_assert (!acfg->final_got_size);
1796 res = acfg->plt_offset;
1797 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1798 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1799 acfg->plt_offset ++;
1803 return res;
1807 * get_got_offset:
1809 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1810 * JI could be found if it exists, otherwise allocates a new one.
1812 static guint32
1813 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1815 guint32 got_offset;
1817 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1818 if (got_offset)
1819 return got_offset - 1;
1821 got_offset = acfg->got_offset;
1822 acfg->got_offset ++;
1824 if (acfg->final_got_size)
1825 g_assert (got_offset < acfg->final_got_size);
1827 acfg->stats.got_slots ++;
1828 acfg->stats.got_slot_types [ji->type] ++;
1830 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1831 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1832 g_ptr_array_add (acfg->got_patches, ji);
1834 return got_offset;
1837 /* Add a method to the list of methods which need to be emitted */
1838 static void
1839 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1841 g_assert (method);
1842 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1843 g_ptr_array_add (acfg->methods, method);
1844 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1845 acfg->nmethods = acfg->methods->len + 1;
1848 if (method->wrapper_type || extra)
1849 g_ptr_array_add (acfg->extra_methods, method);
1852 static guint32
1853 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1855 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1857 g_assert (index);
1859 return index - 1;
1862 static int
1863 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1865 int index;
1867 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1868 if (index)
1869 return index - 1;
1871 index = acfg->method_index;
1872 add_method_with_index (acfg, method, index, extra);
1874 /* FIXME: Fix quadratic behavior */
1875 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1877 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1879 acfg->method_index ++;
1881 return index;
1884 static int
1885 add_method (MonoAotCompile *acfg, MonoMethod *method)
1887 return add_method_full (acfg, method, FALSE, 0);
1890 static void
1891 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1893 add_method_full (acfg, method, TRUE, 0);
1896 static void
1897 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
1899 add_method_full (acfg, method, TRUE, depth);
1902 static void
1903 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1905 MonoAotCompile *acfg = user_data;
1906 MonoJitICallInfo *callinfo = value;
1907 MonoMethod *wrapper;
1908 char *name;
1910 if (!callinfo->sig)
1911 return;
1913 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1914 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1915 g_free (name);
1917 add_method (acfg, wrapper);
1920 static MonoMethod*
1921 get_runtime_invoke_sig (MonoMethodSignature *sig)
1923 MonoMethodBuilder *mb;
1924 MonoMethod *m;
1926 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1927 m = mono_mb_create_method (mb, sig, 16);
1928 return mono_marshal_get_runtime_invoke (m, FALSE);
1931 static gboolean
1932 can_marshal_struct (MonoClass *klass)
1934 MonoClassField *field;
1935 gboolean can_marshal = TRUE;
1936 gpointer iter = NULL;
1938 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1939 return FALSE;
1941 /* Only allow a few field types to avoid asserts in the marshalling code */
1942 while ((field = mono_class_get_fields (klass, &iter))) {
1943 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1944 continue;
1946 switch (field->type->type) {
1947 case MONO_TYPE_I4:
1948 case MONO_TYPE_U4:
1949 case MONO_TYPE_I1:
1950 case MONO_TYPE_U1:
1951 case MONO_TYPE_BOOLEAN:
1952 case MONO_TYPE_I2:
1953 case MONO_TYPE_U2:
1954 case MONO_TYPE_CHAR:
1955 case MONO_TYPE_I8:
1956 case MONO_TYPE_U8:
1957 case MONO_TYPE_I:
1958 case MONO_TYPE_U:
1959 case MONO_TYPE_PTR:
1960 case MONO_TYPE_R4:
1961 case MONO_TYPE_R8:
1962 case MONO_TYPE_STRING:
1963 break;
1964 case MONO_TYPE_VALUETYPE:
1965 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
1966 can_marshal = FALSE;
1967 break;
1968 default:
1969 can_marshal = FALSE;
1970 break;
1974 /* Special cases */
1975 /* Its hard to compute whenever these can be marshalled or not */
1976 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
1977 return TRUE;
1979 return can_marshal;
1982 static void
1983 add_wrappers (MonoAotCompile *acfg)
1985 MonoMethod *method, *m;
1986 int i, j;
1987 MonoMethodSignature *sig, *csig;
1988 guint32 token;
1991 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1992 * so there is only one wrapper of a given type, or inlining their contents into their
1993 * callers.
1997 * FIXME: This depends on the fact that different wrappers have different
1998 * names.
2001 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2002 MonoMethod *method;
2003 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2004 gboolean skip = FALSE;
2006 method = mono_get_method (acfg->image, token, NULL);
2008 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2009 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2010 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2011 skip = TRUE;
2013 if (method->is_generic || method->klass->generic_container)
2014 skip = TRUE;
2016 /* Skip methods which can not be handled by get_runtime_invoke () */
2017 sig = mono_method_signature (method);
2018 if ((sig->ret->type == MONO_TYPE_PTR) ||
2019 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2020 skip = TRUE;
2022 for (j = 0; j < sig->param_count; j++) {
2023 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2024 skip = TRUE;
2027 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2028 if (!method->klass->contextbound) {
2029 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2030 gboolean has_nullable = FALSE;
2032 for (j = 0; j < sig->param_count; j++) {
2033 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2034 has_nullable = TRUE;
2037 if (info && !has_nullable) {
2038 /* Supported by the dynamic runtime-invoke wrapper */
2039 skip = TRUE;
2040 g_free (info);
2043 #endif
2045 if (!skip) {
2046 //printf ("%s\n", mono_method_full_name (method, TRUE));
2047 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2051 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2052 #ifdef MONO_ARCH_HAVE_TLS_GET
2053 MonoMethodDesc *desc;
2054 MonoMethod *orig_method;
2055 int nallocators;
2056 #endif
2058 /* Runtime invoke wrappers */
2060 /* void runtime-invoke () [.cctor] */
2061 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2062 csig->ret = &mono_defaults.void_class->byval_arg;
2063 add_method (acfg, get_runtime_invoke_sig (csig));
2065 /* void runtime-invoke () [Finalize] */
2066 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2067 csig->hasthis = 1;
2068 csig->ret = &mono_defaults.void_class->byval_arg;
2069 add_method (acfg, get_runtime_invoke_sig (csig));
2071 /* void runtime-invoke (string) [exception ctor] */
2072 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2073 csig->hasthis = 1;
2074 csig->ret = &mono_defaults.void_class->byval_arg;
2075 csig->params [0] = &mono_defaults.string_class->byval_arg;
2076 add_method (acfg, get_runtime_invoke_sig (csig));
2078 /* void runtime-invoke (string, string) [exception ctor] */
2079 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2080 csig->hasthis = 1;
2081 csig->ret = &mono_defaults.void_class->byval_arg;
2082 csig->params [0] = &mono_defaults.string_class->byval_arg;
2083 csig->params [1] = &mono_defaults.string_class->byval_arg;
2084 add_method (acfg, get_runtime_invoke_sig (csig));
2086 /* string runtime-invoke () [Exception.ToString ()] */
2087 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2088 csig->hasthis = 1;
2089 csig->ret = &mono_defaults.string_class->byval_arg;
2090 add_method (acfg, get_runtime_invoke_sig (csig));
2092 /* void runtime-invoke (string, Exception) [exception ctor] */
2093 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2094 csig->hasthis = 1;
2095 csig->ret = &mono_defaults.void_class->byval_arg;
2096 csig->params [0] = &mono_defaults.string_class->byval_arg;
2097 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2098 add_method (acfg, get_runtime_invoke_sig (csig));
2100 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2101 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2102 csig->hasthis = 1;
2103 csig->ret = &(mono_class_from_name (
2104 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2105 csig->params [0] = &mono_defaults.string_class->byval_arg;
2106 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2107 add_method (acfg, get_runtime_invoke_sig (csig));
2109 /* runtime-invoke used by finalizers */
2110 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2112 /* This is used by mono_runtime_capture_context () */
2113 method = mono_get_context_capture_method ();
2114 if (method)
2115 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2117 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2118 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2119 #endif
2121 /* JIT icall wrappers */
2122 /* FIXME: locking */
2123 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2125 /* stelemref */
2126 add_method (acfg, mono_marshal_get_stelemref ());
2128 #ifdef MONO_ARCH_HAVE_TLS_GET
2129 /* Managed Allocators */
2130 nallocators = mono_gc_get_managed_allocator_types ();
2131 for (i = 0; i < nallocators; ++i) {
2132 m = mono_gc_get_managed_allocator_by_type (i);
2133 if (m)
2134 add_method (acfg, m);
2137 /* Monitor Enter/Exit */
2138 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2139 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2140 g_assert (orig_method);
2141 mono_method_desc_free (desc);
2142 method = mono_monitor_get_fast_path (orig_method);
2143 if (method)
2144 add_method (acfg, method);
2146 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2147 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2148 g_assert (orig_method);
2149 mono_method_desc_free (desc);
2150 method = mono_monitor_get_fast_path (orig_method);
2151 if (method)
2152 add_method (acfg, method);
2153 #endif
2157 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2158 * we use the original method instead at runtime.
2159 * Since full-aot doesn't support remoting, this is not a problem.
2161 #if 0
2162 /* remoting-invoke wrappers */
2163 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2164 MonoMethodSignature *sig;
2166 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2167 method = mono_get_method (acfg->image, token, NULL);
2169 sig = mono_method_signature (method);
2171 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2172 m = mono_marshal_get_remoting_invoke_with_check (method);
2174 add_method (acfg, m);
2177 #endif
2179 /* delegate-invoke wrappers */
2180 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2181 MonoClass *klass;
2183 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2184 klass = mono_class_get (acfg->image, token);
2186 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2187 method = mono_get_delegate_invoke (klass);
2189 m = mono_marshal_get_delegate_invoke (method, NULL);
2191 add_method (acfg, m);
2193 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2194 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2196 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2197 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2201 /* Synchronized wrappers */
2202 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2203 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2204 method = mono_get_method (acfg->image, token, NULL);
2206 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2207 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2210 /* pinvoke wrappers */
2211 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2212 MonoMethod *method;
2213 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2215 method = mono_get_method (acfg->image, token, NULL);
2217 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2218 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2219 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2223 /* native-to-managed wrappers */
2224 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2225 MonoMethod *method;
2226 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2227 MonoCustomAttrInfo *cattr;
2228 int j;
2230 method = mono_get_method (acfg->image, token, NULL);
2233 * Only generate native-to-managed wrappers for methods which have an
2234 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2235 * name to avoid defining a new assembly to contain it.
2237 cattr = mono_custom_attrs_from_method (method);
2239 if (cattr) {
2240 for (j = 0; j < cattr->num_attrs; ++j)
2241 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2242 break;
2243 if (j < cattr->num_attrs) {
2244 MonoCustomAttrEntry *e = &cattr->attrs [j];
2245 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2246 const char *p = (const char*)e->data;
2247 int slen;
2248 char *n;
2249 MonoType *t;
2250 MonoClass *klass;
2252 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2254 g_assert (sig->param_count == 1);
2255 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2258 * Decode the cattr manually since we can't create objects
2259 * during aot compilation.
2262 /* Skip prolog */
2263 p += 2;
2265 /* From load_cattr_value () in reflection.c */
2266 slen = mono_metadata_decode_value (p, &p);
2267 n = g_memdup (p, slen + 1);
2268 n [slen] = 0;
2269 t = mono_reflection_type_from_name (n, acfg->image);
2270 g_assert (t);
2271 g_free (n);
2273 klass = mono_class_from_mono_type (t);
2274 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2276 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, NULL));
2280 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2281 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2282 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2286 /* StructureToPtr/PtrToStructure wrappers */
2287 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2288 MonoClass *klass;
2290 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2291 klass = mono_class_get (acfg->image, token);
2293 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2294 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2295 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2300 static gboolean
2301 has_type_vars (MonoClass *klass)
2303 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2304 return TRUE;
2305 if (klass->rank)
2306 return has_type_vars (klass->element_class);
2307 if (klass->generic_class) {
2308 MonoGenericContext *context = &klass->generic_class->context;
2309 if (context->class_inst) {
2310 int i;
2312 for (i = 0; i < context->class_inst->type_argc; ++i)
2313 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2314 return TRUE;
2317 return FALSE;
2320 static gboolean
2321 method_has_type_vars (MonoMethod *method)
2323 if (has_type_vars (method->klass))
2324 return TRUE;
2326 if (method->is_inflated) {
2327 MonoGenericContext *context = mono_method_get_context (method);
2328 if (context->method_inst) {
2329 int i;
2331 for (i = 0; i < context->method_inst->type_argc; ++i)
2332 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2333 return TRUE;
2336 return FALSE;
2340 * add_generic_class:
2342 * Add all methods of a generic class.
2344 static void
2345 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2347 MonoMethod *method;
2348 gpointer iter;
2350 mono_class_init (klass);
2352 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2353 return;
2355 if (has_type_vars (klass))
2356 return;
2358 if (!klass->generic_class && !klass->rank)
2359 return;
2361 iter = NULL;
2362 while ((method = mono_class_get_methods (klass, &iter))) {
2363 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2364 /* Already added */
2365 continue;
2367 if (method->is_generic)
2368 /* FIXME: */
2369 continue;
2372 * FIXME: Instances which are referenced by these methods are not added,
2373 * for example Array.Resize<int> for List<int>.Add ().
2375 add_extra_method (acfg, method);
2378 if (klass->delegate) {
2379 method = mono_get_delegate_invoke (klass);
2381 method = mono_marshal_get_delegate_invoke (method, NULL);
2383 add_method (acfg, method);
2387 * For ICollection<T>, add instances of the helper methods
2388 * in Array, since a T[] could be cast to ICollection<T>.
2390 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2391 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2392 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2393 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2394 gpointer iter;
2395 char *name_prefix;
2397 if (!strcmp (klass->name, "IEnumerator`1"))
2398 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2399 else
2400 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2402 /* Add the T[]/InternalEnumerator class */
2403 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2404 MonoClass *nclass;
2406 iter = NULL;
2407 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2408 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2409 break;
2411 g_assert (nclass);
2412 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2413 add_generic_class (acfg, nclass);
2416 iter = NULL;
2417 while ((method = mono_class_get_methods (array_class, &iter))) {
2418 if (strstr (method->name, name_prefix)) {
2419 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2420 add_extra_method (acfg, m);
2424 g_free (name_prefix);
2427 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2428 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2429 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2430 MonoClass *icomparable, *gcomparer;
2431 MonoGenericContext ctx;
2432 MonoType *args [16];
2434 memset (&ctx, 0, sizeof (ctx));
2436 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2437 g_assert (icomparable);
2438 args [0] = &tclass->byval_arg;
2439 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2441 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2442 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2443 g_assert (gcomparer);
2444 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2449 static void
2450 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2452 int i;
2453 MonoGenericContext ctx;
2454 MonoType *args [16];
2456 memset (&ctx, 0, sizeof (ctx));
2458 for (i = 0; i < ninsts; ++i) {
2459 args [0] = insts [i];
2460 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2461 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2466 * add_generic_instances:
2468 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2470 static void
2471 add_generic_instances (MonoAotCompile *acfg)
2473 int i;
2474 guint32 token;
2475 MonoMethod *method;
2476 MonoMethodHeader *header;
2477 MonoMethodSignature *sig;
2478 MonoGenericContext *context;
2480 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2481 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2482 method = mono_get_method (acfg->image, token, NULL);
2484 if (method->klass->image != acfg->image)
2485 continue;
2487 context = mono_method_get_context (method);
2489 if (context && ((context->class_inst && context->class_inst->is_open)))
2490 continue;
2493 * For open methods, create an instantiation which can be passed to the JIT.
2494 * FIXME: Handle class_inst as well.
2496 if (context && context->method_inst && context->method_inst->is_open) {
2497 MonoGenericContext shared_context;
2498 MonoGenericInst *inst;
2499 MonoType **type_argv;
2500 int i;
2501 MonoMethod *declaring_method;
2502 gboolean supported = TRUE;
2504 /* Check that the context doesn't contain open constructed types */
2505 if (context->class_inst) {
2506 inst = context->class_inst;
2507 for (i = 0; i < inst->type_argc; ++i) {
2508 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)
2509 continue;
2510 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2511 supported = FALSE;
2514 if (context->method_inst) {
2515 inst = context->method_inst;
2516 for (i = 0; i < inst->type_argc; ++i) {
2517 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)
2518 continue;
2519 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2520 supported = FALSE;
2524 if (!supported)
2525 continue;
2527 memset (&shared_context, 0, sizeof (MonoGenericContext));
2529 inst = context->class_inst;
2530 if (inst) {
2531 type_argv = g_new0 (MonoType*, inst->type_argc);
2532 for (i = 0; i < inst->type_argc; ++i) {
2533 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)
2534 type_argv [i] = &mono_defaults.object_class->byval_arg;
2535 else
2536 type_argv [i] = inst->type_argv [i];
2539 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2540 g_free (type_argv);
2543 inst = context->method_inst;
2544 if (inst) {
2545 type_argv = g_new0 (MonoType*, inst->type_argc);
2546 for (i = 0; i < inst->type_argc; ++i) {
2547 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)
2548 type_argv [i] = &mono_defaults.object_class->byval_arg;
2549 else
2550 type_argv [i] = inst->type_argv [i];
2553 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2554 g_free (type_argv);
2557 if (method->is_generic || method->klass->generic_container)
2558 declaring_method = method;
2559 else
2560 declaring_method = mono_method_get_declaring_generic_method (method);
2562 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2566 * If the method is fully sharable, it was already added in place of its
2567 * generic definition.
2569 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2570 continue;
2573 * FIXME: Partially shared methods are not shared here, so we end up with
2574 * many identical methods.
2576 add_extra_method (acfg, method);
2579 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2580 MonoClass *klass;
2582 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2584 klass = mono_class_get (acfg->image, token);
2585 if (!klass || klass->rank)
2586 continue;
2588 add_generic_class (acfg, klass);
2591 /* Add types of args/locals */
2592 for (i = 0; i < acfg->methods->len; ++i) {
2593 int j;
2595 method = g_ptr_array_index (acfg->methods, i);
2597 sig = mono_method_signature (method);
2599 if (sig) {
2600 for (j = 0; j < sig->param_count; ++j)
2601 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2602 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2605 header = mono_method_get_header (method);
2607 if (header) {
2608 for (j = 0; j < header->num_locals; ++j)
2609 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2610 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2614 if (acfg->image == mono_defaults.corlib) {
2615 MonoClass *klass;
2616 MonoType *insts [256];
2617 int ninsts = 0;
2619 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2620 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2621 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2622 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2623 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2624 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2625 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2626 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2627 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2628 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2629 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2630 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2632 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2633 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2634 if (klass)
2635 add_instances_of (acfg, klass, insts, ninsts);
2636 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2637 if (klass)
2638 add_instances_of (acfg, klass, insts, ninsts);
2640 /* Add instances of the array generic interfaces for primitive types */
2641 /* This will add instances of the InternalArray_ helper methods in Array too */
2642 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2643 if (klass)
2644 add_instances_of (acfg, klass, insts, ninsts);
2645 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2646 if (klass)
2647 add_instances_of (acfg, klass, insts, ninsts);
2648 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2649 if (klass)
2650 add_instances_of (acfg, klass, insts, ninsts);
2653 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2654 * used for all instances of GetGenericValueImpl by the AOT runtime.
2657 MonoGenericContext ctx;
2658 MonoType *args [16];
2659 MonoMethod *get_method;
2660 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2662 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2664 if (get_method) {
2665 memset (&ctx, 0, sizeof (ctx));
2666 args [0] = &mono_defaults.object_class->byval_arg;
2667 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2668 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2675 * is_direct_callable:
2677 * Return whenever the method identified by JI is directly callable without
2678 * going through the PLT.
2680 static gboolean
2681 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2683 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2684 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2685 if (callee_cfg) {
2686 gboolean direct_callable = TRUE;
2688 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2689 direct_callable = FALSE;
2690 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2691 // FIXME: Maybe call the wrapper directly ?
2692 direct_callable = FALSE;
2694 if (direct_callable)
2695 return TRUE;
2699 return FALSE;
2703 * emit_and_reloc_code:
2705 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2706 * is true, calls are made through the GOT too. This is used for emitting trampolines
2707 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2708 * since trampolines are needed to make PTL work.
2710 static void
2711 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2713 int i, pindex, start_index, method_index;
2714 GPtrArray *patches;
2715 MonoJumpInfo *patch_info;
2716 MonoMethodHeader *header;
2717 gboolean skip, direct_call;
2718 guint32 got_slot;
2719 char direct_call_target [128];
2721 if (method) {
2722 header = mono_method_get_header (method);
2724 method_index = get_method_index (acfg, method);
2727 /* Collect and sort relocations */
2728 patches = g_ptr_array_new ();
2729 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2730 g_ptr_array_add (patches, patch_info);
2731 g_ptr_array_sort (patches, compare_patches);
2733 start_index = 0;
2734 for (i = 0; i < code_len; i++) {
2735 patch_info = NULL;
2736 for (pindex = start_index; pindex < patches->len; ++pindex) {
2737 patch_info = g_ptr_array_index (patches, pindex);
2738 if (patch_info->ip.i >= i)
2739 break;
2742 #ifdef MONO_ARCH_AOT_SUPPORTED
2743 skip = FALSE;
2744 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2745 start_index = pindex;
2747 switch (patch_info->type) {
2748 case MONO_PATCH_INFO_NONE:
2749 break;
2750 case MONO_PATCH_INFO_GOT_OFFSET: {
2751 int code_size;
2753 arch_emit_got_offset (acfg, code + i, &code_size);
2754 i += code_size - 1;
2755 skip = TRUE;
2756 patch_info->type = MONO_PATCH_INFO_NONE;
2757 break;
2759 default: {
2761 * If this patch is a call, try emitting a direct call instead of
2762 * through a PLT entry. This is possible if the called method is in
2763 * the same assembly and requires no initialization.
2765 direct_call = FALSE;
2766 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2767 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2768 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2769 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2770 direct_call = TRUE;
2771 sprintf (direct_call_target, callee_cfg->asm_symbol);
2772 patch_info->type = MONO_PATCH_INFO_NONE;
2773 acfg->stats.direct_calls ++;
2776 acfg->stats.all_calls ++;
2779 if (!got_only && !direct_call) {
2780 int plt_offset = get_plt_offset (acfg, patch_info);
2781 if (plt_offset != -1) {
2782 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2783 direct_call = TRUE;
2784 sprintf (direct_call_target, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
2786 /* Nullify the patch */
2787 patch_info->type = MONO_PATCH_INFO_NONE;
2791 if (direct_call) {
2792 int call_size;
2794 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2795 i += call_size - 1;
2796 } else {
2797 int code_size;
2799 got_slot = get_got_offset (acfg, patch_info);
2801 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2802 i += code_size - 1;
2804 skip = TRUE;
2808 #endif /* MONO_ARCH_AOT_SUPPORTED */
2810 if (!skip) {
2811 /* Find next patch */
2812 patch_info = NULL;
2813 for (pindex = start_index; pindex < patches->len; ++pindex) {
2814 patch_info = g_ptr_array_index (patches, pindex);
2815 if (patch_info->ip.i >= i)
2816 break;
2819 /* Try to emit multiple bytes at once */
2820 if (pindex < patches->len && patch_info->ip.i > i) {
2821 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2822 i = patch_info->ip.i - 1;
2823 } else {
2824 emit_bytes (acfg, code + i, 1);
2831 * sanitize_symbol:
2833 * Modify SYMBOL so it only includes characters permissible in symbols.
2835 static void
2836 sanitize_symbol (char *symbol)
2838 int i, len = strlen (symbol);
2840 for (i = 0; i < len; ++i)
2841 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2842 symbol [i] = '_';
2845 static char*
2846 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2848 char *name1, *name2, *cached;
2849 int i, j, len, count;
2851 name1 = mono_method_full_name (method, TRUE);
2852 len = strlen (name1);
2853 name2 = malloc (strlen (prefix) + len + 16);
2854 memcpy (name2, prefix, strlen (prefix));
2855 j = strlen (prefix);
2856 for (i = 0; i < len; ++i) {
2857 if (isalnum (name1 [i])) {
2858 name2 [j ++] = name1 [i];
2859 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2860 i += 2;
2861 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2862 name2 [j ++] = '_';
2863 i++;
2864 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2865 } else
2866 name2 [j ++] = '_';
2868 name2 [j] = '\0';
2870 g_free (name1);
2872 count = 0;
2873 while (g_hash_table_lookup (cache, name2)) {
2874 sprintf (name2 + j, "_%d", count);
2875 count ++;
2878 cached = g_strdup (name2);
2879 g_hash_table_insert (cache, cached, cached);
2881 return name2;
2884 static void
2885 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2887 MonoMethod *method;
2888 int method_index;
2889 guint8 *code;
2890 char *debug_sym = NULL;
2891 char symbol [128];
2892 int func_alignment = AOT_FUNC_ALIGNMENT;
2893 MonoMethodHeader *header;
2895 method = cfg->orig_method;
2896 code = cfg->native_code;
2897 header = mono_method_get_header (method);
2899 method_index = get_method_index (acfg, method);
2901 /* Make the labels local */
2902 sprintf (symbol, "%s", cfg->asm_symbol);
2904 emit_section_change (acfg, ".text", 0);
2905 emit_alignment (acfg, func_alignment);
2906 emit_label (acfg, symbol);
2908 if (acfg->aot_opts.write_symbols) {
2910 * Write a C style symbol for every method, this has two uses:
2911 * - it works on platforms where the dwarf debugging info is not
2912 * yet supported.
2913 * - it allows the setting of breakpoints of aot-ed methods.
2915 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2917 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2918 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2919 emit_label (acfg, debug_sym);
2922 if (cfg->verbose_level > 0)
2923 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2925 acfg->stats.code_size += cfg->code_len;
2927 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2929 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2931 emit_line (acfg);
2933 if (acfg->aot_opts.write_symbols) {
2934 emit_symbol_size (acfg, debug_sym, ".");
2935 g_free (debug_sym);
2938 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2939 emit_label (acfg, symbol);
2943 * encode_patch:
2945 * Encode PATCH_INFO into its disk representation.
2947 static void
2948 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2950 guint8 *p = buf;
2952 switch (patch_info->type) {
2953 case MONO_PATCH_INFO_NONE:
2954 break;
2955 case MONO_PATCH_INFO_IMAGE:
2956 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2957 break;
2958 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2959 break;
2960 case MONO_PATCH_INFO_METHOD_REL:
2961 encode_value ((gint)patch_info->data.offset, p, &p);
2962 break;
2963 case MONO_PATCH_INFO_SWITCH: {
2964 gpointer *table = (gpointer *)patch_info->data.table->table;
2965 int k;
2967 encode_value (patch_info->data.table->table_size, p, &p);
2968 for (k = 0; k < patch_info->data.table->table_size; k++)
2969 encode_value ((int)(gssize)table [k], p, &p);
2970 break;
2972 case MONO_PATCH_INFO_METHODCONST:
2973 case MONO_PATCH_INFO_METHOD:
2974 case MONO_PATCH_INFO_METHOD_JUMP:
2975 case MONO_PATCH_INFO_ICALL_ADDR:
2976 case MONO_PATCH_INFO_METHOD_RGCTX:
2977 encode_method_ref (acfg, patch_info->data.method, p, &p);
2978 break;
2979 case MONO_PATCH_INFO_INTERNAL_METHOD:
2980 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2981 guint32 len = strlen (patch_info->data.name);
2983 encode_value (len, p, &p);
2985 memcpy (p, patch_info->data.name, len);
2986 p += len;
2987 *p++ = '\0';
2988 break;
2990 case MONO_PATCH_INFO_LDSTR: {
2991 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2992 guint32 token = patch_info->data.token->token;
2993 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2994 encode_value (image_index, p, &p);
2995 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2996 break;
2998 case MONO_PATCH_INFO_RVA:
2999 case MONO_PATCH_INFO_DECLSEC:
3000 case MONO_PATCH_INFO_LDTOKEN:
3001 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3002 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3003 encode_value (patch_info->data.token->token, p, &p);
3004 encode_value (patch_info->data.token->has_context, p, &p);
3005 if (patch_info->data.token->has_context)
3006 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3007 break;
3008 case MONO_PATCH_INFO_EXC_NAME: {
3009 MonoClass *ex_class;
3011 ex_class =
3012 mono_class_from_name (mono_defaults.exception_class->image,
3013 "System", patch_info->data.target);
3014 g_assert (ex_class);
3015 encode_klass_ref (acfg, ex_class, p, &p);
3016 break;
3018 case MONO_PATCH_INFO_R4:
3019 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3020 break;
3021 case MONO_PATCH_INFO_R8:
3022 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3023 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3024 break;
3025 case MONO_PATCH_INFO_VTABLE:
3026 case MONO_PATCH_INFO_CLASS:
3027 case MONO_PATCH_INFO_IID:
3028 case MONO_PATCH_INFO_ADJUSTED_IID:
3029 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3030 break;
3031 case MONO_PATCH_INFO_CLASS_INIT:
3032 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3033 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3034 break;
3035 case MONO_PATCH_INFO_FIELD:
3036 case MONO_PATCH_INFO_SFLDA:
3037 encode_field_info (acfg, patch_info->data.field, p, &p);
3038 break;
3039 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3040 break;
3041 case MONO_PATCH_INFO_RGCTX_FETCH: {
3042 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3044 encode_method_ref (acfg, entry->method, p, &p);
3045 encode_value (entry->in_mrgctx, p, &p);
3046 encode_value (entry->info_type, p, &p);
3047 encode_value (entry->data->type, p, &p);
3048 encode_patch (acfg, entry->data, p, &p);
3049 break;
3051 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3052 case MONO_PATCH_INFO_MONITOR_ENTER:
3053 case MONO_PATCH_INFO_MONITOR_EXIT:
3054 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3055 break;
3056 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3057 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3058 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3059 break;
3060 default:
3061 g_warning ("unable to handle jump info %d", patch_info->type);
3062 g_assert_not_reached ();
3065 *endbuf = p;
3068 static void
3069 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3071 guint8 *p = buf;
3072 guint32 pindex, offset;
3073 MonoJumpInfo *patch_info;
3075 encode_value (n_patches, p, &p);
3077 for (pindex = 0; pindex < patches->len; ++pindex) {
3078 patch_info = g_ptr_array_index (patches, pindex);
3080 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3081 /* Nothing to do */
3082 continue;
3084 offset = get_got_offset (acfg, patch_info);
3085 encode_value (offset, p, &p);
3088 *endbuf = p;
3091 static void
3092 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3094 MonoMethod *method;
3095 GList *l;
3096 int pindex, buf_size, n_patches;
3097 guint8 *code;
3098 GPtrArray *patches;
3099 MonoJumpInfo *patch_info;
3100 MonoMethodHeader *header;
3101 guint32 method_index;
3102 guint8 *p, *buf;
3103 guint32 first_got_offset;
3105 method = cfg->orig_method;
3106 code = cfg->native_code;
3107 header = mono_method_get_header (method);
3109 method_index = get_method_index (acfg, method);
3111 /* Sort relocations */
3112 patches = g_ptr_array_new ();
3113 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3114 g_ptr_array_add (patches, patch_info);
3115 g_ptr_array_sort (patches, compare_patches);
3117 first_got_offset = acfg->cfgs [method_index]->got_offset;
3119 /**********************/
3120 /* Encode method info */
3121 /**********************/
3123 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3124 p = buf = g_malloc (buf_size);
3126 if (mono_class_get_cctor (method->klass))
3127 encode_klass_ref (acfg, method->klass, p, &p);
3128 else
3129 /* Not needed when loading the method */
3130 encode_value (0, p, &p);
3132 /* String table */
3133 if (cfg->opt & MONO_OPT_SHARED) {
3134 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3135 for (l = cfg->ldstr_list; l; l = l->next) {
3136 encode_value ((long)l->data, p, &p);
3139 else
3140 /* Used only in shared mode */
3141 g_assert (!cfg->ldstr_list);
3143 n_patches = 0;
3144 for (pindex = 0; pindex < patches->len; ++pindex) {
3145 patch_info = g_ptr_array_index (patches, pindex);
3147 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3148 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3149 patch_info->type = MONO_PATCH_INFO_NONE;
3150 /* Nothing to do */
3151 continue;
3154 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3155 /* Stored in a GOT slot initialized at module load time */
3156 patch_info->type = MONO_PATCH_INFO_NONE;
3157 continue;
3160 if (is_plt_patch (patch_info)) {
3161 /* Calls are made through the PLT */
3162 patch_info->type = MONO_PATCH_INFO_NONE;
3163 continue;
3166 n_patches ++;
3169 if (n_patches)
3170 g_assert (cfg->has_got_slots);
3172 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3174 acfg->stats.info_size += p - buf;
3176 g_assert (p - buf < buf_size);
3178 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3179 g_free (buf);
3182 static guint32
3183 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3185 guint32 cache_index;
3186 guint32 offset;
3188 /* Reuse the unwind module to canonize and store unwind info entries */
3189 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3191 /* Use +/- 1 to distinguish 0s from missing entries */
3192 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3193 if (offset)
3194 return offset - 1;
3195 else {
3196 guint8 buf [16];
3197 guint8 *p;
3200 * It would be easier to use assembler symbols, but the caller needs an
3201 * offset now.
3203 offset = acfg->unwind_info_offset;
3204 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3205 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3207 p = buf;
3208 encode_value (encoded_len, p, &p);
3210 acfg->unwind_info_offset += encoded_len + (p - buf);
3211 return offset;
3215 static void
3216 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3218 MonoMethod *method;
3219 int i, k, buf_size, method_index;
3220 guint32 debug_info_size;
3221 guint8 *code;
3222 MonoMethodHeader *header;
3223 guint8 *p, *buf, *debug_info;
3224 MonoJitInfo *jinfo = cfg->jit_info;
3225 guint32 flags;
3226 gboolean use_unwind_ops = FALSE;
3227 MonoSeqPointInfo *seq_points;
3229 method = cfg->orig_method;
3230 code = cfg->native_code;
3231 header = mono_method_get_header (method);
3233 method_index = get_method_index (acfg, method);
3235 if (!acfg->aot_opts.nodebug) {
3236 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3237 } else {
3238 debug_info = NULL;
3239 debug_info_size = 0;
3242 seq_points = cfg->seq_point_info;
3244 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3245 p = buf = g_malloc (buf_size);
3247 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3248 use_unwind_ops = cfg->unwind_ops != NULL;
3249 #endif
3251 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);
3253 encode_value (flags, p, &p);
3255 if (use_unwind_ops) {
3256 guint32 encoded_len;
3257 guint8 *encoded;
3260 * This is a duplicate of the data in the .debug_frame section, but that
3261 * section cannot be accessed using the dl interface.
3263 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3264 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3265 g_free (encoded);
3266 } else {
3267 encode_value (jinfo->used_regs, p, &p);
3270 /*Encode the number of holes before the number of clauses to make decoding easier*/
3271 if (jinfo->has_try_block_holes) {
3272 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3273 encode_value (table->num_holes, p, &p);
3276 /* Exception table */
3277 if (cfg->compile_llvm) {
3278 /* The assembly might be CIL stripped so emit the data ourselves */
3279 if (header->num_clauses)
3280 encode_value (header->num_clauses, p, &p);
3282 for (k = 0; k < header->num_clauses; ++k) {
3283 MonoExceptionClause *clause;
3285 clause = &header->clauses [k];
3287 encode_value (clause->flags, p, &p);
3288 if (clause->data.catch_class) {
3289 encode_value (1, p, &p);
3290 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3291 } else {
3292 encode_value (0, p, &p);
3295 } else {
3296 if (jinfo->num_clauses)
3297 encode_value (jinfo->num_clauses, p, &p);
3299 for (k = 0; k < jinfo->num_clauses; ++k) {
3300 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3302 encode_value (ei->flags, p, &p);
3303 encode_value (ei->exvar_offset, p, &p);
3305 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3306 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3307 else {
3308 if (ei->data.catch_class) {
3309 encode_value (1, p, &p);
3310 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3311 } else {
3312 encode_value (0, p, &p);
3316 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3317 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3318 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3322 if (jinfo->has_generic_jit_info) {
3323 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3325 encode_value (gi->has_this ? 1 : 0, p, &p);
3326 encode_value (gi->this_reg, p, &p);
3327 encode_value (gi->this_offset, p, &p);
3330 * Need to encode jinfo->method too, since it is not equal to 'method'
3331 * when using generic sharing.
3333 encode_method_ref (acfg, jinfo->method, p, &p);
3336 if (jinfo->has_try_block_holes) {
3337 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3338 for (i = 0; i < table->num_holes; ++i) {
3339 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3340 encode_value (hole->clause, p, &p);
3341 encode_value (hole->length, p, &p);
3342 encode_value (hole->offset, p, &p);
3346 if (seq_points) {
3347 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3349 encode_value (seq_points->len, p, &p);
3350 last_il_offset = last_native_offset = 0;
3351 for (i = 0; i < seq_points->len; ++i) {
3352 SeqPoint *sp = &seq_points->seq_points [i];
3353 il_offset = sp->il_offset;
3354 native_offset = sp->native_offset;
3355 encode_value (il_offset - last_il_offset, p, &p);
3356 encode_value (native_offset - last_native_offset, p, &p);
3357 last_il_offset = il_offset;
3358 last_native_offset = native_offset;
3360 encode_value (sp->next_len, p, &p);
3361 for (j = 0; j < sp->next_len; ++j)
3362 encode_value (sp->next [j], p, &p);
3367 g_assert (debug_info_size < buf_size);
3369 encode_value (debug_info_size, p, &p);
3370 if (debug_info_size) {
3371 memcpy (p, debug_info, debug_info_size);
3372 p += debug_info_size;
3373 g_free (debug_info);
3376 acfg->stats.ex_info_size += p - buf;
3378 g_assert (p - buf < buf_size);
3380 /* Emit info */
3381 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3382 g_free (buf);
3385 static guint32
3386 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3388 MonoClass *klass = mono_class_get (acfg->image, token);
3389 guint8 *p, *buf;
3390 int i, buf_size, res;
3391 gboolean no_special_static, cant_encode;
3392 gpointer iter = NULL;
3394 buf_size = 10240 + (klass->vtable_size * 16);
3395 p = buf = g_malloc (buf_size);
3397 g_assert (klass);
3399 mono_class_init (klass);
3401 mono_class_get_nested_types (klass, &iter);
3402 g_assert (klass->nested_classes_inited);
3404 mono_class_setup_vtable (klass);
3407 * Emit all the information which is required for creating vtables so
3408 * the runtime does not need to create the MonoMethod structures which
3409 * take up a lot of space.
3412 no_special_static = !mono_class_has_special_static_fields (klass);
3414 /* Check whenever we have enough info to encode the vtable */
3415 cant_encode = FALSE;
3416 for (i = 0; i < klass->vtable_size; ++i) {
3417 MonoMethod *cm = klass->vtable [i];
3419 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3420 cant_encode = TRUE;
3423 if (klass->generic_container || cant_encode) {
3424 encode_value (-1, p, &p);
3425 } else {
3426 encode_value (klass->vtable_size, p, &p);
3427 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);
3428 if (klass->has_cctor)
3429 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3430 if (klass->has_finalize)
3431 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3433 encode_value (klass->instance_size, p, &p);
3434 encode_value (mono_class_data_size (klass), p, &p);
3435 encode_value (klass->packing_size, p, &p);
3436 encode_value (klass->min_align, p, &p);
3438 for (i = 0; i < klass->vtable_size; ++i) {
3439 MonoMethod *cm = klass->vtable [i];
3441 if (cm)
3442 encode_method_ref (acfg, cm, p, &p);
3443 else
3444 encode_value (0, p, &p);
3448 acfg->stats.class_info_size += p - buf;
3450 g_assert (p - buf < buf_size);
3451 res = add_to_blob (acfg, buf, p - buf);
3452 g_free (buf);
3454 return res;
3458 * Calls made from AOTed code are routed through a table of jumps similar to the
3459 * ELF PLT (Program Linkage Table). The differences are the following:
3460 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3461 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3462 * jumps. This means the jumps need to be patched when the address of the callee is
3463 * known. Initially the PLT entries jump to code which transfers control to the
3464 * AOT runtime through the first PLT entry.
3466 static void
3467 emit_plt (MonoAotCompile *acfg)
3469 char symbol [128];
3470 int i;
3471 GHashTable *cache;
3473 cache = g_hash_table_new (g_str_hash, g_str_equal);
3475 emit_line (acfg);
3476 sprintf (symbol, "plt");
3478 emit_section_change (acfg, ".text", 0);
3479 emit_global (acfg, symbol, TRUE);
3480 #ifdef TARGET_X86
3481 /* This section will be made read-write by the AOT loader */
3482 emit_alignment (acfg, mono_pagesize ());
3483 #else
3484 emit_alignment (acfg, 16);
3485 #endif
3486 emit_label (acfg, symbol);
3487 emit_label (acfg, acfg->plt_symbol);
3489 for (i = 0; i < acfg->plt_offset; ++i) {
3490 char label [128];
3491 char *debug_sym = NULL;
3492 MonoJumpInfo *ji;
3494 sprintf (label, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, i);
3496 if (acfg->llvm) {
3498 * If the target is directly callable, alias the plt symbol to point to
3499 * the method code.
3500 * FIXME: Use this to simplify emit_and_reloc_code ().
3501 * FIXME: Avoid the got slot.
3502 * FIXME: Add support to the binary writer.
3504 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3505 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3506 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3507 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3508 continue;
3512 emit_label (acfg, label);
3514 if (acfg->aot_opts.write_symbols) {
3515 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3517 if (ji) {
3518 switch (ji->type) {
3519 case MONO_PATCH_INFO_METHOD:
3520 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3521 break;
3522 case MONO_PATCH_INFO_INTERNAL_METHOD:
3523 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3524 break;
3525 case MONO_PATCH_INFO_CLASS_INIT:
3526 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3527 sanitize_symbol (debug_sym);
3528 break;
3529 case MONO_PATCH_INFO_RGCTX_FETCH:
3530 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3531 break;
3532 case MONO_PATCH_INFO_ICALL_ADDR: {
3533 char *s = get_debug_sym (ji->data.method, "", cache);
3535 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3536 g_free (s);
3537 break;
3539 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3540 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3541 break;
3542 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3543 debug_sym = g_strdup_printf ("plt__generic_class_init");
3544 break;
3545 default:
3546 break;
3549 if (debug_sym) {
3550 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3551 emit_label (acfg, debug_sym);
3557 * The first plt entry is used to transfer code to the AOT loader.
3559 arch_emit_plt_entry (acfg, i);
3561 if (debug_sym) {
3562 emit_symbol_size (acfg, debug_sym, ".");
3563 g_free (debug_sym);
3567 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3569 sprintf (symbol, "plt_end");
3570 emit_global (acfg, symbol, TRUE);
3571 emit_label (acfg, symbol);
3573 g_hash_table_destroy (cache);
3576 static G_GNUC_UNUSED void
3577 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3578 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3580 char start_symbol [256];
3581 char symbol [256];
3582 guint32 buf_size, info_offset;
3583 MonoJumpInfo *patch_info;
3584 guint8 *buf, *p;
3585 GPtrArray *patches;
3587 /* Emit code */
3589 sprintf (start_symbol, "%s", name);
3591 emit_section_change (acfg, ".text", 0);
3592 emit_global (acfg, start_symbol, TRUE);
3593 emit_alignment (acfg, 16);
3594 emit_label (acfg, start_symbol);
3596 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3597 emit_label (acfg, symbol);
3600 * The code should access everything through the GOT, so we pass
3601 * TRUE here.
3603 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3605 emit_symbol_size (acfg, start_symbol, ".");
3607 /* Emit info */
3609 /* Sort relocations */
3610 patches = g_ptr_array_new ();
3611 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3612 if (patch_info->type != MONO_PATCH_INFO_NONE)
3613 g_ptr_array_add (patches, patch_info);
3614 g_ptr_array_sort (patches, compare_patches);
3616 buf_size = patches->len * 128 + 128;
3617 buf = g_malloc (buf_size);
3618 p = buf;
3620 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3621 g_assert (p - buf < buf_size);
3623 sprintf (symbol, "%s_p", name);
3625 info_offset = add_to_blob (acfg, buf, p - buf);
3627 emit_section_change (acfg, ".text", 0);
3628 emit_global (acfg, symbol, FALSE);
3629 emit_label (acfg, symbol);
3631 emit_int32 (acfg, info_offset);
3633 /* Emit debug info */
3634 if (unwind_ops) {
3635 char symbol2 [256];
3637 sprintf (symbol, "%s", name);
3638 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3640 if (acfg->dwarf)
3641 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3645 static void
3646 emit_trampolines (MonoAotCompile *acfg)
3648 char symbol [256];
3649 int i, tramp_got_offset;
3650 MonoAotTrampoline ntype;
3651 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3652 int tramp_type;
3653 guint32 code_size;
3654 MonoJumpInfo *ji;
3655 guint8 *code;
3656 GSList *unwind_ops;
3657 #endif
3659 if (!acfg->aot_opts.full_aot)
3660 return;
3662 g_assert (acfg->image->assembly);
3664 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3665 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3666 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3668 * Emit the generic trampolines.
3670 * We could save some code by treating the generic trampolines as a wrapper
3671 * method, but that approach has its own complexities, so we choose the simpler
3672 * method.
3674 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3675 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3677 /* Emit trampoline code */
3679 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3681 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3684 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3685 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3686 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3687 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3688 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3689 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3690 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3691 #endif
3693 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3694 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3696 /* Emit the exception related code pieces */
3697 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3698 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3699 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3700 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3701 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3702 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3703 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3704 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3705 #ifdef MONO_ARCH_HAVE_THROW_EXCEPTION_BY_NAME
3706 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3707 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3708 #endif
3709 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3710 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3712 #if defined(TARGET_AMD64)
3713 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3714 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3715 #endif
3717 for (i = 0; i < 128; ++i) {
3718 int offset;
3720 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3721 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3722 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3723 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3725 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3726 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3727 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3728 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3732 GSList *l;
3734 /* delegate_invoke_impl trampolines */
3735 l = mono_arch_get_delegate_invoke_impls ();
3736 while (l) {
3737 MonoAotTrampInfo *info = l->data;
3739 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3740 l = l->next;
3744 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3746 /* Emit trampolines which are numerous */
3749 * These include the following:
3750 * - specific trampolines
3751 * - static rgctx invoke trampolines
3752 * - imt thunks
3753 * These trampolines have the same code, they are parameterized by GOT
3754 * slots.
3755 * They are defined in this file, in the arch_... routines instead of
3756 * in tramp-<ARCH>.c, since it is easier to do it this way.
3760 * When running in aot-only mode, we can't create specific trampolines at
3761 * runtime, so we create a few, and save them in the AOT file.
3762 * Normal trampolines embed their argument as a literal inside the
3763 * trampoline code, we can't do that here, so instead we embed an offset
3764 * which needs to be added to the trampoline address to get the address of
3765 * the GOT slot which contains the argument value.
3766 * The generated trampolines jump to the generic trampolines using another
3767 * GOT slot, which will be setup by the AOT loader to point to the
3768 * generic trampoline code of the given type.
3772 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3773 * each class).
3776 emit_section_change (acfg, ".text", 0);
3778 tramp_got_offset = acfg->got_offset;
3780 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3781 switch (ntype) {
3782 case MONO_AOT_TRAMP_SPECIFIC:
3783 sprintf (symbol, "specific_trampolines");
3784 break;
3785 case MONO_AOT_TRAMP_STATIC_RGCTX:
3786 sprintf (symbol, "static_rgctx_trampolines");
3787 break;
3788 case MONO_AOT_TRAMP_IMT_THUNK:
3789 sprintf (symbol, "imt_thunks");
3790 break;
3791 default:
3792 g_assert_not_reached ();
3795 emit_global (acfg, symbol, TRUE);
3796 emit_alignment (acfg, 16);
3797 emit_label (acfg, symbol);
3799 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3801 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3802 int tramp_size = 0;
3804 switch (ntype) {
3805 case MONO_AOT_TRAMP_SPECIFIC:
3806 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3807 tramp_got_offset += 2;
3808 break;
3809 case MONO_AOT_TRAMP_STATIC_RGCTX:
3810 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3811 tramp_got_offset += 2;
3812 break;
3813 case MONO_AOT_TRAMP_IMT_THUNK:
3814 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3815 tramp_got_offset += 1;
3816 break;
3817 default:
3818 g_assert_not_reached ();
3821 if (!acfg->trampoline_size [ntype]) {
3822 g_assert (tramp_size);
3823 acfg->trampoline_size [ntype] = tramp_size;
3828 /* Reserve some entries at the end of the GOT for our use */
3829 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3832 acfg->got_offset += acfg->num_trampoline_got_entries;
3835 static gboolean
3836 str_begins_with (const char *str1, const char *str2)
3838 int len = strlen (str2);
3839 return strncmp (str1, str2, len) == 0;
3842 static void
3843 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3845 gchar **args, **ptr;
3847 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3848 for (ptr = args; ptr && *ptr; ptr ++) {
3849 const char *arg = *ptr;
3851 if (str_begins_with (arg, "outfile=")) {
3852 opts->outfile = g_strdup (arg + strlen ("outfile="));
3853 } else if (str_begins_with (arg, "save-temps")) {
3854 opts->save_temps = TRUE;
3855 } else if (str_begins_with (arg, "keep-temps")) {
3856 opts->save_temps = TRUE;
3857 } else if (str_begins_with (arg, "write-symbols")) {
3858 opts->write_symbols = TRUE;
3859 } else if (str_begins_with (arg, "metadata-only")) {
3860 opts->metadata_only = TRUE;
3861 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3862 opts->bind_to_runtime_version = TRUE;
3863 } else if (str_begins_with (arg, "full")) {
3864 opts->full_aot = TRUE;
3865 } else if (str_begins_with (arg, "threads=")) {
3866 opts->nthreads = atoi (arg + strlen ("threads="));
3867 } else if (str_begins_with (arg, "static")) {
3868 opts->static_link = TRUE;
3869 opts->no_dlsym = TRUE;
3870 } else if (str_begins_with (arg, "asmonly")) {
3871 opts->asm_only = TRUE;
3872 } else if (str_begins_with (arg, "asmwriter")) {
3873 opts->asm_writer = TRUE;
3874 } else if (str_begins_with (arg, "nodebug")) {
3875 opts->nodebug = TRUE;
3876 } else if (str_begins_with (arg, "ntrampolines=")) {
3877 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3878 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
3879 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
3880 } else if (str_begins_with (arg, "nimt-trampolines=")) {
3881 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
3882 } else if (str_begins_with (arg, "autoreg")) {
3883 opts->autoreg = TRUE;
3884 } else if (str_begins_with (arg, "tool-prefix=")) {
3885 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3886 } else if (str_begins_with (arg, "soft-debug")) {
3887 opts->soft_debug = TRUE;
3888 } else if (str_begins_with (arg, "print-skipped")) {
3889 opts->print_skipped_methods = TRUE;
3890 } else if (str_begins_with (arg, "stats")) {
3891 opts->stats = TRUE;
3892 } else {
3893 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3894 exit (1);
3898 g_strfreev (args);
3901 static void
3902 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3904 MonoMethod *method = (MonoMethod*)key;
3905 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3906 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3907 MonoAotCompile *acfg = user_data;
3909 new_ji->image = ji->image;
3910 new_ji->token = ji->token;
3911 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3914 static gboolean
3915 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3917 if (klass->type_token)
3918 return TRUE;
3919 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3920 return TRUE;
3921 if (klass->rank)
3922 return can_encode_class (acfg, klass->element_class);
3923 return FALSE;
3926 static gboolean
3927 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3929 switch (patch_info->type) {
3930 case MONO_PATCH_INFO_METHOD:
3931 case MONO_PATCH_INFO_METHODCONST: {
3932 MonoMethod *method = patch_info->data.method;
3934 if (method->wrapper_type) {
3935 switch (method->wrapper_type) {
3936 case MONO_WRAPPER_NONE:
3937 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3938 case MONO_WRAPPER_XDOMAIN_INVOKE:
3939 case MONO_WRAPPER_STFLD:
3940 case MONO_WRAPPER_LDFLD:
3941 case MONO_WRAPPER_LDFLDA:
3942 case MONO_WRAPPER_LDFLD_REMOTE:
3943 case MONO_WRAPPER_STFLD_REMOTE:
3944 case MONO_WRAPPER_STELEMREF:
3945 case MONO_WRAPPER_ISINST:
3946 case MONO_WRAPPER_PROXY_ISINST:
3947 case MONO_WRAPPER_ALLOC:
3948 case MONO_WRAPPER_REMOTING_INVOKE:
3949 case MONO_WRAPPER_UNKNOWN:
3950 case MONO_WRAPPER_WRITE_BARRIER:
3951 break;
3952 case MONO_WRAPPER_MANAGED_TO_MANAGED:
3953 if (!strcmp (method->name, "ElementAddr"))
3954 return TRUE;
3955 else
3956 return FALSE;
3957 default:
3958 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3959 return FALSE;
3961 } else {
3962 if (!method->token) {
3963 /* The method is part of a constructed type like Int[,].Set (). */
3964 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3965 if (method->klass->rank)
3966 return TRUE;
3967 return FALSE;
3971 break;
3973 case MONO_PATCH_INFO_VTABLE:
3974 case MONO_PATCH_INFO_CLASS_INIT:
3975 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3976 case MONO_PATCH_INFO_CLASS:
3977 case MONO_PATCH_INFO_IID:
3978 case MONO_PATCH_INFO_ADJUSTED_IID:
3979 if (!can_encode_class (acfg, patch_info->data.klass)) {
3980 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3981 return FALSE;
3983 break;
3984 case MONO_PATCH_INFO_RGCTX_FETCH: {
3985 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3987 if (!can_encode_patch (acfg, entry->data))
3988 return FALSE;
3989 break;
3991 default:
3992 break;
3995 return TRUE;
3998 static void
3999 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4002 * compile_method:
4004 * AOT compile a given method.
4005 * This function might be called by multiple threads, so it must be thread-safe.
4007 static void
4008 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4010 MonoCompile *cfg;
4011 MonoJumpInfo *patch_info;
4012 gboolean skip;
4013 int index, depth;
4014 MonoMethod *wrapped;
4016 if (acfg->aot_opts.metadata_only)
4017 return;
4019 mono_acfg_lock (acfg);
4020 index = get_method_index (acfg, method);
4021 mono_acfg_unlock (acfg);
4023 /* fixme: maybe we can also precompile wrapper methods */
4024 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4025 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4026 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4027 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4028 return;
4031 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4032 return;
4034 wrapped = mono_marshal_method_from_wrapper (method);
4035 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4036 // FIXME: The wrapper should be generic too, but it is not
4037 return;
4039 InterlockedIncrement (&acfg->stats.mcount);
4041 #if 0
4042 if (method->is_generic || method->klass->generic_container) {
4043 InterlockedIncrement (&acfg->stats.genericcount);
4044 return;
4046 #endif
4048 //acfg->aot_opts.print_skipped_methods = TRUE;
4051 * Since these methods are the only ones which are compiled with
4052 * AOT support, and they are not used by runtime startup/shutdown code,
4053 * the runtime will not see AOT methods during AOT compilation,so it
4054 * does not need to support them by creating a fake GOT etc.
4056 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4057 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4058 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4059 InterlockedIncrement (&acfg->stats.genericcount);
4060 return;
4062 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4063 /* Let the exception happen at runtime */
4064 return;
4067 if (cfg->disable_aot) {
4068 if (acfg->aot_opts.print_skipped_methods)
4069 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4070 InterlockedIncrement (&acfg->stats.ocount);
4071 mono_destroy_compile (cfg);
4072 return;
4075 /* Nullify patches which need no aot processing */
4076 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4077 switch (patch_info->type) {
4078 case MONO_PATCH_INFO_LABEL:
4079 case MONO_PATCH_INFO_BB:
4080 patch_info->type = MONO_PATCH_INFO_NONE;
4081 break;
4082 default:
4083 break;
4087 /* Collect method->token associations from the cfg */
4088 mono_acfg_lock (acfg);
4089 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4090 mono_acfg_unlock (acfg);
4093 * Check for absolute addresses.
4095 skip = FALSE;
4096 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4097 switch (patch_info->type) {
4098 case MONO_PATCH_INFO_ABS:
4099 /* unable to handle this */
4100 skip = TRUE;
4101 break;
4102 default:
4103 break;
4107 if (skip) {
4108 if (acfg->aot_opts.print_skipped_methods)
4109 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4110 InterlockedIncrement (&acfg->stats.abscount);
4111 mono_destroy_compile (cfg);
4112 return;
4115 /* Lock for the rest of the code */
4116 mono_acfg_lock (acfg);
4119 * Check for methods/klasses we can't encode.
4121 skip = FALSE;
4122 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4123 if (!can_encode_patch (acfg, patch_info))
4124 skip = TRUE;
4127 if (skip) {
4128 if (acfg->aot_opts.print_skipped_methods)
4129 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4130 acfg->stats.ocount++;
4131 mono_destroy_compile (cfg);
4132 mono_acfg_unlock (acfg);
4133 return;
4136 /* Adds generic instances referenced by this method */
4138 * The depth is used to avoid infinite loops when generic virtual recursion is
4139 * encountered.
4141 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4142 if (depth < 32) {
4143 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4144 switch (patch_info->type) {
4145 case MONO_PATCH_INFO_METHOD: {
4146 MonoMethod *m = patch_info->data.method;
4147 if (m->is_inflated) {
4148 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4149 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4150 !method_has_type_vars (m)) {
4151 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4152 if (acfg->aot_opts.full_aot)
4153 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4154 } else {
4155 add_extra_method_with_depth (acfg, m, depth + 1);
4158 add_generic_class (acfg, m->klass);
4160 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4161 add_extra_method_with_depth (acfg, m, depth + 1);
4162 break;
4164 case MONO_PATCH_INFO_VTABLE: {
4165 MonoClass *klass = patch_info->data.klass;
4167 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4168 add_generic_class (acfg, klass);
4169 break;
4171 default:
4172 break;
4177 /* Determine whenever the method has GOT slots */
4178 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4179 switch (patch_info->type) {
4180 case MONO_PATCH_INFO_GOT_OFFSET:
4181 case MONO_PATCH_INFO_NONE:
4182 break;
4183 case MONO_PATCH_INFO_IMAGE:
4184 /* The assembly is stored in GOT slot 0 */
4185 if (patch_info->data.image != acfg->image)
4186 cfg->has_got_slots = TRUE;
4187 break;
4188 default:
4189 if (!is_plt_patch (patch_info))
4190 cfg->has_got_slots = TRUE;
4191 break;
4195 if (!cfg->has_got_slots)
4196 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4199 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4201 /* Make a copy of the patch info which is in the mempool */
4203 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4205 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4206 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4208 if (!patches)
4209 patches = new_patch_info;
4210 else
4211 patches_end->next = new_patch_info;
4212 patches_end = new_patch_info;
4214 cfg->patch_info = patches;
4216 /* Make a copy of the unwind info */
4218 GSList *l, *unwind_ops;
4219 MonoUnwindOp *op;
4221 unwind_ops = NULL;
4222 for (l = cfg->unwind_ops; l; l = l->next) {
4223 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4224 memcpy (op, l->data, sizeof (MonoUnwindOp));
4225 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4227 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4229 /* Make a copy of the argument/local info */
4231 MonoInst **args, **locals;
4232 MonoMethodSignature *sig;
4233 MonoMethodHeader *header;
4234 int i;
4236 sig = mono_method_signature (method);
4237 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4238 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4239 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4240 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4242 cfg->args = args;
4244 header = mono_method_get_header (method);
4245 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4246 for (i = 0; i < header->num_locals; ++i) {
4247 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4248 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4250 cfg->locals = locals;
4253 /* Free some fields used by cfg to conserve memory */
4254 mono_mempool_destroy (cfg->mempool);
4255 cfg->mempool = NULL;
4256 g_free (cfg->varinfo);
4257 cfg->varinfo = NULL;
4258 g_free (cfg->vars);
4259 cfg->vars = NULL;
4260 if (cfg->rs) {
4261 mono_regstate_free (cfg->rs);
4262 cfg->rs = NULL;
4265 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4267 while (index >= acfg->cfgs_size) {
4268 MonoCompile **new_cfgs;
4269 int new_size;
4271 new_size = acfg->cfgs_size * 2;
4272 new_cfgs = g_new0 (MonoCompile*, new_size);
4273 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4274 g_free (acfg->cfgs);
4275 acfg->cfgs = new_cfgs;
4276 acfg->cfgs_size = new_size;
4278 acfg->cfgs [index] = cfg;
4280 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4283 if (cfg->orig_method->wrapper_type)
4284 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4287 mono_acfg_unlock (acfg);
4289 InterlockedIncrement (&acfg->stats.ccount);
4292 static void
4293 compile_thread_main (gpointer *user_data)
4295 MonoDomain *domain = user_data [0];
4296 MonoAotCompile *acfg = user_data [1];
4297 GPtrArray *methods = user_data [2];
4298 int i;
4300 mono_thread_attach (domain);
4302 for (i = 0; i < methods->len; ++i)
4303 compile_method (acfg, g_ptr_array_index (methods, i));
4306 static void
4307 load_profile_files (MonoAotCompile *acfg)
4309 FILE *infile;
4310 char *tmp;
4311 int file_index, res, method_index, i;
4312 char ver [256];
4313 guint32 token;
4314 GList *unordered;
4316 file_index = 0;
4317 while (TRUE) {
4318 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4320 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4321 g_free (tmp);
4322 break;
4325 infile = fopen (tmp, "r");
4326 g_assert (infile);
4328 printf ("Using profile data file '%s'\n", tmp);
4329 g_free (tmp);
4331 file_index ++;
4333 res = fscanf (infile, "%32s\n", ver);
4334 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4335 printf ("Profile file has wrong version or invalid.\n");
4336 fclose (infile);
4337 continue;
4340 while (TRUE) {
4341 char name [1024];
4342 MonoMethodDesc *desc;
4343 MonoMethod *method;
4345 if (fgets (name, 1023, infile) == NULL)
4346 break;
4348 /* Kill the newline */
4349 if (strlen (name) > 0)
4350 name [strlen (name) - 1] = '\0';
4352 desc = mono_method_desc_new (name, TRUE);
4354 method = mono_method_desc_search_in_image (desc, acfg->image);
4356 if (method && mono_method_get_token (method)) {
4357 token = mono_method_get_token (method);
4358 method_index = mono_metadata_token_index (token) - 1;
4360 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4361 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4363 } else {
4364 //printf ("No method found matching '%s'.\n", name);
4367 fclose (infile);
4370 /* Add missing methods */
4371 unordered = NULL;
4372 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4373 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4374 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4376 unordered = g_list_reverse (unordered);
4377 if (acfg->method_order)
4378 g_list_last (acfg->method_order)->next = unordered;
4379 else
4380 acfg->method_order = unordered;
4383 /* Used by the LLVM backend */
4384 guint32
4385 mono_aot_get_got_offset (MonoJumpInfo *ji)
4387 return get_got_offset (llvm_acfg, ji);
4390 char*
4391 mono_aot_get_method_name (MonoCompile *cfg)
4393 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4395 return g_strdup_printf ("m_%x", method_index);
4398 char*
4399 mono_aot_get_method_debug_name (MonoCompile *cfg)
4401 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4404 char*
4405 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4407 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4408 int offset;
4410 ji->type = type;
4411 ji->data.target = data;
4413 if (!can_encode_patch (llvm_acfg, ji))
4414 return NULL;
4416 offset = get_plt_offset (llvm_acfg, ji);
4418 return g_strdup_printf ("%sp_%d", llvm_acfg->temp_prefix, offset);
4421 MonoJumpInfo*
4422 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4424 MonoJumpInfo *res;
4426 mono_acfg_lock (llvm_acfg);
4427 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4428 mono_acfg_unlock (llvm_acfg);
4430 return res;
4433 #ifdef ENABLE_LLVM
4436 * emit_llvm_file:
4438 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4439 * tools.
4441 static void
4442 emit_llvm_file (MonoAotCompile *acfg)
4444 char *command, *opts;
4445 int i;
4446 MonoJumpInfo *patch_info;
4447 char *llc_target_args;
4450 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4451 * to it.
4454 /* Compute the final size of the got */
4455 for (i = 0; i < acfg->nmethods; ++i) {
4456 if (acfg->cfgs [i]) {
4457 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4458 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4459 if (!is_plt_patch (patch_info))
4460 get_got_offset (acfg, patch_info);
4461 else
4462 get_plt_offset (acfg, patch_info);
4468 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4470 if (acfg->aot_opts.full_aot) {
4471 int ntype;
4474 * Need to add the got entries used by the trampolines.
4475 * This is only a conservative approximation.
4477 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4478 /* For the generic + rgctx trampolines */
4479 acfg->final_got_size += 200;
4480 /* For the specific trampolines */
4481 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4482 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4487 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4490 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4491 * a lot of time, and doesn't seem to save much space.
4492 * The following optimizations cannot be enabled:
4493 * - 'tailcallelim'
4494 * The opt list below was produced by taking the output of:
4495 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4496 * then removing tailcallelim + the global opts, and adding a second gvn.
4498 opts = g_strdup ("-instcombine -simplifycfg");
4499 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -jump-threading -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -jump-threading -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
4500 #if 1
4501 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4502 printf ("Executing opt: %s\n", command);
4503 if (system (command) != 0) {
4504 exit (1);
4506 #endif
4507 g_free (opts);
4509 llc_target_args = g_strdup (LLC_TARGET_ARGS);
4511 command = g_strdup_printf ("llc %s -f -relocation-model=pic -unwind-tables -o %s temp.opt.bc", llc_target_args, acfg->tmpfname);
4512 g_free (llc_target_args);
4514 printf ("Executing llc: %s\n", command);
4516 if (system (command) != 0) {
4517 exit (1);
4520 #endif
4522 static void
4523 emit_code (MonoAotCompile *acfg)
4525 int i;
4526 char symbol [256];
4527 char end_symbol [256];
4528 GList *l;
4530 #if defined(TARGET_POWERPC64)
4531 sprintf (symbol, ".Lgot_addr");
4532 emit_section_change (acfg, ".text", 0);
4533 emit_alignment (acfg, 8);
4534 emit_label (acfg, symbol);
4535 emit_pointer (acfg, acfg->got_symbol);
4536 #endif
4539 * This global symbol is used to compute the address of each method using the
4540 * code_offsets array. It is also used to compute the memory ranges occupied by
4541 * AOT code, so it must be equal to the address of the first emitted method.
4543 sprintf (symbol, "methods");
4544 emit_section_change (acfg, ".text", 0);
4545 emit_global (acfg, symbol, TRUE);
4546 emit_alignment (acfg, 8);
4547 if (acfg->llvm) {
4548 for (i = 0; i < acfg->nmethods; ++i) {
4549 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4550 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4551 break;
4554 if (i == acfg->nmethods)
4555 /* No LLVM compiled methods */
4556 emit_label (acfg, symbol);
4557 } else {
4558 emit_label (acfg, symbol);
4562 * Emit some padding so the local symbol for the first method doesn't have the
4563 * same address as 'methods'.
4565 emit_zero_bytes (acfg, 16);
4567 for (l = acfg->method_order; l != NULL; l = l->next) {
4568 MonoCompile *cfg;
4569 MonoMethod *method;
4571 i = GPOINTER_TO_UINT (l->data);
4573 cfg = acfg->cfgs [i];
4575 if (!cfg)
4576 continue;
4578 method = cfg->orig_method;
4580 /* Emit unbox trampoline */
4581 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4582 char call_target [256];
4584 if (!method->wrapper_type && !method->is_inflated) {
4585 g_assert (method->token);
4586 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4587 } else {
4588 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4591 emit_section_change (acfg, ".text", 0);
4592 emit_global (acfg, symbol, TRUE);
4593 emit_label (acfg, symbol);
4595 sprintf (call_target, "%s", cfg->asm_symbol);
4597 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4600 if (cfg->compile_llvm)
4601 acfg->stats.llvm_count ++;
4602 else
4603 emit_method_code (acfg, cfg);
4606 sprintf (symbol, "methods_end");
4607 emit_section_change (acfg, ".text", 0);
4608 emit_global (acfg, symbol, FALSE);
4609 emit_alignment (acfg, 8);
4610 emit_label (acfg, symbol);
4612 sprintf (symbol, "code_offsets");
4613 emit_section_change (acfg, ".text", 1);
4614 emit_global (acfg, symbol, FALSE);
4615 emit_alignment (acfg, 8);
4616 emit_label (acfg, symbol);
4618 acfg->stats.offsets_size += acfg->nmethods * 4;
4620 sprintf (end_symbol, "methods");
4621 for (i = 0; i < acfg->nmethods; ++i) {
4622 if (acfg->cfgs [i]) {
4623 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4624 } else {
4625 emit_int32 (acfg, 0xffffffff);
4628 emit_line (acfg);
4631 static void
4632 emit_info (MonoAotCompile *acfg)
4634 int i;
4635 char symbol [256];
4636 GList *l;
4637 gint32 *offsets;
4639 offsets = g_new0 (gint32, acfg->nmethods);
4641 for (l = acfg->method_order; l != NULL; l = l->next) {
4642 i = GPOINTER_TO_UINT (l->data);
4644 if (acfg->cfgs [i]) {
4645 emit_method_info (acfg, acfg->cfgs [i]);
4646 offsets [i] = acfg->cfgs [i]->method_info_offset;
4647 } else {
4648 offsets [i] = 0;
4652 sprintf (symbol, "method_info_offsets");
4653 emit_section_change (acfg, ".text", 1);
4654 emit_global (acfg, symbol, FALSE);
4655 emit_alignment (acfg, 8);
4656 emit_label (acfg, symbol);
4658 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4660 g_free (offsets);
4663 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4665 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4666 #define mix(a,b,c) { \
4667 a -= c; a ^= rot(c, 4); c += b; \
4668 b -= a; b ^= rot(a, 6); a += c; \
4669 c -= b; c ^= rot(b, 8); b += a; \
4670 a -= c; a ^= rot(c,16); c += b; \
4671 b -= a; b ^= rot(a,19); a += c; \
4672 c -= b; c ^= rot(b, 4); b += a; \
4674 #define final(a,b,c) { \
4675 c ^= b; c -= rot(b,14); \
4676 a ^= c; a -= rot(c,11); \
4677 b ^= a; b -= rot(a,25); \
4678 c ^= b; c -= rot(b,16); \
4679 a ^= c; a -= rot(c,4); \
4680 b ^= a; b -= rot(a,14); \
4681 c ^= b; c -= rot(b,24); \
4684 static guint
4685 mono_aot_type_hash (MonoType *t1)
4687 guint hash = t1->type;
4689 hash |= t1->byref << 6; /* do not collide with t1->type values */
4690 switch (t1->type) {
4691 case MONO_TYPE_VALUETYPE:
4692 case MONO_TYPE_CLASS:
4693 case MONO_TYPE_SZARRAY:
4694 /* check if the distribution is good enough */
4695 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4696 case MONO_TYPE_PTR:
4697 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4698 case MONO_TYPE_ARRAY:
4699 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4700 case MONO_TYPE_GENERICINST:
4701 return ((hash << 5) - hash) ^ 0;
4703 return hash;
4707 * mono_aot_method_hash:
4709 * Return a hash code for methods which only depends on metadata.
4711 guint32
4712 mono_aot_method_hash (MonoMethod *method)
4714 MonoMethodSignature *sig;
4715 MonoClass *klass;
4716 int i;
4717 int hashes_count;
4718 guint32 *hashes_start, *hashes;
4719 guint32 a, b, c;
4721 /* Similar to the hash in mono_method_get_imt_slot () */
4723 sig = mono_method_signature (method);
4725 hashes_count = sig->param_count + 5;
4726 hashes_start = malloc (hashes_count * sizeof (guint32));
4727 hashes = hashes_start;
4729 /* Some wrappers are assigned to random classes */
4730 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4731 klass = method->klass;
4732 else
4733 klass = mono_defaults.object_class;
4735 if (!method->wrapper_type) {
4736 char *full_name = mono_type_full_name (&klass->byval_arg);
4738 hashes [0] = mono_metadata_str_hash (full_name);
4739 hashes [1] = 0;
4740 g_free (full_name);
4741 } else {
4742 hashes [0] = mono_metadata_str_hash (klass->name);
4743 hashes [1] = mono_metadata_str_hash (klass->name_space);
4745 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4746 /* The method name includes a stringified pointer */
4747 hashes [2] = 0;
4748 else
4749 hashes [2] = mono_metadata_str_hash (method->name);
4750 hashes [3] = method->wrapper_type;
4751 hashes [4] = mono_aot_type_hash (sig->ret);
4752 for (i = 0; i < sig->param_count; i++) {
4753 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4756 /* Setup internal state */
4757 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4759 /* Handle most of the hashes */
4760 while (hashes_count > 3) {
4761 a += hashes [0];
4762 b += hashes [1];
4763 c += hashes [2];
4764 mix (a,b,c);
4765 hashes_count -= 3;
4766 hashes += 3;
4769 /* Handle the last 3 hashes (all the case statements fall through) */
4770 switch (hashes_count) {
4771 case 3 : c += hashes [2];
4772 case 2 : b += hashes [1];
4773 case 1 : a += hashes [0];
4774 final (a,b,c);
4775 case 0: /* nothing left to add */
4776 break;
4779 free (hashes_start);
4781 return c;
4783 #undef rot
4784 #undef mix
4785 #undef final
4788 * mono_aot_wrapper_name:
4790 * Return a string which uniqely identifies the given wrapper method.
4792 char*
4793 mono_aot_wrapper_name (MonoMethod *method)
4795 char *name, *tmpsig, *klass_desc;
4797 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4799 switch (method->wrapper_type) {
4800 case MONO_WRAPPER_RUNTIME_INVOKE:
4801 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4802 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4803 else
4804 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4805 break;
4806 default:
4807 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4808 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4809 g_free (klass_desc);
4810 break;
4813 g_free (tmpsig);
4815 return name;
4819 * mono_aot_get_array_helper_from_wrapper;
4821 * Get the helper method in Array called by an array wrapper method.
4823 MonoMethod*
4824 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4826 MonoMethod *m;
4827 const char *prefix;
4828 MonoGenericContext ctx;
4829 MonoType *args [16];
4830 char *mname, *iname, *s, *s2, *helper_name = NULL;
4832 prefix = "System.Collections.Generic";
4833 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4834 s2 = strstr (s, "`1.");
4835 g_assert (s2);
4836 s2 [0] = '\0';
4837 iname = s;
4838 mname = s2 + 3;
4840 //printf ("X: %s %s\n", iname, mname);
4842 if (!strcmp (iname, "IList"))
4843 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4844 else
4845 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4846 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4847 g_assert (m);
4848 g_free (helper_name);
4849 g_free (s);
4851 if (m->is_generic) {
4852 memset (&ctx, 0, sizeof (ctx));
4853 args [0] = &method->klass->element_class->byval_arg;
4854 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4855 m = mono_class_inflate_generic_method (m, &ctx);
4858 return m;
4862 * mono_aot_tramp_info_create:
4864 * Create a MonoAotTrampInfo structure from the arguments.
4866 MonoAotTrampInfo*
4867 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4869 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4871 info->name = (char*)name;
4872 info->code = code;
4873 info->code_size = code_size;
4875 return info;
4878 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4880 typedef struct HashEntry {
4881 guint32 key, value, index;
4882 struct HashEntry *next;
4883 } HashEntry;
4886 * emit_extra_methods:
4888 * Emit methods which are not in the METHOD table, like wrappers.
4890 static void
4891 emit_extra_methods (MonoAotCompile *acfg)
4893 int i, table_size, buf_size;
4894 char symbol [256];
4895 guint8 *p, *buf;
4896 guint32 *info_offsets;
4897 guint32 hash;
4898 GPtrArray *table;
4899 HashEntry *entry, *new_entry;
4900 int nmethods, max_chain_length;
4901 int *chain_lengths;
4903 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4905 /* Emit method info */
4906 nmethods = 0;
4907 for (i = 0; i < acfg->extra_methods->len; ++i) {
4908 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4909 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4910 char *name;
4912 if (!cfg)
4913 continue;
4915 buf_size = 512;
4916 p = buf = g_malloc (buf_size);
4918 nmethods ++;
4920 method = cfg->method_to_register;
4922 name = NULL;
4923 if (method->wrapper_type) {
4925 * We encode some wrappers using their name, since encoding them
4926 * directly would be difficult. This also avoids creating the wrapper
4927 * methods at runtime, since they are not needed anyway.
4929 switch (method->wrapper_type) {
4930 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4931 case MONO_WRAPPER_SYNCHRONIZED:
4932 /* encode_method_ref () can handle these */
4933 break;
4934 case MONO_WRAPPER_RUNTIME_INVOKE:
4935 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4936 /* Direct wrapper, encode normally */
4937 break;
4938 /* Fall through */
4939 default:
4940 name = mono_aot_wrapper_name (method);
4941 break;
4945 if (name) {
4946 encode_value (1, p, &p);
4947 encode_value (method->wrapper_type, p, &p);
4948 strcpy ((char*)p, name);
4949 p += strlen (name ) + 1;
4950 g_free (name);
4951 } else {
4952 encode_value (0, p, &p);
4953 encode_method_ref (acfg, method, p, &p);
4956 g_assert ((p - buf) < buf_size);
4958 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
4959 g_free (buf);
4963 * Construct a chained hash table for mapping indexes in extra_method_info to
4964 * method indexes.
4966 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4967 table = g_ptr_array_sized_new (table_size);
4968 for (i = 0; i < table_size; ++i)
4969 g_ptr_array_add (table, NULL);
4970 chain_lengths = g_new0 (int, table_size);
4971 max_chain_length = 0;
4972 for (i = 0; i < acfg->extra_methods->len; ++i) {
4973 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4974 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4975 guint32 key, value;
4977 if (!cfg)
4978 continue;
4980 key = info_offsets [i];
4981 value = get_method_index (acfg, method);
4983 hash = mono_aot_method_hash (method) % table_size;
4985 chain_lengths [hash] ++;
4986 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4988 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
4989 new_entry->key = key;
4990 new_entry->value = value;
4992 entry = g_ptr_array_index (table, hash);
4993 if (entry == NULL) {
4994 new_entry->index = hash;
4995 g_ptr_array_index (table, hash) = new_entry;
4996 } else {
4997 while (entry->next)
4998 entry = entry->next;
5000 entry->next = new_entry;
5001 new_entry->index = table->len;
5002 g_ptr_array_add (table, new_entry);
5006 //printf ("MAX: %d\n", max_chain_length);
5008 /* Emit the table */
5009 sprintf (symbol, "extra_method_table");
5010 emit_section_change (acfg, ".text", 0);
5011 emit_global (acfg, symbol, FALSE);
5012 emit_alignment (acfg, 8);
5013 emit_label (acfg, symbol);
5015 emit_int32 (acfg, table_size);
5016 for (i = 0; i < table->len; ++i) {
5017 HashEntry *entry = g_ptr_array_index (table, i);
5019 if (entry == NULL) {
5020 emit_int32 (acfg, 0);
5021 emit_int32 (acfg, 0);
5022 emit_int32 (acfg, 0);
5023 } else {
5024 //g_assert (entry->key > 0);
5025 emit_int32 (acfg, entry->key);
5026 emit_int32 (acfg, entry->value);
5027 if (entry->next)
5028 emit_int32 (acfg, entry->next->index);
5029 else
5030 emit_int32 (acfg, 0);
5035 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5036 * This is used by mono_aot_find_jit_info ().
5038 sprintf (symbol, "extra_method_info_offsets");
5039 emit_section_change (acfg, ".text", 0);
5040 emit_global (acfg, symbol, FALSE);
5041 emit_alignment (acfg, 8);
5042 emit_label (acfg, symbol);
5044 emit_int32 (acfg, acfg->extra_methods->len);
5045 for (i = 0; i < acfg->extra_methods->len; ++i) {
5046 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5048 emit_int32 (acfg, get_method_index (acfg, method));
5049 emit_int32 (acfg, info_offsets [i]);
5053 static void
5054 emit_exception_info (MonoAotCompile *acfg)
5056 int i;
5057 char symbol [256];
5058 gint32 *offsets;
5060 offsets = g_new0 (gint32, acfg->nmethods);
5061 for (i = 0; i < acfg->nmethods; ++i) {
5062 if (acfg->cfgs [i]) {
5063 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5064 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5065 } else {
5066 offsets [i] = 0;
5070 sprintf (symbol, "ex_info_offsets");
5071 emit_section_change (acfg, ".text", 1);
5072 emit_global (acfg, symbol, FALSE);
5073 emit_alignment (acfg, 8);
5074 emit_label (acfg, symbol);
5076 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5077 g_free (offsets);
5080 static void
5081 emit_unwind_info (MonoAotCompile *acfg)
5083 int i;
5084 char symbol [128];
5087 * The unwind info contains a lot of duplicates so we emit each unique
5088 * entry once, and only store the offset from the start of the table in the
5089 * exception info.
5092 sprintf (symbol, "unwind_info");
5093 emit_section_change (acfg, ".text", 1);
5094 emit_alignment (acfg, 8);
5095 emit_label (acfg, symbol);
5096 emit_global (acfg, symbol, FALSE);
5098 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5099 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5100 guint8 *unwind_info;
5101 guint32 unwind_info_len;
5102 guint8 buf [16];
5103 guint8 *p;
5105 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5107 p = buf;
5108 encode_value (unwind_info_len, p, &p);
5109 emit_bytes (acfg, buf, p - buf);
5110 emit_bytes (acfg, unwind_info, unwind_info_len);
5112 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5116 static void
5117 emit_class_info (MonoAotCompile *acfg)
5119 int i;
5120 char symbol [256];
5121 gint32 *offsets;
5123 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5124 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5125 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5127 sprintf (symbol, "class_info_offsets");
5128 emit_section_change (acfg, ".text", 1);
5129 emit_global (acfg, symbol, FALSE);
5130 emit_alignment (acfg, 8);
5131 emit_label (acfg, symbol);
5133 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5134 g_free (offsets);
5137 typedef struct ClassNameTableEntry {
5138 guint32 token, index;
5139 struct ClassNameTableEntry *next;
5140 } ClassNameTableEntry;
5142 static void
5143 emit_class_name_table (MonoAotCompile *acfg)
5145 int i, table_size;
5146 guint32 token, hash;
5147 MonoClass *klass;
5148 GPtrArray *table;
5149 char *full_name;
5150 char symbol [256];
5151 ClassNameTableEntry *entry, *new_entry;
5154 * Construct a chained hash table for mapping class names to typedef tokens.
5156 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5157 table = g_ptr_array_sized_new (table_size);
5158 for (i = 0; i < table_size; ++i)
5159 g_ptr_array_add (table, NULL);
5160 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5161 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5162 klass = mono_class_get (acfg->image, token);
5163 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5164 hash = mono_metadata_str_hash (full_name) % table_size;
5165 g_free (full_name);
5167 /* FIXME: Allocate from the mempool */
5168 new_entry = g_new0 (ClassNameTableEntry, 1);
5169 new_entry->token = token;
5171 entry = g_ptr_array_index (table, hash);
5172 if (entry == NULL) {
5173 new_entry->index = hash;
5174 g_ptr_array_index (table, hash) = new_entry;
5175 } else {
5176 while (entry->next)
5177 entry = entry->next;
5179 entry->next = new_entry;
5180 new_entry->index = table->len;
5181 g_ptr_array_add (table, new_entry);
5185 /* Emit the table */
5186 sprintf (symbol, "class_name_table");
5187 emit_section_change (acfg, ".text", 0);
5188 emit_global (acfg, symbol, FALSE);
5189 emit_alignment (acfg, 8);
5190 emit_label (acfg, symbol);
5192 /* FIXME: Optimize memory usage */
5193 g_assert (table_size < 65000);
5194 emit_int16 (acfg, table_size);
5195 g_assert (table->len < 65000);
5196 for (i = 0; i < table->len; ++i) {
5197 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5199 if (entry == NULL) {
5200 emit_int16 (acfg, 0);
5201 emit_int16 (acfg, 0);
5202 } else {
5203 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5204 if (entry->next)
5205 emit_int16 (acfg, entry->next->index);
5206 else
5207 emit_int16 (acfg, 0);
5212 static void
5213 emit_image_table (MonoAotCompile *acfg)
5215 int i;
5216 char symbol [256];
5219 * The image table is small but referenced in a lot of places.
5220 * So we emit it at once, and reference its elements by an index.
5223 sprintf (symbol, "mono_image_table");
5224 emit_section_change (acfg, ".text", 1);
5225 emit_global (acfg, symbol, FALSE);
5226 emit_alignment (acfg, 8);
5227 emit_label (acfg, symbol);
5229 emit_int32 (acfg, acfg->image_table->len);
5230 for (i = 0; i < acfg->image_table->len; i++) {
5231 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5232 MonoAssemblyName *aname = &image->assembly->aname;
5234 /* FIXME: Support multi-module assemblies */
5235 g_assert (image->assembly->image == image);
5237 emit_string (acfg, image->assembly_name);
5238 emit_string (acfg, image->guid);
5239 emit_string (acfg, aname->culture ? aname->culture : "");
5240 emit_string (acfg, (const char*)aname->public_key_token);
5242 emit_alignment (acfg, 8);
5243 emit_int32 (acfg, aname->flags);
5244 emit_int32 (acfg, aname->major);
5245 emit_int32 (acfg, aname->minor);
5246 emit_int32 (acfg, aname->build);
5247 emit_int32 (acfg, aname->revision);
5251 static void
5252 emit_got_info (MonoAotCompile *acfg)
5254 char symbol [256];
5255 int i, first_plt_got_patch, buf_size;
5256 guint8 *p, *buf;
5257 guint32 *got_info_offsets;
5259 /* Add the patches needed by the PLT to the GOT */
5260 acfg->plt_got_offset_base = acfg->got_offset;
5261 first_plt_got_patch = acfg->got_patches->len;
5262 for (i = 1; i < acfg->plt_offset; ++i) {
5263 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
5265 g_ptr_array_add (acfg->got_patches, patch_info);
5268 acfg->got_offset += acfg->plt_offset;
5271 * FIXME:
5272 * - optimize offsets table.
5273 * - reduce number of exported symbols.
5274 * - emit info for a klass only once.
5275 * - determine when a method uses a GOT slot which is guaranteed to be already
5276 * initialized.
5277 * - clean up and document the code.
5278 * - use String.Empty in class libs.
5281 /* Encode info required to decode shared GOT entries */
5282 buf_size = acfg->got_patches->len * 64;
5283 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5284 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5285 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5286 /* Unused */
5287 if (acfg->plt_offset)
5288 acfg->plt_got_info_offsets [0] = 0;
5289 for (i = 0; i < acfg->got_patches->len; ++i) {
5290 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5292 p = buf;
5294 encode_value (ji->type, p, &p);
5295 encode_patch (acfg, ji, p, &p);
5297 g_assert (p - buf <= buf_size);
5298 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5300 if (i >= first_plt_got_patch)
5301 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5302 acfg->stats.got_info_size += p - buf;
5305 /* Emit got_info_offsets table */
5306 sprintf (symbol, "got_info_offsets");
5307 emit_section_change (acfg, ".text", 1);
5308 emit_global (acfg, symbol, FALSE);
5309 emit_alignment (acfg, 8);
5310 emit_label (acfg, symbol);
5312 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5313 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5316 static void
5317 emit_got (MonoAotCompile *acfg)
5319 char symbol [256];
5321 if (!acfg->llvm) {
5322 /* Don't make GOT global so accesses to it don't need relocations */
5323 sprintf (symbol, "%s", acfg->got_symbol);
5324 emit_section_change (acfg, ".bss", 0);
5325 emit_alignment (acfg, 8);
5326 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5327 emit_label (acfg, symbol);
5328 if (acfg->got_offset > 0)
5329 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5331 sprintf (symbol, "got_end");
5332 emit_label (acfg, symbol);
5335 sprintf (symbol, "mono_aot_got_addr");
5336 emit_section_change (acfg, ".data", 0);
5337 emit_global (acfg, symbol, FALSE);
5338 emit_alignment (acfg, 8);
5339 emit_label (acfg, symbol);
5340 emit_pointer (acfg, acfg->got_symbol);
5343 typedef struct GlobalsTableEntry {
5344 guint32 value, index;
5345 struct GlobalsTableEntry *next;
5346 } GlobalsTableEntry;
5348 static void
5349 emit_globals_table (MonoAotCompile *acfg)
5351 int i, table_size;
5352 guint32 hash;
5353 GPtrArray *table;
5354 char symbol [256];
5355 GlobalsTableEntry *entry, *new_entry;
5358 * Construct a chained hash table for mapping global names to their index in
5359 * the globals table.
5361 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5362 table = g_ptr_array_sized_new (table_size);
5363 for (i = 0; i < table_size; ++i)
5364 g_ptr_array_add (table, NULL);
5365 for (i = 0; i < acfg->globals->len; ++i) {
5366 char *name = g_ptr_array_index (acfg->globals, i);
5368 hash = mono_metadata_str_hash (name) % table_size;
5370 /* FIXME: Allocate from the mempool */
5371 new_entry = g_new0 (GlobalsTableEntry, 1);
5372 new_entry->value = i;
5374 entry = g_ptr_array_index (table, hash);
5375 if (entry == NULL) {
5376 new_entry->index = hash;
5377 g_ptr_array_index (table, hash) = new_entry;
5378 } else {
5379 while (entry->next)
5380 entry = entry->next;
5382 entry->next = new_entry;
5383 new_entry->index = table->len;
5384 g_ptr_array_add (table, new_entry);
5388 /* Emit the table */
5389 sprintf (symbol, ".Lglobals_hash");
5390 emit_section_change (acfg, ".text", 0);
5391 emit_alignment (acfg, 8);
5392 emit_label (acfg, symbol);
5394 /* FIXME: Optimize memory usage */
5395 g_assert (table_size < 65000);
5396 emit_int16 (acfg, table_size);
5397 for (i = 0; i < table->len; ++i) {
5398 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5400 if (entry == NULL) {
5401 emit_int16 (acfg, 0);
5402 emit_int16 (acfg, 0);
5403 } else {
5404 emit_int16 (acfg, entry->value + 1);
5405 if (entry->next)
5406 emit_int16 (acfg, entry->next->index);
5407 else
5408 emit_int16 (acfg, 0);
5412 /* Emit the names */
5413 for (i = 0; i < acfg->globals->len; ++i) {
5414 char *name = g_ptr_array_index (acfg->globals, i);
5416 sprintf (symbol, "name_%d", i);
5417 emit_section_change (acfg, ".text", 1);
5418 emit_label (acfg, symbol);
5419 emit_string (acfg, name);
5422 /* Emit the globals table */
5423 sprintf (symbol, ".Lglobals");
5424 emit_section_change (acfg, ".data", 0);
5425 /* This is not a global, since it is accessed by the init function */
5426 emit_alignment (acfg, 8);
5427 emit_label (acfg, symbol);
5429 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5430 emit_pointer (acfg, symbol);
5432 for (i = 0; i < acfg->globals->len; ++i) {
5433 char *name = g_ptr_array_index (acfg->globals, i);
5435 sprintf (symbol, "name_%d", i);
5436 emit_pointer (acfg, symbol);
5438 sprintf (symbol, "%s", name);
5439 emit_pointer (acfg, symbol);
5441 /* Null terminate the table */
5442 emit_int32 (acfg, 0);
5443 emit_int32 (acfg, 0);
5446 static void
5447 emit_globals (MonoAotCompile *acfg)
5449 char *build_info;
5451 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5453 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5455 if (acfg->aot_opts.bind_to_runtime_version) {
5456 build_info = mono_get_runtime_build_info ();
5457 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5458 g_free (build_info);
5459 } else {
5460 emit_string_symbol (acfg, "mono_runtime_version", "");
5464 * When static linking, we emit a global which will point to the symbol table.
5466 if (acfg->aot_opts.static_link) {
5467 char symbol [256];
5468 char *p;
5470 /* Emit a string holding the assembly name */
5471 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5473 emit_globals_table (acfg);
5476 * Emit a global symbol which can be passed by an embedding app to
5477 * mono_aot_register_module ().
5479 #if defined(__MACH__)
5480 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5481 #else
5482 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5483 #endif
5485 /* Get rid of characters which cannot occur in symbols */
5486 p = symbol;
5487 for (p = symbol; *p; ++p) {
5488 if (!(isalnum (*p) || *p == '_'))
5489 *p = '_';
5491 acfg->static_linking_symbol = g_strdup (symbol);
5492 emit_global_inner (acfg, symbol, FALSE);
5493 emit_alignment (acfg, 8);
5494 emit_label (acfg, symbol);
5495 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5496 emit_pointer (acfg, symbol);
5500 static void
5501 emit_autoreg (MonoAotCompile *acfg)
5503 char *symbol;
5506 * Emit a function into the .ctor section which will be called by the ELF
5507 * loader to register this module with the runtime.
5509 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5510 return;
5512 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5514 arch_emit_autoreg (acfg, symbol);
5516 g_free (symbol);
5519 static void
5520 emit_mem_end (MonoAotCompile *acfg)
5522 char symbol [128];
5524 sprintf (symbol, "mem_end");
5525 emit_section_change (acfg, ".text", 1);
5526 emit_global (acfg, symbol, FALSE);
5527 emit_alignment (acfg, 8);
5528 emit_label (acfg, symbol);
5532 * Emit a structure containing all the information not stored elsewhere.
5534 static void
5535 emit_file_info (MonoAotCompile *acfg)
5537 char symbol [128];
5538 int i;
5540 sprintf (symbol, "mono_aot_file_info");
5541 emit_section_change (acfg, ".data", 0);
5542 emit_alignment (acfg, 8);
5543 emit_label (acfg, symbol);
5544 emit_global (acfg, symbol, FALSE);
5546 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5547 emit_int32 (acfg, acfg->plt_got_offset_base);
5548 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5549 emit_int32 (acfg, acfg->plt_offset);
5550 emit_int32 (acfg, acfg->nmethods);
5551 emit_int32 (acfg, acfg->flags);
5552 emit_int32 (acfg, acfg->opts);
5554 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5555 emit_int32 (acfg, acfg->num_trampolines [i]);
5556 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5557 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5558 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5559 emit_int32 (acfg, acfg->trampoline_size [i]);
5562 static void
5563 emit_blob (MonoAotCompile *acfg)
5565 char symbol [128];
5567 sprintf (symbol, "blob");
5568 emit_section_change (acfg, ".text", 1);
5569 emit_global (acfg, symbol, FALSE);
5570 emit_alignment (acfg, 8);
5571 emit_label (acfg, symbol);
5573 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5576 static void
5577 emit_dwarf_info (MonoAotCompile *acfg)
5579 #ifdef EMIT_DWARF_INFO
5580 int i;
5581 char symbol [128], symbol2 [128];
5583 /* DIEs for methods */
5584 for (i = 0; i < acfg->nmethods; ++i) {
5585 MonoCompile *cfg = acfg->cfgs [i];
5587 if (!cfg)
5588 continue;
5590 // FIXME: LLVM doesn't define .Lme_...
5591 if (cfg->compile_llvm)
5592 continue;
5594 sprintf (symbol, "%s", cfg->asm_symbol);
5595 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5597 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 ()));
5599 #endif
5602 static void
5603 collect_methods (MonoAotCompile *acfg)
5605 int i;
5606 MonoImage *image = acfg->image;
5608 /* Collect methods */
5609 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5610 MonoMethod *method;
5611 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5613 method = mono_get_method (acfg->image, token, NULL);
5615 if (!method) {
5616 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5617 exit (1);
5620 /* Load all methods eagerly to skip the slower lazy loading code */
5621 mono_class_setup_methods (method->klass);
5623 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5624 /* Compile the wrapper instead */
5625 /* We do this here instead of add_wrappers () because it is easy to do it here */
5626 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5627 method = wrapper;
5630 /* FIXME: Some mscorlib methods don't have debug info */
5632 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5633 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5634 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5635 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5636 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5637 if (!mono_debug_lookup_method (method)) {
5638 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5639 exit (1);
5645 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5646 add_method_with_index (acfg, method, i, FALSE);
5647 acfg->method_index ++;
5650 add_generic_instances (acfg);
5652 if (acfg->aot_opts.full_aot)
5653 add_wrappers (acfg);
5656 static void
5657 compile_methods (MonoAotCompile *acfg)
5659 int i, methods_len;
5661 if (acfg->aot_opts.nthreads > 0) {
5662 GPtrArray *frag;
5663 int len, j;
5664 GPtrArray *threads;
5665 HANDLE handle;
5666 gpointer *user_data;
5667 MonoMethod **methods;
5669 methods_len = acfg->methods->len;
5671 len = acfg->methods->len / acfg->aot_opts.nthreads;
5672 g_assert (len > 0);
5674 * Partition the list of methods into fragments, and hand it to threads to
5675 * process.
5677 threads = g_ptr_array_new ();
5678 /* Make a copy since acfg->methods is modified by compile_method () */
5679 methods = g_new0 (MonoMethod*, methods_len);
5680 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5681 for (i = 0; i < methods_len; ++i)
5682 methods [i] = g_ptr_array_index (acfg->methods, i);
5683 i = 0;
5684 while (i < methods_len) {
5685 frag = g_ptr_array_new ();
5686 for (j = 0; j < len; ++j) {
5687 if (i < methods_len) {
5688 g_ptr_array_add (frag, methods [i]);
5689 i ++;
5693 user_data = g_new0 (gpointer, 3);
5694 user_data [0] = mono_domain_get ();
5695 user_data [1] = acfg;
5696 user_data [2] = frag;
5698 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5699 g_ptr_array_add (threads, handle);
5701 g_free (methods);
5703 for (i = 0; i < threads->len; ++i) {
5704 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5706 } else {
5707 methods_len = 0;
5710 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5711 for (i = methods_len; i < acfg->methods->len; ++i) {
5712 /* This can new methods to acfg->methods */
5713 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5717 static int
5718 compile_asm (MonoAotCompile *acfg)
5720 char *command, *objfile;
5721 char *outfile_name, *tmp_outfile_name;
5722 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5724 #if defined(TARGET_AMD64)
5725 #define AS_OPTIONS "--64"
5726 #elif defined(TARGET_POWERPC64)
5727 #define AS_OPTIONS "-a64 -mppc64"
5728 #define LD_OPTIONS "-m elf64ppc"
5729 #elif defined(sparc) && SIZEOF_VOID_P == 8
5730 #define AS_OPTIONS "-xarch=v9"
5731 #else
5732 #define AS_OPTIONS ""
5733 #endif
5735 #ifndef LD_OPTIONS
5736 #define LD_OPTIONS ""
5737 #endif
5739 #ifdef ENABLE_LLVM
5740 #define EH_LD_OPTIONS "--eh-frame-hdr"
5741 #else
5742 #define EH_LD_OPTIONS ""
5743 #endif
5745 if (acfg->aot_opts.asm_only) {
5746 printf ("Output file: '%s'.\n", acfg->tmpfname);
5747 if (acfg->aot_opts.static_link)
5748 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5749 return 0;
5752 if (acfg->aot_opts.static_link) {
5753 if (acfg->aot_opts.outfile)
5754 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5755 else
5756 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5757 } else {
5758 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5760 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5761 printf ("Executing the native assembler: %s\n", command);
5762 if (system (command) != 0) {
5763 g_free (command);
5764 g_free (objfile);
5765 return 1;
5768 g_free (command);
5770 if (acfg->aot_opts.static_link) {
5771 printf ("Output file: '%s'.\n", objfile);
5772 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5773 g_free (objfile);
5774 return 0;
5777 if (acfg->aot_opts.outfile)
5778 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5779 else
5780 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5782 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5784 #if defined(sparc)
5785 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5786 #elif defined(__ppc__) && defined(__MACH__)
5787 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5788 #elif defined(HOST_WIN32)
5789 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5790 #else
5791 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5792 #endif
5793 printf ("Executing the native linker: %s\n", command);
5794 if (system (command) != 0) {
5795 g_free (tmp_outfile_name);
5796 g_free (outfile_name);
5797 g_free (command);
5798 g_free (objfile);
5799 return 1;
5802 g_free (command);
5803 unlink (objfile);
5804 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5805 printf ("Stripping the binary: %s\n", com);
5806 system (com);
5807 g_free (com);*/
5809 #if defined(TARGET_ARM) && !defined(__MACH__)
5811 * gas generates 'mapping symbols' each time code and data is mixed, which
5812 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5814 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5815 printf ("Stripping the binary: %s\n", command);
5816 if (system (command) != 0) {
5817 g_free (tmp_outfile_name);
5818 g_free (outfile_name);
5819 g_free (command);
5820 g_free (objfile);
5821 return 1;
5823 #endif
5825 rename (tmp_outfile_name, outfile_name);
5827 g_free (tmp_outfile_name);
5828 g_free (outfile_name);
5829 g_free (objfile);
5831 if (acfg->aot_opts.save_temps)
5832 printf ("Retained input file.\n");
5833 else
5834 unlink (acfg->tmpfname);
5836 return 0;
5839 static MonoAotCompile*
5840 acfg_create (MonoAssembly *ass, guint32 opts)
5842 MonoImage *image = ass->image;
5843 MonoAotCompile *acfg;
5844 int i;
5846 acfg = g_new0 (MonoAotCompile, 1);
5847 acfg->methods = g_ptr_array_new ();
5848 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5849 acfg->method_depth = g_hash_table_new (NULL, NULL);
5850 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5851 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5852 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5853 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5854 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5855 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5856 acfg->got_patches = g_ptr_array_new ();
5857 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5858 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5859 acfg->image_hash = g_hash_table_new (NULL, NULL);
5860 acfg->image_table = g_ptr_array_new ();
5861 acfg->globals = g_ptr_array_new ();
5862 acfg->image = image;
5863 acfg->opts = opts;
5864 acfg->mempool = mono_mempool_new ();
5865 acfg->extra_methods = g_ptr_array_new ();
5866 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5867 acfg->unwind_ops = g_ptr_array_new ();
5868 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5869 InitializeCriticalSection (&acfg->mutex);
5871 return acfg;
5874 static void
5875 acfg_free (MonoAotCompile *acfg)
5877 int i;
5879 img_writer_destroy (acfg->w);
5880 for (i = 0; i < acfg->nmethods; ++i)
5881 if (acfg->cfgs [i])
5882 g_free (acfg->cfgs [i]);
5883 g_free (acfg->cfgs);
5884 g_free (acfg->static_linking_symbol);
5885 g_free (acfg->got_symbol);
5886 g_free (acfg->plt_symbol);
5887 g_ptr_array_free (acfg->methods, TRUE);
5888 g_ptr_array_free (acfg->got_patches, TRUE);
5889 g_ptr_array_free (acfg->image_table, TRUE);
5890 g_ptr_array_free (acfg->globals, TRUE);
5891 g_ptr_array_free (acfg->unwind_ops, TRUE);
5892 g_hash_table_destroy (acfg->method_indexes);
5893 g_hash_table_destroy (acfg->method_depth);
5894 g_hash_table_destroy (acfg->plt_offset_to_patch);
5895 g_hash_table_destroy (acfg->patch_to_plt_offset);
5896 g_hash_table_destroy (acfg->patch_to_got_offset);
5897 g_hash_table_destroy (acfg->method_to_cfg);
5898 g_hash_table_destroy (acfg->token_info_hash);
5899 g_hash_table_destroy (acfg->image_hash);
5900 g_hash_table_destroy (acfg->unwind_info_offsets);
5901 g_hash_table_destroy (acfg->method_label_hash);
5902 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5903 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
5904 g_free (acfg->patch_to_got_offset_by_type);
5905 mono_mempool_destroy (acfg->mempool);
5906 g_free (acfg);
5910 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5912 MonoImage *image = ass->image;
5913 int i, res;
5914 MonoAotCompile *acfg;
5915 char *outfile_name, *tmp_outfile_name, *p;
5916 TV_DECLARE (atv);
5917 TV_DECLARE (btv);
5919 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5921 acfg = acfg_create (ass, opts);
5923 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5924 acfg->aot_opts.write_symbols = TRUE;
5925 acfg->aot_opts.ntrampolines = 1024;
5926 acfg->aot_opts.nrgctx_trampolines = 1024;
5927 acfg->aot_opts.nimt_trampolines = 128;
5929 mono_aot_parse_options (aot_options, &acfg->aot_opts);
5931 if (acfg->aot_opts.static_link)
5932 acfg->aot_opts.autoreg = TRUE;
5934 //acfg->aot_opts.print_skipped_methods = TRUE;
5936 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5937 if (acfg->aot_opts.full_aot) {
5938 printf ("--aot=full is not supported on this platform.\n");
5939 return 1;
5941 #endif
5943 if (acfg->aot_opts.static_link)
5944 acfg->aot_opts.asm_writer = TRUE;
5946 if (acfg->aot_opts.soft_debug) {
5947 MonoDebugOptions *opt = mini_get_debug_options ();
5949 opt->mdb_optimizations = TRUE;
5950 opt->gen_seq_points = TRUE;
5952 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
5953 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
5954 return 1;
5958 #ifdef ENABLE_LLVM
5959 acfg->llvm = TRUE;
5960 acfg->aot_opts.asm_writer = TRUE;
5961 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
5962 #endif
5964 if (acfg->aot_opts.full_aot)
5965 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
5967 load_profile_files (acfg);
5969 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5970 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5971 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
5972 #endif
5973 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
5975 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5976 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5978 /* Get rid of characters which cannot occur in symbols */
5979 for (p = acfg->got_symbol_base; *p; ++p) {
5980 if (!(isalnum (*p) || *p == '_'))
5981 *p = '_';
5983 for (p = acfg->plt_symbol; *p; ++p) {
5984 if (!(isalnum (*p) || *p == '_'))
5985 *p = '_';
5988 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
5990 acfg->method_index = 1;
5992 collect_methods (acfg);
5994 acfg->cfgs_size = acfg->methods->len + 32;
5995 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5997 /* PLT offset 0 is reserved for the PLT trampoline */
5998 acfg->plt_offset = 1;
6000 #ifdef ENABLE_LLVM
6001 llvm_acfg = acfg;
6002 mono_llvm_create_aot_module (acfg->got_symbol_base);
6003 #endif
6005 /* GOT offset 0 is reserved for the address of the current assembly */
6007 MonoJumpInfo *ji;
6009 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6010 ji->type = MONO_PATCH_INFO_IMAGE;
6011 ji->data.image = acfg->image;
6013 get_got_offset (acfg, ji);
6015 /* Slot 1 is reserved for the mscorlib got addr */
6016 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6017 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6018 get_got_offset (acfg, ji);
6021 TV_GETTIME (atv);
6023 compile_methods (acfg);
6025 TV_GETTIME (btv);
6027 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6029 TV_GETTIME (atv);
6031 #ifdef ENABLE_LLVM
6032 if (acfg->llvm) {
6033 if (acfg->aot_opts.asm_only) {
6034 if (acfg->aot_opts.outfile)
6035 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6036 else
6037 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6038 } else {
6039 acfg->tmpfname = g_strdup ("temp.s");
6043 emit_llvm_file (acfg);
6044 #endif
6046 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6047 if (acfg->aot_opts.outfile)
6048 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6049 else
6050 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6053 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6054 * it might be in another file system so the rename () won't work.
6056 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6058 acfg->fp = fopen (tmp_outfile_name, "w");
6059 if (!acfg->fp) {
6060 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6061 return 1;
6064 acfg->w = img_writer_create (acfg->fp, TRUE);
6065 acfg->use_bin_writer = TRUE;
6066 } else {
6067 if (acfg->llvm) {
6068 /* Append to the .s file created by llvm */
6069 /* FIXME: Use multiple files instead */
6070 acfg->fp = fopen (acfg->tmpfname, "a+");
6071 } else {
6072 if (acfg->aot_opts.asm_only) {
6073 if (acfg->aot_opts.outfile)
6074 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6075 else
6076 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6077 acfg->fp = fopen (acfg->tmpfname, "w+");
6078 } else {
6079 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6080 acfg->fp = fdopen (i, "w+");
6082 g_assert (acfg->fp);
6084 acfg->w = img_writer_create (acfg->fp, FALSE);
6086 tmp_outfile_name = NULL;
6087 outfile_name = NULL;
6091 * The prefix LLVM likes to put in front of symbol names on darwin.
6092 * The mach-os specs require this for globals, but LLVM puts them in front of all
6093 * symbols. We need to handle this, since we need to refer to LLVM generated
6094 * symbols.
6096 acfg->llvm_label_prefix = "";
6097 if (acfg->llvm)
6098 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6100 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6102 /* Compute symbols for methods */
6103 for (i = 0; i < acfg->nmethods; ++i) {
6104 if (acfg->cfgs [i]) {
6105 MonoCompile *cfg = acfg->cfgs [i];
6106 int method_index = get_method_index (acfg, cfg->orig_method);
6108 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6112 if (!acfg->aot_opts.nodebug)
6113 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6115 img_writer_emit_start (acfg->w);
6117 if (acfg->dwarf)
6118 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6120 emit_code (acfg);
6122 emit_info (acfg);
6124 emit_extra_methods (acfg);
6126 emit_trampolines (acfg);
6128 emit_class_name_table (acfg);
6130 emit_got_info (acfg);
6132 emit_exception_info (acfg);
6134 emit_unwind_info (acfg);
6136 emit_class_info (acfg);
6138 emit_plt (acfg);
6140 emit_image_table (acfg);
6142 emit_got (acfg);
6144 emit_file_info (acfg);
6146 emit_blob (acfg);
6148 emit_globals (acfg);
6150 emit_autoreg (acfg);
6152 if (acfg->dwarf) {
6153 emit_dwarf_info (acfg);
6154 mono_dwarf_writer_close (acfg->dwarf);
6157 emit_mem_end (acfg);
6159 TV_GETTIME (btv);
6161 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6163 if (acfg->llvm)
6164 g_assert (acfg->got_offset <= acfg->final_got_size);
6166 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);
6168 TV_GETTIME (atv);
6169 res = img_writer_emit_writeout (acfg->w);
6170 if (res != 0) {
6171 acfg_free (acfg);
6172 return res;
6174 if (acfg->use_bin_writer) {
6175 int err = rename (tmp_outfile_name, outfile_name);
6177 if (err) {
6178 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6179 return 1;
6181 } else {
6182 res = compile_asm (acfg);
6183 if (res != 0) {
6184 acfg_free (acfg);
6185 return res;
6188 TV_GETTIME (btv);
6189 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6191 printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
6192 if (acfg->stats.genericcount)
6193 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6194 if (acfg->stats.abscount)
6195 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6196 if (acfg->stats.lmfcount)
6197 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6198 if (acfg->stats.ocount)
6199 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6200 if (acfg->llvm)
6201 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6202 printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
6203 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6205 if (acfg->aot_opts.stats) {
6206 int i;
6208 printf ("GOT slot distribution:\n");
6209 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6210 if (acfg->stats.got_slot_types [i])
6211 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6214 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);
6216 acfg_free (acfg);
6218 return 0;
6221 #else
6223 /* AOT disabled */
6226 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6228 return 0;
6231 #endif