Merge branch 'cecil-light'
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot-compiler.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
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.
23  */
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
41
42 #include <errno.h>
43 #include <sys/stat.h>
44
45
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>
64
65 #include "mini.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
73 #else
74 #define RODATA_SECT ".text"
75 #endif
76
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
80
81 #ifdef TARGET_WIN32
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__MACH__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
87 #else
88 #define SHARED_EXT ".so"
89 #endif
90
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
94
95 typedef struct MonoAotOptions {
96         char *outfile;
97         gboolean save_temps;
98         gboolean write_symbols;
99         gboolean metadata_only;
100         gboolean bind_to_runtime_version;
101         gboolean full_aot;
102         gboolean no_dlsym;
103         gboolean static_link;
104         gboolean asm_only;
105         gboolean asm_writer;
106         gboolean nodebug;
107         gboolean soft_debug;
108         int nthreads;
109         int ntrampolines;
110         int nrgctx_trampolines;
111         int nimt_trampolines;
112         gboolean print_skipped_methods;
113         gboolean stats;
114         char *tool_prefix;
115         gboolean autoreg;
116 } MonoAotOptions;
117
118 typedef struct MonoAotStats {
119         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
120         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
121         int methods_without_got_slots, direct_calls, all_calls, llvm_count;
122         int got_slots, offsets_size;
123         int got_slot_types [MONO_PATCH_INFO_NONE];
124         int jit_time, gen_time, link_time;
125 } MonoAotStats;
126
127 typedef struct MonoAotCompile {
128         MonoImage *image;
129         GPtrArray *methods;
130         GHashTable *method_indexes;
131         GHashTable *method_depth;
132         MonoCompile **cfgs;
133         int cfgs_size;
134         GHashTable *patch_to_plt_entry;
135         GHashTable *plt_offset_to_entry;
136         GHashTable *patch_to_got_offset;
137         GHashTable **patch_to_got_offset_by_type;
138         GPtrArray *got_patches;
139         GHashTable *image_hash;
140         GHashTable *method_to_cfg;
141         GHashTable *token_info_hash;
142         GPtrArray *extra_methods;
143         GPtrArray *image_table;
144         GPtrArray *globals;
145         GList *method_order;
146         guint32 *plt_got_info_offsets;
147         guint32 got_offset, plt_offset, plt_got_offset_base;
148         guint32 final_got_size;
149         /* Number of GOT entries reserved for trampolines */
150         guint32 num_trampoline_got_entries;
151
152         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
153         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
154         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
155
156         MonoAotOptions aot_opts;
157         guint32 nmethods;
158         guint32 opts;
159         MonoMemPool *mempool;
160         MonoAotStats stats;
161         int method_index;
162         char *static_linking_symbol;
163         CRITICAL_SECTION mutex;
164         gboolean use_bin_writer;
165         MonoImageWriter *w;
166         MonoDwarfWriter *dwarf;
167         FILE *fp;
168         char *tmpfname;
169         GSList *cie_program;
170         GHashTable *unwind_info_offsets;
171         GPtrArray *unwind_ops;
172         guint32 unwind_info_offset;
173         char *got_symbol_base;
174         char *got_symbol;
175         char *plt_symbol;
176         GHashTable *method_label_hash;
177         const char *temp_prefix;
178         const char *llvm_label_prefix;
179         guint32 label_generator;
180         gboolean llvm;
181         MonoAotFileFlags flags;
182         MonoDynamicStream blob;
183         MonoClass **typespec_classes;
184 } MonoAotCompile;
185
186 typedef struct {
187         int plt_offset;
188         char *symbol;
189         MonoJumpInfo *ji;
190 } MonoPltEntry;
191
192 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
193 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
194
195 /* This points to the current acfg in LLVM mode */
196 static MonoAotCompile *llvm_acfg;
197
198 #ifdef HAVE_ARRAY_ELEM_INIT
199 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
200 #define MSGSTRFIELD1(line) str##line
201 static const struct msgstr_t {
202 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
203 #include "patch-info.h"
204 #undef PATCH_INFO
205 } opstr = {
206 #define PATCH_INFO(a,b) b,
207 #include "patch-info.h"
208 #undef PATCH_INFO
209 };
210 static const gint16 opidx [] = {
211 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
212 #include "patch-info.h"
213 #undef PATCH_INFO
214 };
215
216 static G_GNUC_UNUSED const char*
217 get_patch_name (int info)
218 {
219         return (const char*)&opstr + opidx [info];
220 }
221
222 #else
223 #define PATCH_INFO(a,b) b,
224 static const char* const
225 patch_types [MONO_PATCH_INFO_NUM + 1] = {
226 #include "patch-info.h"
227         NULL
228 };
229
230 static G_GNUC_UNUSED const char*
231 get_patch_name (int info)
232 {
233         return patch_types [info];
234 }
235
236 #endif
237
238 /* Wrappers around the image writer functions */
239
240 static inline void
241 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
242 {
243         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
244 }
245
246 static inline void
247 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
248 {
249         img_writer_emit_push_section (acfg->w, section_name, subsection);
250 }
251
252 static inline void
253 emit_pop_section (MonoAotCompile *acfg)
254 {
255         img_writer_emit_pop_section (acfg->w);
256 }
257
258 static inline void
259 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
260
261         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
262 }
263
264 static inline void
265 emit_label (MonoAotCompile *acfg, const char *name) 
266
267         img_writer_emit_label (acfg->w, name); 
268 }
269
270 static inline void
271 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
272
273         img_writer_emit_bytes (acfg->w, buf, size); 
274 }
275
276 static inline void
277 emit_string (MonoAotCompile *acfg, const char *value) 
278
279         img_writer_emit_string (acfg->w, value); 
280 }
281
282 static inline void
283 emit_line (MonoAotCompile *acfg) 
284
285         img_writer_emit_line (acfg->w); 
286 }
287
288 static inline void
289 emit_alignment (MonoAotCompile *acfg, int size) 
290
291         img_writer_emit_alignment (acfg->w, size); 
292 }
293
294 static inline void
295 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
296
297         img_writer_emit_pointer_unaligned (acfg->w, target); 
298 }
299
300 static inline void
301 emit_pointer (MonoAotCompile *acfg, const char *target) 
302
303         img_writer_emit_pointer (acfg->w, target); 
304 }
305
306 static inline void
307 emit_int16 (MonoAotCompile *acfg, int value) 
308
309         img_writer_emit_int16 (acfg->w, value); 
310 }
311
312 static inline void
313 emit_int32 (MonoAotCompile *acfg, int value) 
314
315         img_writer_emit_int32 (acfg->w, value); 
316 }
317
318 static inline void
319 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
320
321         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
322 }
323
324 static inline void
325 emit_zero_bytes (MonoAotCompile *acfg, int num) 
326
327         img_writer_emit_zero_bytes (acfg->w, num); 
328 }
329
330 static inline void
331 emit_byte (MonoAotCompile *acfg, guint8 val) 
332
333         img_writer_emit_byte (acfg->w, val); 
334 }
335
336 #ifdef __native_client_codegen__
337 static inline void
338 emit_nacl_call_alignment (MonoAotCompile *acfg)
339 {
340         img_writer_emit_nacl_call_alignment (acfg->w);
341 }
342 #endif
343
344 static G_GNUC_UNUSED void
345 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
346 {
347         img_writer_emit_global (acfg->w, name, func);
348 }
349
350 static void
351 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
352 {
353         if (acfg->aot_opts.no_dlsym) {
354                 g_ptr_array_add (acfg->globals, g_strdup (name));
355                 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
356         } else {
357                 img_writer_emit_global (acfg->w, name, func);
358         }
359 }
360
361 static void
362 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
363 {
364         img_writer_emit_symbol_size (acfg->w, name, end_label);
365 }
366
367 static void
368 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
369 {
370         img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
371         emit_global (acfg, name, FALSE);
372         img_writer_emit_label (acfg->w, name);
373         img_writer_emit_string (acfg->w, value);
374 }
375
376 static G_GNUC_UNUSED void
377 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
378 {
379         do {
380                 guint8 b = value & 0x7f;
381                 value >>= 7;
382                 if (value != 0) /* more bytes to come */
383                         b |= 0x80;
384                 emit_byte (acfg, b);
385         } while (value);
386 }
387
388 static G_GNUC_UNUSED void
389 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
390 {
391         gboolean more = 1;
392         gboolean negative = (value < 0);
393         guint32 size = 64;
394         guint8 byte;
395
396         while (more) {
397                 byte = value & 0x7f;
398                 value >>= 7;
399                 /* the following is unnecessary if the
400                  * implementation of >>= uses an arithmetic rather
401                  * than logical shift for a signed left operand
402                  */
403                 if (negative)
404                         /* sign extend */
405                         value |= - ((gint64)1 <<(size - 7));
406                 /* sign bit of byte is second high order bit (0x40) */
407                 if ((value == 0 && !(byte & 0x40)) ||
408                         (value == -1 && (byte & 0x40)))
409                         more = 0;
410                 else
411                         byte |= 0x80;
412                 emit_byte (acfg, byte);
413         }
414 }
415
416 static G_GNUC_UNUSED void
417 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
418 {
419         guint8 *p = buf;
420
421         do {
422                 guint8 b = value & 0x7f;
423                 value >>= 7;
424                 if (value != 0) /* more bytes to come */
425                         b |= 0x80;
426                 *p ++ = b;
427         } while (value);
428
429         *endbuf = p;
430 }
431
432 static G_GNUC_UNUSED void
433 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
434 {
435         gboolean more = 1;
436         gboolean negative = (value < 0);
437         guint32 size = 32;
438         guint8 byte;
439         guint8 *p = buf;
440
441         while (more) {
442                 byte = value & 0x7f;
443                 value >>= 7;
444                 /* the following is unnecessary if the
445                  * implementation of >>= uses an arithmetic rather
446                  * than logical shift for a signed left operand
447                  */
448                 if (negative)
449                         /* sign extend */
450                         value |= - (1 <<(size - 7));
451                 /* sign bit of byte is second high order bit (0x40) */
452                 if ((value == 0 && !(byte & 0x40)) ||
453                         (value == -1 && (byte & 0x40)))
454                         more = 0;
455                 else
456                         byte |= 0x80;
457                 *p ++= byte;
458         }
459
460         *endbuf = p;
461 }
462
463 /* ARCHITECTURE SPECIFIC CODE */
464
465 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
466 #define EMIT_DWARF_INFO 1
467 #endif
468
469 #if defined(TARGET_ARM)
470 #define AOT_FUNC_ALIGNMENT 4
471 #else
472 #define AOT_FUNC_ALIGNMENT 16
473 #endif
474 #if defined(TARGET_X86) && defined(__native_client_codegen__)
475 #undef AOT_FUNC_ALIGNMENT
476 #define AOT_FUNC_ALIGNMENT 32
477 #endif
478  
479 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
480 #define PPC_LD_OP "ld"
481 #define PPC_LDX_OP "ldx"
482 #else
483 #define PPC_LD_OP "lwz"
484 #define PPC_LDX_OP "lwzx"
485 #endif
486
487 //#define TARGET_ARM
488
489 #ifdef TARGET_ARM
490 #define LLVM_LABEL_PREFIX "_"
491 #else
492 #define LLVM_LABEL_PREFIX ""
493 #endif
494
495 #ifdef TARGET_ARM
496 /* iphone */
497 #define LLC_TARGET_ARGS "-march=arm -mattr=+v6 -mtriple=arm-apple-darwin"
498 /* ELF */
499 //#define LLC_TARGET_ARGS "-march=arm -mtriple=arm-linux-gnueabi -soft-float"
500 #else
501 #define LLC_TARGET_ARGS ""
502 #endif
503
504 /*
505  * arch_emit_direct_call:
506  *
507  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
508  * calling code.
509  */
510 static void
511 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
512 {
513 #if defined(TARGET_X86) || defined(TARGET_AMD64)
514         /* Need to make sure this is exactly 5 bytes long */
515         emit_byte (acfg, '\xe8');
516         emit_symbol_diff (acfg, target, ".", -4);
517         *call_size = 5;
518 #elif defined(TARGET_ARM)
519         if (acfg->use_bin_writer) {
520                 guint8 buf [4];
521                 guint8 *code;
522
523                 code = buf;
524                 ARM_BL (code, 0);
525
526                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
527                 emit_bytes (acfg, buf, 4);
528         } else {
529                 img_writer_emit_unset_mode (acfg->w);
530                 fprintf (acfg->fp, "bl %s\n", target);
531         }
532         *call_size = 4;
533 #elif defined(TARGET_POWERPC)
534         if (acfg->use_bin_writer) {
535                 g_assert_not_reached ();
536         } else {
537                 img_writer_emit_unset_mode (acfg->w);
538                 fprintf (acfg->fp, "bl %s\n", target);
539                 *call_size = 4;
540         }
541 #else
542         g_assert_not_reached ();
543 #endif
544 }
545
546 /*
547  * PPC32 design:
548  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
549  *   the GOT pointer.
550  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
551  *   in in the 2. slot of every GOT, and require every method to place the GOT
552  *   address in r30, even when it doesn't access the GOT otherwise. This way,
553  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
554  */
555
556 /*
557  * PPC64 design:
558  * PPC64 uses function descriptors which greatly complicate all code, since
559  * these are used very inconsistently in the runtime. Some functions like 
560  * mono_compile_method () return ftn descriptors, while others like the
561  * trampoline creation functions do not.
562  * We assume that all GOT slots contain function descriptors, and create 
563  * descriptors in aot-runtime.c when needed.
564  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
565  * from function descriptors, we could do the same, but it would require 
566  * rewriting all the ppc/aot code to handle function descriptors properly.
567  * So instead, we use the same approach as on PPC32.
568  * This is a horrible mess, but fixing it would probably lead to an even bigger
569  * one.
570  */
571
572 /*
573  * X86 design:
574  * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
575  */
576
577 #ifdef MONO_ARCH_AOT_SUPPORTED
578 /*
579  * arch_emit_got_offset:
580  *
581  *   The memory pointed to by CODE should hold native code for computing the GOT
582  * address. Emit this code while patching it with the offset between code and
583  * the GOT. CODE_SIZE is set to the number of bytes emitted.
584  */
585 static void
586 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
587 {
588 #if defined(TARGET_POWERPC64)
589         g_assert (!acfg->use_bin_writer);
590         img_writer_emit_unset_mode (acfg->w);
591         /* 
592          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
593          * unsupported relocations. So we store the got address into the .Lgot_addr
594          * symbol which is in the text segment, compute its address, and load it.
595          */
596         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
597         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
598         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
599         fprintf (acfg->fp, "add 30, 30, 0\n");
600         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
601         acfg->label_generator ++;
602         *code_size = 16;
603 #elif defined(TARGET_POWERPC)
604         g_assert (!acfg->use_bin_writer);
605         img_writer_emit_unset_mode (acfg->w);
606         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
607         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
608         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
609         acfg->label_generator ++;
610         *code_size = 8;
611 #else
612         guint32 offset = mono_arch_get_patch_offset (code);
613         emit_bytes (acfg, code, offset);
614         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
615
616         *code_size = offset + 4;
617 #endif
618 }
619
620 /*
621  * arch_emit_got_access:
622  *
623  *   The memory pointed to by CODE should hold native code for loading a GOT
624  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
625  * CODE_SIZE is set to the number of bytes emitted.
626  */
627 static void
628 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
629 {
630         /* Emit beginning of instruction */
631         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
632
633         /* Emit the offset */
634 #ifdef TARGET_AMD64
635         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
636         *code_size = mono_arch_get_patch_offset (code) + 4;
637 #elif defined(TARGET_X86)
638         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
639         *code_size = mono_arch_get_patch_offset (code) + 4;
640 #elif defined(TARGET_ARM)
641         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
642         *code_size = mono_arch_get_patch_offset (code) + 4;
643 #elif defined(TARGET_POWERPC)
644         {
645                 guint8 buf [32];
646                 guint8 *code;
647
648                 code = buf;
649                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
650                 g_assert (code - buf == 8);
651                 emit_bytes (acfg, buf, code - buf);
652                 *code_size = code - buf;
653         }
654 #else
655         g_assert_not_reached ();
656 #endif
657 }
658
659 #endif
660
661 /*
662  * arch_emit_plt_entry:
663  *
664  *   Emit code for the PLT entry with index INDEX.
665  */
666 static void
667 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
668 {
669 #if defined(TARGET_X86)
670                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
671
672 #ifdef __native_client_codegen__
673                 const guint8 kSizeOfNaClJmp = 11;
674                 guint8 bytes[kSizeOfNaClJmp];
675                 guint8 *pbytes = &bytes[0];
676                 
677                 x86_jump_membase32 (pbytes, X86_EBX, offset);
678                 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
679                 /* four bytes of data, used by mono_arch_patch_plt_entry              */
680                 /* For Native Client, make this work with data embedded in push.      */
681                 emit_byte (acfg, 0x68);  /* hide data in a push */
682                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
683                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
684 #else
685                 /* jmp *<offset>(%ebx) */
686                 emit_byte (acfg, 0xff);
687                 emit_byte (acfg, 0xa3);
688                 emit_int32 (acfg, offset);
689                 /* Used by mono_aot_get_plt_info_offset */
690                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
691 #endif  /* __native_client_codegen__ */
692 #elif defined(TARGET_AMD64)
693                 /*
694                  * We can't emit jumps because they are 32 bits only so they can't be patched.
695                  * So we make indirect calls through GOT entries which are patched by the AOT 
696                  * loader to point to .Lpd entries. 
697                  */
698                 /* jmpq *<offset>(%rip) */
699                 emit_byte (acfg, '\xff');
700                 emit_byte (acfg, '\x25');
701                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
702                 /* Used by mono_aot_get_plt_info_offset */
703                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
704 #elif defined(TARGET_ARM)
705                 guint8 buf [256];
706                 guint8 *code;
707
708                 /* FIXME:
709                  * - optimize OP_AOTCONST implementation
710                  * - optimize the PLT entries
711                  * - optimize SWITCH AOT implementation
712                  */
713                 code = buf;
714                 if (acfg->use_bin_writer && FALSE) {
715                         /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
716                         /* We only emit 1 relocation since we implement it ourselves anyway */
717                         img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
718                         /* FIXME: A 2 instruction encoding is sufficient in most cases */
719                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
720                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
721                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
722                         emit_bytes (acfg, buf, code - buf);
723                         /* Used by mono_aot_get_plt_info_offset */
724                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
725                 } else {
726                         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
727                         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
728                         emit_bytes (acfg, buf, code - buf);
729                         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
730                         /* Used by mono_aot_get_plt_info_offset */
731                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
732                 }
733                 /* 
734                  * The plt_got_info_offset is computed automatically by 
735                  * mono_aot_get_plt_info_offset (), so no need to save it here.
736                  */
737 #elif defined(TARGET_POWERPC)
738                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
739
740                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
741                 g_assert (!acfg->use_bin_writer);
742                 img_writer_emit_unset_mode (acfg->w);
743                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
744                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
745                 fprintf (acfg->fp, "add 11, 11, 30\n");
746                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
747 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
748                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
749                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
750 #endif
751                 fprintf (acfg->fp, "mtctr 11\n");
752                 fprintf (acfg->fp, "bctr\n");
753                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
754 #else
755                 g_assert_not_reached ();
756 #endif
757 }
758
759 /*
760  * arch_emit_specific_trampoline:
761  *
762  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
763  * two GOT slots which contain the generic trampoline address and the trampoline
764  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
765  */
766 static void
767 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
768 {
769         /*
770          * The trampolines created here are variations of the specific 
771          * trampolines created in mono_arch_create_specific_trampoline (). The 
772          * differences are:
773          * - the generic trampoline address is taken from a got slot.
774          * - the offset of the got slot where the trampoline argument is stored
775          *   is embedded in the instruction stream, and the generic trampoline
776          *   can load the argument by loading the offset, adding it to the
777          *   address of the trampoline to get the address of the got slot, and
778          *   loading the argument from there.
779          * - all the trampolines should be of the same length.
780          */
781 #if defined(TARGET_AMD64)
782         /* This should be exactly 16 bytes long */
783         *tramp_size = 16;
784         /* call *<offset>(%rip) */
785         emit_byte (acfg, '\x41');
786         emit_byte (acfg, '\xff');
787         emit_byte (acfg, '\x15');
788         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
789         /* This should be relative to the start of the trampoline */
790         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
791         emit_zero_bytes (acfg, 5);
792 #elif defined(TARGET_ARM)
793         guint8 buf [128];
794         guint8 *code;
795
796         /* This should be exactly 20 bytes long */
797         *tramp_size = 20;
798         code = buf;
799         ARM_PUSH (code, 0x5fff);
800         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
801         /* Load the value from the GOT */
802         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
803         /* Branch to it */
804         ARM_BLX_REG (code, ARMREG_R1);
805
806         g_assert (code - buf == 16);
807
808         /* Emit it */
809         emit_bytes (acfg, buf, code - buf);
810         /* 
811          * Only one offset is needed, since the second one would be equal to the
812          * first one.
813          */
814         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
815         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
816 #elif defined(TARGET_POWERPC)
817         guint8 buf [128];
818         guint8 *code;
819
820         *tramp_size = 4;
821         code = buf;
822
823         g_assert (!acfg->use_bin_writer);
824
825         /*
826          * PPC has no ip relative addressing, so we need to compute the address
827          * of the mscorlib got. That is slow and complex, so instead, we store it
828          * in the second got slot of every aot image. The caller already computed
829          * the address of its got and placed it into r30.
830          */
831         img_writer_emit_unset_mode (acfg->w);
832         /* Load mscorlib got address */
833         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
834         /* Load generic trampoline address */
835         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
836         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
837         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
838 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
839         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
840 #endif
841         fprintf (acfg->fp, "mtctr 11\n");
842         /* Load trampoline argument */
843         /* On ppc, we pass it normally to the generic trampoline */
844         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
845         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
846         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
847         /* Branch to generic trampoline */
848         fprintf (acfg->fp, "bctr\n");
849
850 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
851         *tramp_size = 10 * 4;
852 #else
853         *tramp_size = 9 * 4;
854 #endif
855 #elif defined(TARGET_X86)
856         guint8 buf [128];
857         guint8 *code;
858
859         /* Similar to the PPC code above */
860
861         /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
862
863         /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
864 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
865         g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
866 #endif
867
868         code = buf;
869         /* Load mscorlib got address */
870         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
871         /* Push trampoline argument */
872         x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
873         /* Load generic trampoline address */
874         x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
875         /* Branch to generic trampoline */
876         x86_jump_reg (code, X86_ECX);
877
878 #ifdef __native_client_codegen__
879         {
880                 /* emit nops to next 32 byte alignment */
881                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
882                 while (code < (buf + a)) x86_nop(code);
883         }
884 #endif
885         emit_bytes (acfg, buf, code - buf);
886
887         *tramp_size = NACL_SIZE(17, kNaClAlignment);
888         g_assert (code - buf == *tramp_size);
889 #else
890         g_assert_not_reached ();
891 #endif
892 }
893
894 /*
895  * arch_emit_unbox_trampoline:
896  *
897  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
898  * CALL_TARGET is the symbol pointing to the native code of METHOD.
899  */
900 static void
901 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, const char *call_target)
902 {
903 #if defined(TARGET_AMD64)
904         guint8 buf [32];
905         guint8 *code;
906         int this_reg;
907
908         this_reg = mono_arch_get_this_arg_reg (NULL);
909         code = buf;
910         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
911
912         emit_bytes (acfg, buf, code - buf);
913         /* jump <method> */
914         emit_byte (acfg, '\xe9');
915         emit_symbol_diff (acfg, call_target, ".", -4);
916 #elif defined(TARGET_X86)
917         guint8 buf [32];
918         guint8 *code;
919         int this_pos = 4;
920
921         code = buf;
922
923         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
924
925         emit_bytes (acfg, buf, code - buf);
926
927         /* jump <method> */
928         emit_byte (acfg, '\xe9');
929         emit_symbol_diff (acfg, call_target, ".", -4);
930 #elif defined(TARGET_ARM)
931         guint8 buf [128];
932         guint8 *code;
933
934         code = buf;
935
936         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
937
938         emit_bytes (acfg, buf, code - buf);
939         /* jump to method */
940         if (acfg->use_bin_writer) {
941                 guint8 buf [4];
942                 guint8 *code;
943
944                 code = buf;
945                 ARM_B (code, 0);
946
947                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
948                 emit_bytes (acfg, buf, 4);
949         } else {
950                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
951         }
952 #elif defined(TARGET_POWERPC)
953         int this_pos = 3;
954
955         g_assert (!acfg->use_bin_writer);
956
957         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
958         fprintf (acfg->fp, "\n\tb %s\n", call_target);
959 #else
960         g_assert_not_reached ();
961 #endif
962 }
963
964 /*
965  * arch_emit_static_rgctx_trampoline:
966  *
967  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
968  * two GOT slots which contain the rgctx argument, and the method to jump to.
969  * TRAMP_SIZE is set to the size of the emitted trampoline.
970  * These kinds of trampolines cannot be enumerated statically, since there could
971  * be one trampoline per method instantiation, so we emit the same code for all
972  * trampolines, and parameterize them using two GOT slots.
973  */
974 static void
975 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
976 {
977 #if defined(TARGET_AMD64)
978         /* This should be exactly 13 bytes long */
979         *tramp_size = 13;
980
981         /* mov <OFFSET>(%rip), %r10 */
982         emit_byte (acfg, '\x4d');
983         emit_byte (acfg, '\x8b');
984         emit_byte (acfg, '\x15');
985         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
986
987         /* jmp *<offset>(%rip) */
988         emit_byte (acfg, '\xff');
989         emit_byte (acfg, '\x25');
990         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
991 #elif defined(TARGET_ARM)
992         guint8 buf [128];
993         guint8 *code;
994
995         /* This should be exactly 24 bytes long */
996         *tramp_size = 24;
997         code = buf;
998         /* Load rgctx value */
999         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1000         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1001         /* Load branch addr + branch */
1002         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1003         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1004
1005         g_assert (code - buf == 16);
1006
1007         /* Emit it */
1008         emit_bytes (acfg, buf, code - buf);
1009         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1010         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1011 #elif defined(TARGET_POWERPC)
1012         guint8 buf [128];
1013         guint8 *code;
1014
1015         *tramp_size = 4;
1016         code = buf;
1017
1018         g_assert (!acfg->use_bin_writer);
1019
1020         /*
1021          * PPC has no ip relative addressing, so we need to compute the address
1022          * of the mscorlib got. That is slow and complex, so instead, we store it
1023          * in the second got slot of every aot image. The caller already computed
1024          * the address of its got and placed it into r30.
1025          */
1026         img_writer_emit_unset_mode (acfg->w);
1027         /* Load mscorlib got address */
1028         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1029         /* Load rgctx */
1030         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1031         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1032         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1033         /* Load target address */
1034         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1035         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1036         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1037 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1038         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1039         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1040 #endif
1041         fprintf (acfg->fp, "mtctr 11\n");
1042         /* Branch to the target address */
1043         fprintf (acfg->fp, "bctr\n");
1044
1045 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1046         *tramp_size = 11 * 4;
1047 #else
1048         *tramp_size = 9 * 4;
1049 #endif
1050
1051 #elif defined(TARGET_X86)
1052         guint8 buf [128];
1053         guint8 *code;
1054
1055         /* Similar to the PPC code above */
1056
1057         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1058
1059         code = buf;
1060         /* Load mscorlib got address */
1061         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1062         /* Load arg */
1063         x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1064         /* Branch to the target address */
1065         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1066
1067 #ifdef __native_client_codegen__
1068         {
1069                 /* emit nops to next 32 byte alignment */
1070                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1071                 while (code < (buf + a)) x86_nop(code);
1072         }
1073 #endif
1074
1075         emit_bytes (acfg, buf, code - buf);
1076
1077         *tramp_size = NACL_SIZE (15, kNaClAlignment);
1078         g_assert (code - buf == *tramp_size);
1079 #else
1080         g_assert_not_reached ();
1081 #endif
1082 }       
1083
1084 /*
1085  * arch_emit_imt_thunk:
1086  *
1087  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1088  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1089  * key is the IMT key, and ptr holds the address of a memory location holding
1090  * the address to branch to if the IMT arg matches the key. The array is 
1091  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
1092  * fail_tramp.
1093  * TRAMP_SIZE is set to the size of the emitted trampoline.
1094  */
1095 static void
1096 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1097 {
1098 #if defined(TARGET_AMD64)
1099         guint8 *buf, *code;
1100         guint8 *labels [3];
1101
1102         code = buf = g_malloc (256);
1103
1104         /* FIXME: Optimize this, i.e. use binary search etc. */
1105         /* Maybe move the body into a separate function (slower, but much smaller) */
1106
1107         /* R11 is a free register */
1108
1109         labels [0] = code;
1110         amd64_alu_membase_imm (code, X86_CMP, AMD64_R11, 0, 0);
1111         labels [1] = code;
1112         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1113
1114         /* Check key */
1115         amd64_alu_membase_reg (code, X86_CMP, AMD64_R11, 0, MONO_ARCH_IMT_REG);
1116         labels [2] = code;
1117         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1118
1119         /* Loop footer */
1120         amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, 2 * sizeof (gpointer));
1121         amd64_jump_code (code, labels [0]);
1122
1123         /* Match */
1124         mono_amd64_patch (labels [2], code);
1125         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, sizeof (gpointer), 8);
1126         amd64_jump_membase (code, AMD64_R11, 0);
1127
1128         /* No match */
1129         /* FIXME: */
1130         mono_amd64_patch (labels [1], code);
1131         x86_breakpoint (code);
1132
1133         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 12345678, 8);
1134
1135         /* mov <OFFSET>(%rip), %r11 */
1136         emit_byte (acfg, '\x4d');
1137         emit_byte (acfg, '\x8b');
1138         emit_byte (acfg, '\x1d');
1139         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1140
1141         emit_bytes (acfg, buf, code - buf);
1142         
1143         *tramp_size = code - buf + 7;
1144 #elif defined(TARGET_X86)
1145         guint8 *buf, *code;
1146 #ifdef __native_client_codegen__
1147         guint8 *buf_alloc;
1148 #endif
1149         guint8 *labels [3];
1150
1151 #ifdef __native_client_codegen__
1152         buf_alloc = g_malloc (256 + kNaClAlignment);
1153         code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1154 #else
1155         code = buf = g_malloc (256);
1156 #endif
1157
1158         /* Allocate a temporary stack slot */
1159         x86_push_reg (code, X86_EAX);
1160         /* Save EAX */
1161         x86_push_reg (code, X86_EAX);
1162
1163         /* Load mscorlib got address */
1164         x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1165         /* Load arg */
1166         x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1167
1168         labels [0] = code;
1169         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1170         labels [1] = code;
1171         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1172
1173         /* Check key */
1174         x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1175         labels [2] = code;
1176         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1177
1178         /* Loop footer */
1179         x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1180         x86_jump_code (code, labels [0]);
1181
1182         /* Match */
1183         mono_x86_patch (labels [2], code);
1184         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1185         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1186         /* Save the target address to the temporary stack location */
1187         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1188         /* Restore EAX */
1189         x86_pop_reg (code, X86_EAX);
1190         /* Jump to the target address */
1191         x86_ret (code);
1192
1193         /* No match */
1194         /* FIXME: */
1195         mono_x86_patch (labels [1], code);
1196         x86_breakpoint (code);
1197
1198 #ifdef __native_client_codegen__
1199         {
1200                 /* emit nops to next 32 byte alignment */
1201                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1202                 while (code < (buf + a)) x86_nop(code);
1203         }
1204 #endif
1205         emit_bytes (acfg, buf, code - buf);
1206         
1207         *tramp_size = code - buf;
1208 #elif defined(TARGET_ARM)
1209         guint8 buf [128];
1210         guint8 *code, *code2, *labels [16];
1211
1212         code = buf;
1213
1214         /* The IMT method is in v5 */
1215
1216         /* Need at least two free registers, plus a slot for storing the pc */
1217         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1218         labels [0] = code;
1219         /* Load the parameter from the GOT */
1220         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1221         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1222
1223         labels [1] = code;
1224         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1225         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1226         labels [2] = code;
1227         ARM_B_COND (code, ARMCOND_EQ, 0);
1228
1229         /* End-of-loop check */
1230         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1231         labels [3] = code;
1232         ARM_B_COND (code, ARMCOND_EQ, 0);
1233
1234         /* Loop footer */
1235         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1236         labels [4] = code;
1237         ARM_B (code, 0);
1238         arm_patch (labels [4], labels [1]);
1239
1240         /* Match */
1241         arm_patch (labels [2], code);
1242         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1243         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1244         /* Save it to the third stack slot */
1245         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1246         /* Restore the registers and branch */
1247         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1248
1249         /* No match */
1250         arm_patch (labels [3], code);
1251         ARM_DBRK (code);
1252
1253         /* Fixup offset */
1254         code2 = labels [0];
1255         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1256
1257         emit_bytes (acfg, buf, code - buf);
1258         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1259
1260         *tramp_size = code - buf + 4;
1261 #elif defined(TARGET_POWERPC)
1262         guint8 buf [128];
1263         guint8 *code, *labels [16];
1264
1265         code = buf;
1266
1267         /* Load the mscorlib got address */
1268         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1269         /* Load the parameter from the GOT */
1270         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1271         ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1272
1273         /* Load and check key */
1274         labels [1] = code;
1275         ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1276         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1277         labels [2] = code;
1278         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1279
1280         /* End-of-loop check */
1281         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1282         labels [3] = code;
1283         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1284
1285         /* Loop footer */
1286         ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1287         labels [4] = code;
1288         ppc_b (code, 0);
1289         mono_ppc_patch (labels [4], labels [1]);
1290
1291         /* Match */
1292         mono_ppc_patch (labels [2], code);
1293         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1294         /* r11 now contains the value of the vtable slot */
1295         /* this is not a function descriptor on ppc64 */
1296         ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1297         ppc_mtctr (code, ppc_r11);
1298         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1299
1300         /* Fail */
1301         mono_ppc_patch (labels [3], code);
1302         /* FIXME: */
1303         ppc_break (code);
1304
1305         *tramp_size = code - buf;
1306
1307         emit_bytes (acfg, buf, code - buf);
1308 #else
1309         g_assert_not_reached ();
1310 #endif
1311 }
1312
1313 static void
1314 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1315 {
1316 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1317         /* Based on code generated by gcc */
1318         img_writer_emit_unset_mode (acfg->w);
1319
1320         fprintf (acfg->fp,
1321 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
1322                          ".section      .ctors,\"aw\",@progbits\n"
1323                          ".align 2\n"
1324                          ".globl        %s\n"
1325                          ".long %s\n"
1326                          ".section      .opd,\"aw\"\n"
1327                          ".align 2\n"
1328                          "%s:\n"
1329                          ".long .%s,.TOC.@tocbase32\n"
1330                          ".size %s,.-%s\n"
1331                          ".section .text\n"
1332                          ".type .%s,@function\n"
1333                          ".align 2\n"
1334                          ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1335 #else
1336                          ".section      .ctors,\"aw\",@progbits\n"
1337                          ".align 2\n"
1338                          ".globl        %1$s\n"
1339                          ".long %1$s\n"
1340                          ".section      .opd,\"aw\"\n"
1341                          ".align 2\n"
1342                          "%1$s:\n"
1343                          ".long .%1$s,.TOC.@tocbase32\n"
1344                          ".size %1$s,.-%1$s\n"
1345                          ".section .text\n"
1346                          ".type .%1$s,@function\n"
1347                          ".align 2\n"
1348                          ".%1$s:\n", symbol);
1349 #endif
1350
1351
1352         fprintf (acfg->fp,
1353                          "stdu 1,-128(1)\n"
1354                          "mflr 0\n"
1355                          "std 31,120(1)\n"
1356                          "std 0,144(1)\n"
1357
1358                          ".Lautoreg:\n"
1359                          "lis 3, .Lglobals@h\n"
1360                          "ori 3, 3, .Lglobals@l\n"
1361                          "bl .mono_aot_register_module\n"
1362                          "ld 11,0(1)\n"
1363                          "ld 0,16(11)\n"
1364                          "mtlr 0\n"
1365                          "ld 31,-8(11)\n"
1366                          "mr 1,11\n"
1367                          "blr\n"
1368                          );
1369 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
1370                 fprintf (acfg->fp,
1371                          ".size .%s,.-.%s\n", symbol, symbol);
1372 #else
1373         fprintf (acfg->fp,
1374                          ".size .%1$s,.-.%1$s\n", symbol);
1375 #endif
1376 #else
1377 #endif
1378 }
1379
1380 /* END OF ARCH SPECIFIC CODE */
1381
1382 static guint32
1383 mono_get_field_token (MonoClassField *field) 
1384 {
1385         MonoClass *klass = field->parent;
1386         int i;
1387
1388         for (i = 0; i < klass->field.count; ++i) {
1389                 if (field == &klass->fields [i])
1390                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1391         }
1392
1393         g_assert_not_reached ();
1394         return 0;
1395 }
1396
1397 static inline void
1398 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1399 {
1400         guint8 *p = buf;
1401
1402         //printf ("ENCODE: %d 0x%x.\n", value, value);
1403
1404         /* 
1405          * Same encoding as the one used in the metadata, extended to handle values
1406          * greater than 0x1fffffff.
1407          */
1408         if ((value >= 0) && (value <= 127))
1409                 *p++ = value;
1410         else if ((value >= 0) && (value <= 16383)) {
1411                 p [0] = 0x80 | (value >> 8);
1412                 p [1] = value & 0xff;
1413                 p += 2;
1414         } else if ((value >= 0) && (value <= 0x1fffffff)) {
1415                 p [0] = (value >> 24) | 0xc0;
1416                 p [1] = (value >> 16) & 0xff;
1417                 p [2] = (value >> 8) & 0xff;
1418                 p [3] = value & 0xff;
1419                 p += 4;
1420         }
1421         else {
1422                 p [0] = 0xff;
1423                 p [1] = (value >> 24) & 0xff;
1424                 p [2] = (value >> 16) & 0xff;
1425                 p [3] = (value >> 8) & 0xff;
1426                 p [4] = value & 0xff;
1427                 p += 5;
1428         }
1429         if (endbuf)
1430                 *endbuf = p;
1431 }
1432
1433 static void
1434 stream_init (MonoDynamicStream *sh)
1435 {
1436         sh->index = 0;
1437         sh->alloc_size = 4096;
1438         sh->data = g_malloc (4096);
1439
1440         /* So offsets are > 0 */
1441         sh->index ++;
1442 }
1443
1444 static void
1445 make_room_in_stream (MonoDynamicStream *stream, int size)
1446 {
1447         if (size <= stream->alloc_size)
1448                 return;
1449         
1450         while (stream->alloc_size <= size) {
1451                 if (stream->alloc_size < 4096)
1452                         stream->alloc_size = 4096;
1453                 else
1454                         stream->alloc_size *= 2;
1455         }
1456         
1457         stream->data = g_realloc (stream->data, stream->alloc_size);
1458 }
1459
1460 static guint32
1461 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1462 {
1463         guint32 idx;
1464         
1465         make_room_in_stream (stream, stream->index + len);
1466         memcpy (stream->data + stream->index, data, len);
1467         idx = stream->index;
1468         stream->index += len;
1469         return idx;
1470 }
1471
1472 /*
1473  * add_to_blob:
1474  *
1475  *   Add data to the binary blob inside the aot image. Returns the offset inside the
1476  * blob where the data was stored.
1477  */
1478 static guint32
1479 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1480 {
1481         if (acfg->blob.alloc_size == 0)
1482                 stream_init (&acfg->blob);
1483
1484         return add_stream_data (&acfg->blob, (char*)data, data_len);
1485 }
1486
1487 /*
1488  * emit_offset_table:
1489  *
1490  *   Emit a table of increasing offsets in a compact form using differential encoding.
1491  * There is an index entry for each GROUP_SIZE number of entries. The greater the
1492  * group size, the more compact the table becomes, but the slower it becomes to compute
1493  * a given entry. Returns the size of the table.
1494  */
1495 static guint32
1496 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1497 {
1498         gint32 current_offset;
1499         int i, buf_size, ngroups, index_entry_size;
1500         guint8 *p, *buf;
1501         guint32 *index_offsets;
1502
1503         ngroups = (noffsets + (group_size - 1)) / group_size;
1504
1505         index_offsets = g_new0 (guint32, ngroups);
1506
1507         buf_size = noffsets * 4;
1508         p = buf = g_malloc0 (buf_size);
1509
1510         current_offset = 0;
1511         for (i = 0; i < noffsets; ++i) {
1512                 //printf ("D: %d -> %d\n", i, offsets [i]);
1513                 if ((i % group_size) == 0) {
1514                         index_offsets [i / group_size] = p - buf;
1515                         /* Emit the full value for these entries */
1516                         encode_value (offsets [i], p, &p);
1517                 } else {
1518                         /* The offsets are allowed to be non-increasing */
1519                         //g_assert (offsets [i] >= current_offset);
1520                         encode_value (offsets [i] - current_offset, p, &p);
1521                 }
1522                 current_offset = offsets [i];
1523         }
1524
1525         if (ngroups && index_offsets [ngroups - 1] < 65000)
1526                 index_entry_size = 2;
1527         else
1528                 index_entry_size = 4;
1529
1530         /* Emit the header */
1531         emit_int32 (acfg, noffsets);
1532         emit_int32 (acfg, group_size);
1533         emit_int32 (acfg, ngroups);
1534         emit_int32 (acfg, index_entry_size);
1535
1536         /* Emit the index */
1537         for (i = 0; i < ngroups; ++i) {
1538                 if (index_entry_size == 2)
1539                         emit_int16 (acfg, index_offsets [i]);
1540                 else
1541                         emit_int32 (acfg, index_offsets [i]);
1542         }
1543
1544         /* Emit the data */
1545         emit_bytes (acfg, buf, p - buf);
1546
1547     return (int)(p - buf) + (ngroups * 4);
1548 }
1549
1550 static guint32
1551 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1552 {
1553         guint32 index;
1554
1555         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1556         if (index)
1557                 return index - 1;
1558         else {
1559                 index = g_hash_table_size (cfg->image_hash);
1560                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1561                 g_ptr_array_add (cfg->image_table, image);
1562                 return index;
1563         }
1564 }
1565
1566 static guint32
1567 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1568 {
1569         int i;
1570         int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1571
1572         /* FIXME: Search referenced images as well */
1573         if (!acfg->typespec_classes) {
1574                 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1575                 for (i = 0; i < len; ++i) {
1576                         acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1577                 }
1578         }
1579         for (i = 0; i < len; ++i) {
1580                 if (acfg->typespec_classes [i] == klass)
1581                         break;
1582         }
1583
1584         if (i < len)
1585                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1586         else
1587                 return 0;
1588 }
1589
1590 static void
1591 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1592
1593 /*
1594  * encode_klass_ref:
1595  *
1596  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
1597  * standard metadata encoding.
1598  */
1599 static void
1600 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1601 {
1602         guint8 *p = buf;
1603
1604         if (klass->generic_class) {
1605                 guint32 token;
1606                 g_assert (klass->type_token);
1607
1608                 /* Find a typespec for a class if possible */
1609                 token = find_typespec_for_class (acfg, klass);
1610                 if (token) {
1611                         encode_value (token, p, &p);
1612                         encode_value (get_image_index (acfg, acfg->image), p, &p);
1613                 } else {
1614                         MonoClass *gclass = klass->generic_class->container_class;
1615                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
1616                         int i;
1617
1618                         /* Encode it ourselves */
1619                         /* Marker */
1620                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1621                         encode_value (MONO_TYPE_GENERICINST, p, &p);
1622                         encode_klass_ref (acfg, gclass, p, &p);
1623                         encode_value (inst->type_argc, p, &p);
1624                         for (i = 0; i < inst->type_argc; ++i)
1625                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1626                 }
1627         } else if (klass->type_token) {
1628                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1629                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1630                 encode_value (get_image_index (acfg, klass->image), p, &p);
1631         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1632                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1633                 g_assert (container);
1634
1635                 /* Marker */
1636                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1637                 encode_value (klass->byval_arg.type, p, &p);
1638
1639                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1640                 
1641                 encode_value (container->is_method, p, &p);
1642                 if (container->is_method)
1643                         encode_method_ref (acfg, container->owner.method, p, &p);
1644                 else
1645                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1646         } else {
1647                 /* Array class */
1648                 g_assert (klass->rank > 0);
1649                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1650                 encode_value (get_image_index (acfg, klass->image), p, &p);
1651                 encode_value (klass->rank, p, &p);
1652                 encode_klass_ref (acfg, klass->element_class, p, &p);
1653         }
1654         *endbuf = p;
1655 }
1656
1657 static void
1658 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1659 {
1660         guint32 token = mono_get_field_token (field);
1661         guint8 *p = buf;
1662
1663         encode_klass_ref (cfg, field->parent, p, &p);
1664         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1665         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1666         *endbuf = p;
1667 }
1668
1669 static void
1670 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1671 {
1672         guint8 *p = buf;
1673         int i;
1674         MonoGenericInst *inst;
1675
1676         /* Encode the context */
1677         inst = context->class_inst;
1678         encode_value (inst ? 1 : 0, p, &p);
1679         if (inst) {
1680                 encode_value (inst->type_argc, p, &p);
1681                 for (i = 0; i < inst->type_argc; ++i)
1682                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1683         }
1684         inst = context->method_inst;
1685         encode_value (inst ? 1 : 0, p, &p);
1686         if (inst) {
1687                 encode_value (inst->type_argc, p, &p);
1688                 for (i = 0; i < inst->type_argc; ++i)
1689                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1690         }
1691
1692         *endbuf = p;
1693 }
1694
1695 #define MAX_IMAGE_INDEX 250
1696
1697 static void
1698 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1699 {
1700         guint32 image_index = get_image_index (acfg, method->klass->image);
1701         guint32 token = method->token;
1702         MonoJumpInfoToken *ji;
1703         guint8 *p = buf;
1704         char *name;
1705
1706         /*
1707          * The encoding for most methods is as follows:
1708          * - image index encoded as a leb128
1709          * - token index encoded as a leb128
1710          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1711          * types of method encodings.
1712          */
1713
1714         g_assert (image_index < MONO_AOT_METHODREF_MIN);
1715
1716         /* Mark methods which can't use aot trampolines because they need the further 
1717          * processing in mono_magic_trampoline () which requires a MonoMethod*.
1718          */
1719         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1720                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1721                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1722
1723         /* 
1724          * Some wrapper methods are shared using their signature, encode their 
1725          * stringified signature instead.
1726          * FIXME: Optimize disk usage
1727          */
1728         name = NULL;
1729         if (method->wrapper_type) {
1730                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1731                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1732                         if (strcmp (method->name, "runtime_invoke_dynamic")) {
1733                                 name = mono_aot_wrapper_name (method);
1734                         } else if (mono_marshal_method_from_wrapper (method) != method) {
1735                                 /* Direct wrapper, encode it normally */
1736                         } else {
1737                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1738                         }
1739                         g_free (tmpsig);
1740                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1741                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1742                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1743                         g_free (tmpsig);
1744                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1745                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1746                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1747                         g_free (tmpsig);
1748                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1749                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1750                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1751                         g_free (tmpsig);
1752                 }
1753         }
1754
1755         if (name) {
1756                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1757                 strcpy ((char*)p, name);
1758                 p += strlen (name) + 1;
1759                 g_free (name);
1760         } else if (method->wrapper_type) {
1761                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1762
1763                 encode_value (method->wrapper_type, p, &p);
1764
1765                 switch (method->wrapper_type) {
1766                 case MONO_WRAPPER_REMOTING_INVOKE:
1767                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1768                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1769                         MonoMethod *m;
1770
1771                         m = mono_marshal_method_from_wrapper (method);
1772                         g_assert (m);
1773                         encode_method_ref (acfg, m, p, &p);
1774                         break;
1775                 }
1776                 case MONO_WRAPPER_PROXY_ISINST:
1777                 case MONO_WRAPPER_LDFLD:
1778                 case MONO_WRAPPER_LDFLDA:
1779                 case MONO_WRAPPER_STFLD:
1780                 case MONO_WRAPPER_ISINST: {
1781                         MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1782                         encode_klass_ref (acfg, proxy_class, p, &p);
1783                         break;
1784                 }
1785                 case MONO_WRAPPER_LDFLD_REMOTE:
1786                 case MONO_WRAPPER_STFLD_REMOTE:
1787                         break;
1788                 case MONO_WRAPPER_ALLOC: {
1789                         AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1790
1791                         /* The GC name is saved once in MonoAotFileInfo */
1792                         g_assert (info->alloc_type != -1);
1793                         encode_value (info->alloc_type, p, &p);
1794                         break;
1795                 }
1796                 case MONO_WRAPPER_WRITE_BARRIER:
1797                         break;
1798                 case MONO_WRAPPER_STELEMREF: {
1799                         MonoClass *klass = mono_marshal_get_wrapper_info (method);
1800
1801                         /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
1802                         g_assert (!klass);
1803                         break;
1804                 }
1805                 case MONO_WRAPPER_UNKNOWN:
1806                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1807                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1808                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1809                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1810                         else
1811                                 g_assert_not_reached ();
1812                         break;
1813                 case MONO_WRAPPER_SYNCHRONIZED:
1814                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1815                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1816                         MonoMethod *m;
1817
1818                         m = mono_marshal_method_from_wrapper (method);
1819                         g_assert (m);
1820                         g_assert (m != method);
1821                         encode_method_ref (acfg, m, p, &p);
1822                         break;
1823                 }
1824                 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1825                         if (!strcmp (method->name, "ElementAddr")) {
1826                                 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1827
1828                                 g_assert (info);
1829                                 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1830                                 encode_value (info->rank, p, &p);
1831                                 encode_value (info->elem_size, p, &p);
1832                         } else {
1833                                 g_assert_not_reached ();
1834                         }
1835                         break;
1836                 default:
1837                         g_assert_not_reached ();
1838                 }
1839         } else if (mono_method_signature (method)->is_inflated) {
1840                 /* 
1841                  * This is a generic method, find the original token which referenced it and
1842                  * encode that.
1843                  * Obtain the token from information recorded by the JIT.
1844                  */
1845                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1846                 if (ji) {
1847                         image_index = get_image_index (acfg, ji->image);
1848                         g_assert (image_index < MAX_IMAGE_INDEX);
1849                         token = ji->token;
1850
1851                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1852                         encode_value (image_index, p, &p);
1853                         encode_value (token, p, &p);
1854                 } else {
1855                         MonoMethod *declaring;
1856                         MonoGenericContext *context = mono_method_get_context (method);
1857
1858                         g_assert (method->is_inflated);
1859                         declaring = ((MonoMethodInflated*)method)->declaring;
1860
1861                         /*
1862                          * This might be a non-generic method of a generic instance, which 
1863                          * doesn't have a token since the reference is generated by the JIT 
1864                          * like Nullable:Box/Unbox, or by generic sharing.
1865                          */
1866
1867                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1868                         /* Encode the klass */
1869                         encode_klass_ref (acfg, method->klass, p, &p);
1870                         /* Encode the method */
1871                         image_index = get_image_index (acfg, method->klass->image);
1872                         g_assert (image_index < MAX_IMAGE_INDEX);
1873                         g_assert (declaring->token);
1874                         token = declaring->token;
1875                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1876                         encode_value (image_index, p, &p);
1877                         encode_value (token, p, &p);
1878                         encode_generic_context (acfg, context, p, &p);
1879                 }
1880         } else if (token == 0) {
1881                 /* This might be a method of a constructed type like int[,].Set */
1882                 /* Obtain the token from information recorded by the JIT */
1883                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1884                 if (ji) {
1885                         image_index = get_image_index (acfg, ji->image);
1886                         g_assert (image_index < MAX_IMAGE_INDEX);
1887                         token = ji->token;
1888
1889                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1890                         encode_value (image_index, p, &p);
1891                         encode_value (token, p, &p);
1892                 } else {
1893                         /* Array methods */
1894                         g_assert (method->klass->rank);
1895
1896                         /* Encode directly */
1897                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1898                         encode_klass_ref (acfg, method->klass, p, &p);
1899                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1900                                 encode_value (0, p, &p);
1901                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1902                                 encode_value (1, p, &p);
1903                         else if (!strcmp (method->name, "Get"))
1904                                 encode_value (2, p, &p);
1905                         else if (!strcmp (method->name, "Address"))
1906                                 encode_value (3, p, &p);
1907                         else if (!strcmp (method->name, "Set"))
1908                                 encode_value (4, p, &p);
1909                         else
1910                                 g_assert_not_reached ();
1911                 }
1912         } else {
1913                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1914                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1915         }
1916         *endbuf = p;
1917 }
1918
1919 static gint
1920 compare_patches (gconstpointer a, gconstpointer b)
1921 {
1922         int i, j;
1923
1924         i = (*(MonoJumpInfo**)a)->ip.i;
1925         j = (*(MonoJumpInfo**)b)->ip.i;
1926
1927         if (i < j)
1928                 return -1;
1929         else
1930                 if (i > j)
1931                         return 1;
1932         else
1933                 return 0;
1934 }
1935
1936 static G_GNUC_UNUSED char*
1937 patch_to_string (MonoJumpInfo *patch_info)
1938 {
1939         GString *str;
1940
1941         str = g_string_new ("");
1942
1943         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
1944
1945         switch (patch_info->type) {
1946         case MONO_PATCH_INFO_VTABLE:
1947                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
1948                 break;
1949         default:
1950                 break;
1951         }
1952         g_string_append_printf (str, ")");
1953         return g_string_free (str, FALSE);
1954 }
1955
1956 /*
1957  * is_plt_patch:
1958  *
1959  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1960  * PLT entry.
1961  */
1962 static inline gboolean
1963 is_plt_patch (MonoJumpInfo *patch_info)
1964 {
1965         switch (patch_info->type) {
1966         case MONO_PATCH_INFO_METHOD:
1967         case MONO_PATCH_INFO_INTERNAL_METHOD:
1968         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1969         case MONO_PATCH_INFO_ICALL_ADDR:
1970         case MONO_PATCH_INFO_CLASS_INIT:
1971         case MONO_PATCH_INFO_RGCTX_FETCH:
1972         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1973         case MONO_PATCH_INFO_MONITOR_ENTER:
1974         case MONO_PATCH_INFO_MONITOR_EXIT:
1975         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1976                 return TRUE;
1977         default:
1978                 return FALSE;
1979         }
1980 }
1981
1982 /*
1983  * get_plt_symbol:
1984  *
1985  *   Return the symbol identifying the plt entry PLT_OFFSET.
1986  */
1987 static char*
1988 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
1989 {
1990 #ifdef __MACH__
1991         /* 
1992          * The Apple linker reorganizes object files, so it doesn't like branches to local
1993          * labels, since those have no relocations.
1994          */
1995         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
1996 #else
1997         return g_strdup_printf ("%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
1998 #endif
1999 }
2000
2001 /*
2002  * get_plt_entry:
2003  *
2004  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2005  */
2006 static MonoPltEntry*
2007 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2008 {
2009         MonoPltEntry *res;
2010
2011         if (!is_plt_patch (patch_info))
2012                 return NULL;
2013
2014         res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2015
2016         // FIXME: This breaks the calculation of final_got_size         
2017         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2018                 /* 
2019                  * Allocate a separate PLT slot for each such patch, since some plt
2020                  * entries will refer to the method itself, and some will refer to the
2021                  * wrapper.
2022                  */
2023                 res = NULL;
2024         }
2025
2026         if (!res) {
2027                 MonoJumpInfo *new_ji;
2028
2029                 g_assert (!acfg->final_got_size);
2030
2031                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2032
2033                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2034                 res->plt_offset = acfg->plt_offset;
2035                 res->ji = new_ji;
2036                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2037
2038                 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2039
2040                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2041
2042                 acfg->plt_offset ++;
2043         }
2044
2045         return res;
2046 }
2047
2048 /**
2049  * get_got_offset:
2050  *
2051  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
2052  * JI could be found if it exists, otherwise allocates a new one.
2053  */
2054 static guint32
2055 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2056 {
2057         guint32 got_offset;
2058
2059         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2060         if (got_offset)
2061                 return got_offset - 1;
2062
2063         got_offset = acfg->got_offset;
2064         acfg->got_offset ++;
2065
2066         if (acfg->final_got_size)
2067                 g_assert (got_offset < acfg->final_got_size);
2068
2069         acfg->stats.got_slots ++;
2070         acfg->stats.got_slot_types [ji->type] ++;
2071
2072         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2073         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2074         g_ptr_array_add (acfg->got_patches, ji);
2075
2076         return got_offset;
2077 }
2078
2079 /* Add a method to the list of methods which need to be emitted */
2080 static void
2081 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2082 {
2083         g_assert (method);
2084         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2085                 g_ptr_array_add (acfg->methods, method);
2086                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2087                 acfg->nmethods = acfg->methods->len + 1;
2088         }
2089
2090         if (method->wrapper_type || extra)
2091                 g_ptr_array_add (acfg->extra_methods, method);
2092 }
2093
2094 static guint32
2095 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2096 {
2097         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2098         
2099         g_assert (index);
2100
2101         return index - 1;
2102 }
2103
2104 static int
2105 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2106 {
2107         int index;
2108
2109         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2110         if (index)
2111                 return index - 1;
2112
2113         index = acfg->method_index;
2114         add_method_with_index (acfg, method, index, extra);
2115
2116         /* FIXME: Fix quadratic behavior */
2117         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2118
2119         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2120
2121         acfg->method_index ++;
2122
2123         return index;
2124 }
2125
2126 static int
2127 add_method (MonoAotCompile *acfg, MonoMethod *method)
2128 {
2129         return add_method_full (acfg, method, FALSE, 0);
2130 }
2131
2132 static void
2133 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2134 {
2135         add_method_full (acfg, method, TRUE, 0);
2136 }
2137
2138 static void
2139 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2140 {
2141         add_method_full (acfg, method, TRUE, depth);
2142 }
2143
2144 static void
2145 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2146 {
2147         MonoAotCompile *acfg = user_data;
2148         MonoJitICallInfo *callinfo = value;
2149         MonoMethod *wrapper;
2150         char *name;
2151
2152         if (!callinfo->sig)
2153                 return;
2154
2155         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2156         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2157         g_free (name);
2158
2159         add_method (acfg, wrapper);
2160 }
2161
2162 static MonoMethod*
2163 get_runtime_invoke_sig (MonoMethodSignature *sig)
2164 {
2165         MonoMethodBuilder *mb;
2166         MonoMethod *m;
2167
2168         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2169         m = mono_mb_create_method (mb, sig, 16);
2170         return mono_marshal_get_runtime_invoke (m, FALSE);
2171 }
2172
2173 static gboolean
2174 can_marshal_struct (MonoClass *klass)
2175 {
2176         MonoClassField *field;
2177         gboolean can_marshal = TRUE;
2178         gpointer iter = NULL;
2179
2180         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2181                 return FALSE;
2182
2183         /* Only allow a few field types to avoid asserts in the marshalling code */
2184         while ((field = mono_class_get_fields (klass, &iter))) {
2185                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2186                         continue;
2187
2188                 switch (field->type->type) {
2189                 case MONO_TYPE_I4:
2190                 case MONO_TYPE_U4:
2191                 case MONO_TYPE_I1:
2192                 case MONO_TYPE_U1:
2193                 case MONO_TYPE_BOOLEAN:
2194                 case MONO_TYPE_I2:
2195                 case MONO_TYPE_U2:
2196                 case MONO_TYPE_CHAR:
2197                 case MONO_TYPE_I8:
2198                 case MONO_TYPE_U8:
2199                 case MONO_TYPE_I:
2200                 case MONO_TYPE_U:
2201                 case MONO_TYPE_PTR:
2202                 case MONO_TYPE_R4:
2203                 case MONO_TYPE_R8:
2204                 case MONO_TYPE_STRING:
2205                         break;
2206                 case MONO_TYPE_VALUETYPE:
2207                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2208                                 can_marshal = FALSE;
2209                         break;
2210                 default:
2211                         can_marshal = FALSE;
2212                         break;
2213                 }
2214         }
2215
2216         /* Special cases */
2217         /* Its hard to compute whenever these can be marshalled or not */
2218         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2219                 return TRUE;
2220
2221         return can_marshal;
2222 }
2223
2224 static void
2225 add_wrappers (MonoAotCompile *acfg)
2226 {
2227         MonoMethod *method, *m;
2228         int i, j;
2229         MonoMethodSignature *sig, *csig;
2230         guint32 token;
2231
2232         /* 
2233          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2234          * so there is only one wrapper of a given type, or inlining their contents into their
2235          * callers.
2236          */
2237
2238         /* 
2239          * FIXME: This depends on the fact that different wrappers have different 
2240          * names.
2241          */
2242
2243         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2244                 MonoMethod *method;
2245                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2246                 gboolean skip = FALSE;
2247
2248                 method = mono_get_method (acfg->image, token, NULL);
2249
2250                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2251                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2252                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2253                         skip = TRUE;
2254
2255                 if (method->is_generic || method->klass->generic_container)
2256                         skip = TRUE;
2257
2258                 /* Skip methods which can not be handled by get_runtime_invoke () */
2259                 sig = mono_method_signature (method);
2260                 if ((sig->ret->type == MONO_TYPE_PTR) ||
2261                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2262                         skip = TRUE;
2263
2264                 for (j = 0; j < sig->param_count; j++) {
2265                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2266                                 skip = TRUE;
2267                 }
2268
2269 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2270                 if (!method->klass->contextbound) {
2271                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2272                         gboolean has_nullable = FALSE;
2273
2274                         for (j = 0; j < sig->param_count; j++) {
2275                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2276                                         has_nullable = TRUE;
2277                         }
2278
2279                         if (info && !has_nullable) {
2280                                 /* Supported by the dynamic runtime-invoke wrapper */
2281                                 skip = TRUE;
2282                                 g_free (info);
2283                         }
2284                 }
2285 #endif
2286
2287                 if (!skip) {
2288                         //printf ("%s\n", mono_method_full_name (method, TRUE));
2289                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2290                 }
2291         }
2292
2293         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2294 #ifdef MONO_ARCH_HAVE_TLS_GET
2295                 MonoMethodDesc *desc;
2296                 MonoMethod *orig_method;
2297                 int nallocators;
2298 #endif
2299
2300                 /* Runtime invoke wrappers */
2301
2302                 /* void runtime-invoke () [.cctor] */
2303                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2304                 csig->ret = &mono_defaults.void_class->byval_arg;
2305                 add_method (acfg, get_runtime_invoke_sig (csig));
2306
2307                 /* void runtime-invoke () [Finalize] */
2308                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2309                 csig->hasthis = 1;
2310                 csig->ret = &mono_defaults.void_class->byval_arg;
2311                 add_method (acfg, get_runtime_invoke_sig (csig));
2312
2313                 /* void runtime-invoke (string) [exception ctor] */
2314                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2315                 csig->hasthis = 1;
2316                 csig->ret = &mono_defaults.void_class->byval_arg;
2317                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2318                 add_method (acfg, get_runtime_invoke_sig (csig));
2319
2320                 /* void runtime-invoke (string, string) [exception ctor] */
2321                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2322                 csig->hasthis = 1;
2323                 csig->ret = &mono_defaults.void_class->byval_arg;
2324                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2325                 csig->params [1] = &mono_defaults.string_class->byval_arg;
2326                 add_method (acfg, get_runtime_invoke_sig (csig));
2327
2328                 /* string runtime-invoke () [Exception.ToString ()] */
2329                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2330                 csig->hasthis = 1;
2331                 csig->ret = &mono_defaults.string_class->byval_arg;
2332                 add_method (acfg, get_runtime_invoke_sig (csig));
2333
2334                 /* void runtime-invoke (string, Exception) [exception ctor] */
2335                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2336                 csig->hasthis = 1;
2337                 csig->ret = &mono_defaults.void_class->byval_arg;
2338                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2339                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2340                 add_method (acfg, get_runtime_invoke_sig (csig));
2341
2342                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2343                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2344                 csig->hasthis = 1;
2345                 csig->ret = &(mono_class_from_name (
2346                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2347                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2348                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2349                 add_method (acfg, get_runtime_invoke_sig (csig));
2350
2351                 /* runtime-invoke used by finalizers */
2352                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2353
2354                 /* This is used by mono_runtime_capture_context () */
2355                 method = mono_get_context_capture_method ();
2356                 if (method)
2357                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2358
2359 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2360                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2361 #endif
2362
2363                 /* JIT icall wrappers */
2364                 /* FIXME: locking */
2365                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2366
2367                 /* stelemref */
2368                 add_method (acfg, mono_marshal_get_stelemref ());
2369
2370 #ifdef MONO_ARCH_HAVE_TLS_GET
2371                 /* Managed Allocators */
2372                 nallocators = mono_gc_get_managed_allocator_types ();
2373                 for (i = 0; i < nallocators; ++i) {
2374                         m = mono_gc_get_managed_allocator_by_type (i);
2375                         if (m)
2376                                 add_method (acfg, m);
2377                 }
2378
2379                 /* Monitor Enter/Exit */
2380                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2381                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2382                 g_assert (orig_method);
2383                 mono_method_desc_free (desc);
2384                 method = mono_monitor_get_fast_path (orig_method);
2385                 if (method)
2386                         add_method (acfg, method);
2387
2388                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2389                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2390                 g_assert (orig_method);
2391                 mono_method_desc_free (desc);
2392                 method = mono_monitor_get_fast_path (orig_method);
2393                 if (method)
2394                         add_method (acfg, method);
2395 #endif
2396
2397                 /* Stelemref wrappers */
2398                 /* There is only a constant number of these, iterating over all types should handle them all */
2399                 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2400                         MonoClass *klass;
2401                 
2402                         token = MONO_TOKEN_TYPE_DEF | (i + 1);
2403                         klass = mono_class_get (acfg->image, token);
2404                         if (klass)
2405                                 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2406                 }
2407         }
2408
2409         /* 
2410          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2411          * we use the original method instead at runtime.
2412          * Since full-aot doesn't support remoting, this is not a problem.
2413          */
2414 #if 0
2415         /* remoting-invoke wrappers */
2416         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2417                 MonoMethodSignature *sig;
2418                 
2419                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2420                 method = mono_get_method (acfg->image, token, NULL);
2421
2422                 sig = mono_method_signature (method);
2423
2424                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2425                         m = mono_marshal_get_remoting_invoke_with_check (method);
2426
2427                         add_method (acfg, m);
2428                 }
2429         }
2430 #endif
2431
2432         /* delegate-invoke wrappers */
2433         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2434                 MonoClass *klass;
2435                 
2436                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2437                 klass = mono_class_get (acfg->image, token);
2438
2439                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2440                         method = mono_get_delegate_invoke (klass);
2441
2442                         m = mono_marshal_get_delegate_invoke (method, NULL);
2443
2444                         add_method (acfg, m);
2445
2446                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2447                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2448
2449                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2450                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2451                 }
2452         }
2453
2454         /* Synchronized wrappers */
2455         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2456                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2457                 method = mono_get_method (acfg->image, token, NULL);
2458
2459                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2460                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2461         }
2462
2463         /* pinvoke wrappers */
2464         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2465                 MonoMethod *method;
2466                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2467
2468                 method = mono_get_method (acfg->image, token, NULL);
2469
2470                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2471                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2472                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2473                 }
2474         }
2475  
2476         /* native-to-managed wrappers */
2477         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2478                 MonoMethod *method;
2479                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2480                 MonoCustomAttrInfo *cattr;
2481                 int j;
2482
2483                 method = mono_get_method (acfg->image, token, NULL);
2484
2485                 /* 
2486                  * Only generate native-to-managed wrappers for methods which have an
2487                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2488                  * name to avoid defining a new assembly to contain it.
2489                  */
2490                 cattr = mono_custom_attrs_from_method (method);
2491
2492                 if (cattr) {
2493                         for (j = 0; j < cattr->num_attrs; ++j)
2494                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2495                                         break;
2496                         if (j < cattr->num_attrs) {
2497                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
2498                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2499                                 const char *p = (const char*)e->data;
2500                                 int slen;
2501                                 char *n;
2502                                 MonoType *t;
2503                                 MonoClass *klass;
2504
2505                                 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2506
2507                                 g_assert (sig->param_count == 1);
2508                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2509
2510                                 /* 
2511                                  * Decode the cattr manually since we can't create objects
2512                                  * during aot compilation.
2513                                  */
2514                                         
2515                                 /* Skip prolog */
2516                                 p += 2;
2517
2518                                 /* From load_cattr_value () in reflection.c */
2519                                 slen = mono_metadata_decode_value (p, &p);
2520                                 n = g_memdup (p, slen + 1);
2521                                 n [slen] = 0;
2522                                 t = mono_reflection_type_from_name (n, acfg->image);
2523                                 g_assert (t);
2524                                 g_free (n);
2525
2526                                 klass = mono_class_from_mono_type (t);
2527                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2528
2529                                 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2530                         }
2531                 }
2532
2533                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2534                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2535                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2536                 }
2537         }
2538
2539         /* StructureToPtr/PtrToStructure wrappers */
2540         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2541                 MonoClass *klass;
2542                 
2543                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2544                 klass = mono_class_get (acfg->image, token);
2545
2546                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2547                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2548                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2549                 }
2550         }
2551 }
2552
2553 static gboolean
2554 has_type_vars (MonoClass *klass)
2555 {
2556         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2557                 return TRUE;
2558         if (klass->rank)
2559                 return has_type_vars (klass->element_class);
2560         if (klass->generic_class) {
2561                 MonoGenericContext *context = &klass->generic_class->context;
2562                 if (context->class_inst) {
2563                         int i;
2564
2565                         for (i = 0; i < context->class_inst->type_argc; ++i)
2566                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2567                                         return TRUE;
2568                 }
2569         }
2570         return FALSE;
2571 }
2572
2573 static gboolean
2574 method_has_type_vars (MonoMethod *method)
2575 {
2576         if (has_type_vars (method->klass))
2577                 return TRUE;
2578
2579         if (method->is_inflated) {
2580                 MonoGenericContext *context = mono_method_get_context (method);
2581                 if (context->method_inst) {
2582                         int i;
2583
2584                         for (i = 0; i < context->method_inst->type_argc; ++i)
2585                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2586                                         return TRUE;
2587                 }
2588         }
2589         return FALSE;
2590 }
2591
2592 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2593
2594 static void
2595 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2596 {
2597         /* This might lead to a huge code blowup so only do it if neccesary */
2598         if (!acfg->aot_opts.full_aot && !force)
2599                 return;
2600
2601         add_generic_class_with_depth (acfg, klass, 0);
2602 }
2603
2604 /*
2605  * add_generic_class:
2606  *
2607  *   Add all methods of a generic class.
2608  */
2609 static void
2610 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2611 {
2612         MonoMethod *method;
2613         gpointer iter;
2614
2615         mono_class_init (klass);
2616
2617         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2618                 return;
2619
2620         if (has_type_vars (klass))
2621                 return;
2622
2623         if (!klass->generic_class && !klass->rank)
2624                 return;
2625
2626         iter = NULL;
2627         while ((method = mono_class_get_methods (klass, &iter))) {
2628                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2629                         /* Already added */
2630                         continue;
2631
2632                 if (method->is_generic)
2633                         /* FIXME: */
2634                         continue;
2635
2636                 /*
2637                  * FIXME: Instances which are referenced by these methods are not added,
2638                  * for example Array.Resize<int> for List<int>.Add ().
2639                  */
2640                 add_extra_method_with_depth (acfg, method, depth);
2641         }
2642
2643         if (klass->delegate) {
2644                 method = mono_get_delegate_invoke (klass);
2645
2646                 method = mono_marshal_get_delegate_invoke (method, NULL);
2647
2648                 add_method (acfg, method);
2649         }
2650
2651         /* 
2652          * For ICollection<T>, add instances of the helper methods
2653          * in Array, since a T[] could be cast to ICollection<T>.
2654          */
2655         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2656                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2657                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2658                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2659                 gpointer iter;
2660                 char *name_prefix;
2661
2662                 if (!strcmp (klass->name, "IEnumerator`1"))
2663                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2664                 else
2665                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2666
2667                 /* Add the T[]/InternalEnumerator class */
2668                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2669                         MonoClass *nclass;
2670
2671                         iter = NULL;
2672                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2673                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2674                                         break;
2675                         }
2676                         g_assert (nclass);
2677                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2678                         add_generic_class (acfg, nclass, FALSE);
2679                 }
2680
2681                 iter = NULL;
2682                 while ((method = mono_class_get_methods (array_class, &iter))) {
2683                         if (strstr (method->name, name_prefix)) {
2684                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2685                                 add_extra_method_with_depth (acfg, m, depth);
2686                         }
2687                 }
2688
2689                 g_free (name_prefix);
2690         }
2691
2692         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2693         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2694                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2695                 MonoClass *icomparable, *gcomparer;
2696                 MonoGenericContext ctx;
2697                 MonoType *args [16];
2698
2699                 memset (&ctx, 0, sizeof (ctx));
2700
2701                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2702                 g_assert (icomparable);
2703                 args [0] = &tclass->byval_arg;
2704                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2705
2706                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2707                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2708                         g_assert (gcomparer);
2709                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2710                 }
2711         }
2712
2713         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2714         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2715                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2716                 MonoClass *iface, *gcomparer;
2717                 MonoGenericContext ctx;
2718                 MonoType *args [16];
2719
2720                 memset (&ctx, 0, sizeof (ctx));
2721
2722                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2723                 g_assert (iface);
2724                 args [0] = &tclass->byval_arg;
2725                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2726
2727                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2728                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2729                         g_assert (gcomparer);
2730                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2731                 }
2732         }
2733 }
2734
2735 static void
2736 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
2737 {
2738         int i;
2739         MonoGenericContext ctx;
2740         MonoType *args [16];
2741
2742         memset (&ctx, 0, sizeof (ctx));
2743
2744         for (i = 0; i < ninsts; ++i) {
2745                 args [0] = insts [i];
2746                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2747                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
2748         }
2749 }
2750
2751 /*
2752  * add_generic_instances:
2753  *
2754  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2755  */
2756 static void
2757 add_generic_instances (MonoAotCompile *acfg)
2758 {
2759         int i;
2760         guint32 token;
2761         MonoMethod *method;
2762         MonoMethodHeader *header;
2763         MonoMethodSignature *sig;
2764         MonoGenericContext *context;
2765
2766         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2767                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2768                 method = mono_get_method (acfg->image, token, NULL);
2769
2770                 if (method->klass->image != acfg->image)
2771                         continue;
2772
2773                 context = mono_method_get_context (method);
2774
2775                 if (context && ((context->class_inst && context->class_inst->is_open)))
2776                         continue;
2777
2778                 /*
2779                  * For open methods, create an instantiation which can be passed to the JIT.
2780                  * FIXME: Handle class_inst as well.
2781                  */
2782                 if (context && context->method_inst && context->method_inst->is_open) {
2783                         MonoGenericContext shared_context;
2784                         MonoGenericInst *inst;
2785                         MonoType **type_argv;
2786                         int i;
2787                         MonoMethod *declaring_method;
2788                         gboolean supported = TRUE;
2789
2790                         /* Check that the context doesn't contain open constructed types */
2791                         if (context->class_inst) {
2792                                 inst = context->class_inst;
2793                                 for (i = 0; i < inst->type_argc; ++i) {
2794                                         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)
2795                                                 continue;
2796                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2797                                                 supported = FALSE;
2798                                 }
2799                         }
2800                         if (context->method_inst) {
2801                                 inst = context->method_inst;
2802                                 for (i = 0; i < inst->type_argc; ++i) {
2803                                         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)
2804                                                 continue;
2805                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2806                                                 supported = FALSE;
2807                                 }
2808                         }
2809
2810                         if (!supported)
2811                                 continue;
2812
2813                         memset (&shared_context, 0, sizeof (MonoGenericContext));
2814
2815                         inst = context->class_inst;
2816                         if (inst) {
2817                                 type_argv = g_new0 (MonoType*, inst->type_argc);
2818                                 for (i = 0; i < inst->type_argc; ++i) {
2819                                         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)
2820                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
2821                                         else
2822                                                 type_argv [i] = inst->type_argv [i];
2823                                 }
2824                                 
2825                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2826                                 g_free (type_argv);
2827                         }
2828
2829                         inst = context->method_inst;
2830                         if (inst) {
2831                                 type_argv = g_new0 (MonoType*, inst->type_argc);
2832                                 for (i = 0; i < inst->type_argc; ++i) {
2833                                         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)
2834                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
2835                                         else
2836                                                 type_argv [i] = inst->type_argv [i];
2837                                 }
2838
2839                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2840                                 g_free (type_argv);
2841                         }
2842
2843                         if (method->is_generic || method->klass->generic_container)
2844                                 declaring_method = method;
2845                         else
2846                                 declaring_method = mono_method_get_declaring_generic_method (method);
2847
2848                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2849                 }
2850
2851                 /* 
2852                  * If the method is fully sharable, it was already added in place of its
2853                  * generic definition.
2854                  */
2855                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2856                         continue;
2857
2858                 /*
2859                  * FIXME: Partially shared methods are not shared here, so we end up with
2860                  * many identical methods.
2861                  */
2862                 add_extra_method (acfg, method);
2863         }
2864
2865         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2866                 MonoClass *klass;
2867
2868                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2869
2870                 klass = mono_class_get (acfg->image, token);
2871                 if (!klass || klass->rank)
2872                         continue;
2873
2874                 add_generic_class (acfg, klass, FALSE);
2875         }
2876
2877         /* Add types of args/locals */
2878         for (i = 0; i < acfg->methods->len; ++i) {
2879                 int j;
2880
2881                 method = g_ptr_array_index (acfg->methods, i);
2882
2883                 sig = mono_method_signature (method);
2884
2885                 if (sig) {
2886                         for (j = 0; j < sig->param_count; ++j)
2887                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2888                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]), FALSE);
2889                 }
2890
2891                 header = mono_method_get_header (method);
2892
2893                 if (header) {
2894                         for (j = 0; j < header->num_locals; ++j)
2895                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2896                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]), FALSE);
2897                 }
2898         }
2899
2900         if (acfg->image == mono_defaults.corlib) {
2901                 MonoClass *klass;
2902                 MonoType *insts [256];
2903                 int ninsts = 0;
2904
2905                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2906                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2907                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2908                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2909                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2910                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2911                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2912                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2913                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2914                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2915                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2916                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2917
2918                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2919                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2920                 if (klass)
2921                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2922                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2923                 if (klass)
2924                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2925
2926                 /* Add instances of the array generic interfaces for primitive types */
2927                 /* This will add instances of the InternalArray_ helper methods in Array too */
2928                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2929                 if (klass)
2930                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2931                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2932                 if (klass)
2933                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2934                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2935                 if (klass)
2936                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2937
2938                 /* 
2939                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2940                  * used for all instances of GetGenericValueImpl by the AOT runtime.
2941                  */
2942                 {
2943                         MonoGenericContext ctx;
2944                         MonoType *args [16];
2945                         MonoMethod *get_method;
2946                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2947
2948                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2949
2950                         if (get_method) {
2951                                 memset (&ctx, 0, sizeof (ctx));
2952                                 args [0] = &mono_defaults.object_class->byval_arg;
2953                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2954                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2955                         }
2956                 }
2957         }
2958 }
2959
2960 /*
2961  * is_direct_callable:
2962  *
2963  *   Return whenever the method identified by JI is directly callable without 
2964  * going through the PLT.
2965  */
2966 static gboolean
2967 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2968 {
2969         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2970                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2971                 if (callee_cfg) {
2972                         gboolean direct_callable = TRUE;
2973
2974                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2975                                 direct_callable = FALSE;
2976                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2977                                 // FIXME: Maybe call the wrapper directly ?
2978                                 direct_callable = FALSE;
2979
2980                         if (direct_callable)
2981                                 return TRUE;
2982                 }
2983         }
2984
2985         return FALSE;
2986 }
2987
2988 /*
2989  * emit_and_reloc_code:
2990  *
2991  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2992  * is true, calls are made through the GOT too. This is used for emitting trampolines
2993  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2994  * since trampolines are needed to make PTL work.
2995  */
2996 static void
2997 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2998 {
2999         int i, pindex, start_index, method_index;
3000         GPtrArray *patches;
3001         MonoJumpInfo *patch_info;
3002         MonoMethodHeader *header;
3003         gboolean skip, direct_call;
3004         guint32 got_slot;
3005         char direct_call_target [128];
3006
3007         if (method) {
3008                 header = mono_method_get_header (method);
3009
3010                 method_index = get_method_index (acfg, method);
3011         }
3012
3013         /* Collect and sort relocations */
3014         patches = g_ptr_array_new ();
3015         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3016                 g_ptr_array_add (patches, patch_info);
3017         g_ptr_array_sort (patches, compare_patches);
3018
3019         start_index = 0;
3020         for (i = 0; i < code_len; i++) {
3021                 patch_info = NULL;
3022                 for (pindex = start_index; pindex < patches->len; ++pindex) {
3023                         patch_info = g_ptr_array_index (patches, pindex);
3024                         if (patch_info->ip.i >= i)
3025                                 break;
3026                 }
3027
3028 #ifdef MONO_ARCH_AOT_SUPPORTED
3029                 skip = FALSE;
3030                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3031                         start_index = pindex;
3032
3033                         switch (patch_info->type) {
3034                         case MONO_PATCH_INFO_NONE:
3035                                 break;
3036                         case MONO_PATCH_INFO_GOT_OFFSET: {
3037                                 int code_size;
3038  
3039                                 arch_emit_got_offset (acfg, code + i, &code_size);
3040                                 i += code_size - 1;
3041                                 skip = TRUE;
3042                                 patch_info->type = MONO_PATCH_INFO_NONE;
3043                                 break;
3044                         }
3045                         default: {
3046                                 /*
3047                                  * If this patch is a call, try emitting a direct call instead of
3048                                  * through a PLT entry. This is possible if the called method is in
3049                                  * the same assembly and requires no initialization.
3050                                  */
3051                                 direct_call = FALSE;
3052                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3053                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3054                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3055                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3056                                                 direct_call = TRUE;
3057                                                 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3058                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3059                                                 acfg->stats.direct_calls ++;
3060                                         }
3061
3062                                         acfg->stats.all_calls ++;
3063                                 }
3064
3065                                 if (!got_only && !direct_call) {
3066                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3067                                         if (plt_entry) {
3068                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3069                                                 direct_call = TRUE;
3070                                                 sprintf (direct_call_target, "%s", plt_entry->symbol);
3071                 
3072                                                 /* Nullify the patch */
3073                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3074                                         }
3075                                 }
3076
3077                                 if (direct_call) {
3078                                         int call_size;
3079
3080                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
3081                                         i += call_size - 1;
3082                                 } else {
3083                                         int code_size;
3084
3085                                         got_slot = get_got_offset (acfg, patch_info);
3086
3087                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3088                                         i += code_size - 1;
3089                                 }
3090                                 skip = TRUE;
3091                         }
3092                         }
3093                 }
3094 #endif /* MONO_ARCH_AOT_SUPPORTED */
3095
3096                 if (!skip) {
3097                         /* Find next patch */
3098                         patch_info = NULL;
3099                         for (pindex = start_index; pindex < patches->len; ++pindex) {
3100                                 patch_info = g_ptr_array_index (patches, pindex);
3101                                 if (patch_info->ip.i >= i)
3102                                         break;
3103                         }
3104
3105                         /* Try to emit multiple bytes at once */
3106                         if (pindex < patches->len && patch_info->ip.i > i) {
3107                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3108                                 i = patch_info->ip.i - 1;
3109                         } else {
3110                                 emit_bytes (acfg, code + i, 1);
3111                         }
3112                 }
3113         }
3114 }
3115
3116 /*
3117  * sanitize_symbol:
3118  *
3119  *   Modify SYMBOL so it only includes characters permissible in symbols.
3120  */
3121 static void
3122 sanitize_symbol (char *symbol)
3123 {
3124         int i, len = strlen (symbol);
3125
3126         for (i = 0; i < len; ++i)
3127                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3128                         symbol [i] = '_';
3129 }
3130
3131 static char*
3132 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3133 {
3134         char *name1, *name2, *cached;
3135         int i, j, len, count;
3136                 
3137         name1 = mono_method_full_name (method, TRUE);
3138         len = strlen (name1);
3139         name2 = malloc (strlen (prefix) + len + 16);
3140         memcpy (name2, prefix, strlen (prefix));
3141         j = strlen (prefix);
3142         for (i = 0; i < len; ++i) {
3143                 if (isalnum (name1 [i])) {
3144                         name2 [j ++] = name1 [i];
3145                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3146                         i += 2;
3147                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3148                         name2 [j ++] = '_';
3149                         i++;
3150                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3151                 } else
3152                         name2 [j ++] = '_';
3153         }
3154         name2 [j] = '\0';
3155
3156         g_free (name1);
3157
3158         count = 0;
3159         while (g_hash_table_lookup (cache, name2)) {
3160                 sprintf (name2 + j, "_%d", count);
3161                 count ++;
3162         }
3163
3164         cached = g_strdup (name2);
3165         g_hash_table_insert (cache, cached, cached);
3166
3167         return name2;
3168 }
3169
3170 static void
3171 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3172 {
3173         MonoMethod *method;
3174         int method_index;
3175         guint8 *code;
3176         char *debug_sym = NULL;
3177         char symbol [128];
3178         int func_alignment = AOT_FUNC_ALIGNMENT;
3179         MonoMethodHeader *header;
3180
3181         method = cfg->orig_method;
3182         code = cfg->native_code;
3183         header = cfg->header;
3184
3185         method_index = get_method_index (acfg, method);
3186
3187         /* Make the labels local */
3188         sprintf (symbol, "%s", cfg->asm_symbol);
3189
3190         emit_section_change (acfg, ".text", 0);
3191         emit_alignment (acfg, func_alignment);
3192         emit_label (acfg, symbol);
3193
3194         if (acfg->aot_opts.write_symbols) {
3195                 /* 
3196                  * Write a C style symbol for every method, this has two uses:
3197                  * - it works on platforms where the dwarf debugging info is not
3198                  *   yet supported.
3199                  * - it allows the setting of breakpoints of aot-ed methods.
3200                  */
3201                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3202
3203                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3204                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3205                 emit_label (acfg, debug_sym);
3206         }
3207
3208         if (cfg->verbose_level > 0)
3209                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3210
3211         acfg->stats.code_size += cfg->code_len;
3212
3213         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3214
3215         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3216
3217         emit_line (acfg);
3218
3219         if (acfg->aot_opts.write_symbols) {
3220                 emit_symbol_size (acfg, debug_sym, ".");
3221                 g_free (debug_sym);
3222         }
3223
3224         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3225         emit_label (acfg, symbol);
3226 }
3227
3228 /**
3229  * encode_patch:
3230  *
3231  *  Encode PATCH_INFO into its disk representation.
3232  */
3233 static void
3234 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3235 {
3236         guint8 *p = buf;
3237
3238         switch (patch_info->type) {
3239         case MONO_PATCH_INFO_NONE:
3240                 break;
3241         case MONO_PATCH_INFO_IMAGE:
3242                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3243                 break;
3244         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3245         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3246                 break;
3247         case MONO_PATCH_INFO_METHOD_REL:
3248                 encode_value ((gint)patch_info->data.offset, p, &p);
3249                 break;
3250         case MONO_PATCH_INFO_SWITCH: {
3251                 gpointer *table = (gpointer *)patch_info->data.table->table;
3252                 int k;
3253
3254                 encode_value (patch_info->data.table->table_size, p, &p);
3255                 for (k = 0; k < patch_info->data.table->table_size; k++)
3256                         encode_value ((int)(gssize)table [k], p, &p);
3257                 break;
3258         }
3259         case MONO_PATCH_INFO_METHODCONST:
3260         case MONO_PATCH_INFO_METHOD:
3261         case MONO_PATCH_INFO_METHOD_JUMP:
3262         case MONO_PATCH_INFO_ICALL_ADDR:
3263         case MONO_PATCH_INFO_METHOD_RGCTX:
3264                 encode_method_ref (acfg, patch_info->data.method, p, &p);
3265                 break;
3266         case MONO_PATCH_INFO_INTERNAL_METHOD:
3267         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3268                 guint32 len = strlen (patch_info->data.name);
3269
3270                 encode_value (len, p, &p);
3271
3272                 memcpy (p, patch_info->data.name, len);
3273                 p += len;
3274                 *p++ = '\0';
3275                 break;
3276         }
3277         case MONO_PATCH_INFO_LDSTR: {
3278                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3279                 guint32 token = patch_info->data.token->token;
3280                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3281                 encode_value (image_index, p, &p);
3282                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3283                 break;
3284         }
3285         case MONO_PATCH_INFO_RVA:
3286         case MONO_PATCH_INFO_DECLSEC:
3287         case MONO_PATCH_INFO_LDTOKEN:
3288         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3289                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3290                 encode_value (patch_info->data.token->token, p, &p);
3291                 encode_value (patch_info->data.token->has_context, p, &p);
3292                 if (patch_info->data.token->has_context)
3293                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3294                 break;
3295         case MONO_PATCH_INFO_EXC_NAME: {
3296                 MonoClass *ex_class;
3297
3298                 ex_class =
3299                         mono_class_from_name (mono_defaults.exception_class->image,
3300                                                                   "System", patch_info->data.target);
3301                 g_assert (ex_class);
3302                 encode_klass_ref (acfg, ex_class, p, &p);
3303                 break;
3304         }
3305         case MONO_PATCH_INFO_R4:
3306                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3307                 break;
3308         case MONO_PATCH_INFO_R8:
3309                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3310                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3311                 break;
3312         case MONO_PATCH_INFO_VTABLE:
3313         case MONO_PATCH_INFO_CLASS:
3314         case MONO_PATCH_INFO_IID:
3315         case MONO_PATCH_INFO_ADJUSTED_IID:
3316                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3317                 break;
3318         case MONO_PATCH_INFO_CLASS_INIT:
3319         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3320                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3321                 break;
3322         case MONO_PATCH_INFO_FIELD:
3323         case MONO_PATCH_INFO_SFLDA:
3324                 encode_field_info (acfg, patch_info->data.field, p, &p);
3325                 break;
3326         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3327                 break;
3328         case MONO_PATCH_INFO_RGCTX_FETCH: {
3329                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3330
3331                 encode_method_ref (acfg, entry->method, p, &p);
3332                 encode_value (entry->in_mrgctx, p, &p);
3333                 encode_value (entry->info_type, p, &p);
3334                 encode_value (entry->data->type, p, &p);
3335                 encode_patch (acfg, entry->data, p, &p);
3336                 break;
3337         }
3338         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3339         case MONO_PATCH_INFO_MONITOR_ENTER:
3340         case MONO_PATCH_INFO_MONITOR_EXIT:
3341         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3342                 break;
3343         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3344                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3345                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3346                 break;
3347         default:
3348                 g_warning ("unable to handle jump info %d", patch_info->type);
3349                 g_assert_not_reached ();
3350         }
3351
3352         *endbuf = p;
3353 }
3354
3355 static void
3356 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3357 {
3358         guint8 *p = buf;
3359         guint32 pindex, offset;
3360         MonoJumpInfo *patch_info;
3361
3362         encode_value (n_patches, p, &p);
3363
3364         for (pindex = 0; pindex < patches->len; ++pindex) {
3365                 patch_info = g_ptr_array_index (patches, pindex);
3366
3367                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3368                         /* Nothing to do */
3369                         continue;
3370
3371                 offset = get_got_offset (acfg, patch_info);
3372                 encode_value (offset, p, &p);
3373         }
3374
3375         *endbuf = p;
3376 }
3377
3378 static void
3379 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3380 {
3381         MonoMethod *method;
3382         GList *l;
3383         int pindex, buf_size, n_patches;
3384         guint8 *code;
3385         GPtrArray *patches;
3386         MonoJumpInfo *patch_info;
3387         MonoMethodHeader *header;
3388         guint32 method_index;
3389         guint8 *p, *buf;
3390         guint32 first_got_offset;
3391
3392         method = cfg->orig_method;
3393         code = cfg->native_code;
3394         header = mono_method_get_header (method);
3395
3396         method_index = get_method_index (acfg, method);
3397
3398         /* Sort relocations */
3399         patches = g_ptr_array_new ();
3400         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3401                 g_ptr_array_add (patches, patch_info);
3402         g_ptr_array_sort (patches, compare_patches);
3403
3404         first_got_offset = acfg->cfgs [method_index]->got_offset;
3405
3406         /**********************/
3407         /* Encode method info */
3408         /**********************/
3409
3410         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3411         p = buf = g_malloc (buf_size);
3412
3413         if (mono_class_get_cctor (method->klass))
3414                 encode_klass_ref (acfg, method->klass, p, &p);
3415         else
3416                 /* Not needed when loading the method */
3417                 encode_value (0, p, &p);
3418
3419         /* String table */
3420         if (cfg->opt & MONO_OPT_SHARED) {
3421                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3422                 for (l = cfg->ldstr_list; l; l = l->next) {
3423                         encode_value ((long)l->data, p, &p);
3424                 }
3425         }
3426         else
3427                 /* Used only in shared mode */
3428                 g_assert (!cfg->ldstr_list);
3429
3430         n_patches = 0;
3431         for (pindex = 0; pindex < patches->len; ++pindex) {
3432                 patch_info = g_ptr_array_index (patches, pindex);
3433                 
3434                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3435                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
3436                         patch_info->type = MONO_PATCH_INFO_NONE;
3437                         /* Nothing to do */
3438                         continue;
3439                 }
3440
3441                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3442                         /* Stored in a GOT slot initialized at module load time */
3443                         patch_info->type = MONO_PATCH_INFO_NONE;
3444                         continue;
3445                 }
3446
3447                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3448                         /* Stored in a GOT slot initialized at module load time */
3449                         patch_info->type = MONO_PATCH_INFO_NONE;
3450                         continue;
3451                 }
3452
3453                 if (is_plt_patch (patch_info)) {
3454                         /* Calls are made through the PLT */
3455                         patch_info->type = MONO_PATCH_INFO_NONE;
3456                         continue;
3457                 }
3458
3459                 n_patches ++;
3460         }
3461
3462         if (n_patches)
3463                 g_assert (cfg->has_got_slots);
3464
3465         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3466
3467         acfg->stats.info_size += p - buf;
3468
3469         g_assert (p - buf < buf_size);
3470
3471         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3472         g_free (buf);
3473 }
3474
3475 static guint32
3476 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3477 {
3478         guint32 cache_index;
3479         guint32 offset;
3480
3481         /* Reuse the unwind module to canonize and store unwind info entries */
3482         cache_index = mono_cache_unwind_info (encoded, encoded_len);
3483
3484         /* Use +/- 1 to distinguish 0s from missing entries */
3485         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3486         if (offset)
3487                 return offset - 1;
3488         else {
3489                 guint8 buf [16];
3490                 guint8 *p;
3491
3492                 /* 
3493                  * It would be easier to use assembler symbols, but the caller needs an
3494                  * offset now.
3495                  */
3496                 offset = acfg->unwind_info_offset;
3497                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3498                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3499
3500                 p = buf;
3501                 encode_value (encoded_len, p, &p);
3502
3503                 acfg->unwind_info_offset += encoded_len + (p - buf);
3504                 return offset;
3505         }
3506 }
3507
3508 static void
3509 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3510 {
3511         MonoMethod *method;
3512         int i, k, buf_size, method_index;
3513         guint32 debug_info_size;
3514         guint8 *code;
3515         MonoMethodHeader *header;
3516         guint8 *p, *buf, *debug_info;
3517         MonoJitInfo *jinfo = cfg->jit_info;
3518         guint32 flags;
3519         gboolean use_unwind_ops = FALSE;
3520         MonoSeqPointInfo *seq_points;
3521
3522         method = cfg->orig_method;
3523         code = cfg->native_code;
3524         header = cfg->header;
3525
3526         method_index = get_method_index (acfg, method);
3527
3528         if (!acfg->aot_opts.nodebug) {
3529                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3530         } else {
3531                 debug_info = NULL;
3532                 debug_info_size = 0;
3533         }
3534
3535         seq_points = cfg->seq_point_info;
3536
3537         buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3538         p = buf = g_malloc (buf_size);
3539
3540 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3541         use_unwind_ops = cfg->unwind_ops != NULL;
3542 #endif
3543
3544         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);
3545
3546         encode_value (flags, p, &p);
3547
3548         if (use_unwind_ops) {
3549                 guint32 encoded_len;
3550                 guint8 *encoded;
3551
3552                 /* 
3553                  * This is a duplicate of the data in the .debug_frame section, but that
3554                  * section cannot be accessed using the dl interface.
3555                  */
3556                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3557                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3558                 g_free (encoded);
3559         } else {
3560                 encode_value (jinfo->used_regs, p, &p);
3561         }
3562
3563         /*Encode the number of holes before the number of clauses to make decoding easier*/
3564         if (jinfo->has_try_block_holes) {
3565                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3566                 encode_value (table->num_holes, p, &p);
3567         }
3568
3569         /* Exception table */
3570         if (cfg->compile_llvm) {
3571                 /*
3572                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3573                  * since the information is only available to llc. Instead, we let llc save the data
3574                  * into the LSDA, and read it from there at runtime.
3575                  */
3576                 /* The assembly might be CIL stripped so emit the data ourselves */
3577                 if (header->num_clauses)
3578                         encode_value (header->num_clauses, p, &p);
3579
3580                 for (k = 0; k < header->num_clauses; ++k) {
3581                         MonoExceptionClause *clause;
3582
3583                         clause = &header->clauses [k];
3584
3585                         encode_value (clause->flags, p, &p);
3586                         if (clause->data.catch_class) {
3587                                 encode_value (1, p, &p);
3588                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3589                         } else {
3590                                 encode_value (0, p, &p);
3591                         }
3592
3593                         /* Emit a list of nesting clauses */
3594                         for (i = 0; i < header->num_clauses; ++i) {
3595                                 gint32 cindex1 = k;
3596                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3597                                 gint32 cindex2 = i;
3598                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3599
3600                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3601                                         encode_value (i, p, &p);
3602                         }
3603                         encode_value (-1, p, &p);
3604                 }
3605         } else {
3606                 if (jinfo->num_clauses)
3607                         encode_value (jinfo->num_clauses, p, &p);
3608
3609                 for (k = 0; k < jinfo->num_clauses; ++k) {
3610                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3611
3612                         encode_value (ei->flags, p, &p);
3613                         encode_value (ei->exvar_offset, p, &p);
3614
3615                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3616                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3617                         else {
3618                                 if (ei->data.catch_class) {
3619                                         encode_value (1, p, &p);
3620                                         encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3621                                 } else {
3622                                         encode_value (0, p, &p);
3623                                 }
3624                         }
3625
3626                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3627                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3628                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3629                 }
3630         }
3631
3632         if (jinfo->has_generic_jit_info) {
3633                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3634
3635                 if (!cfg->compile_llvm) {
3636                         encode_value (gi->has_this ? 1 : 0, p, &p);
3637                         encode_value (gi->this_reg, p, &p);
3638                         encode_value (gi->this_offset, p, &p);
3639                 }
3640
3641                 /* 
3642                  * Need to encode jinfo->method too, since it is not equal to 'method'
3643                  * when using generic sharing.
3644                  */
3645                 encode_method_ref (acfg, jinfo->method, p, &p);
3646         }
3647
3648         if (jinfo->has_try_block_holes) {
3649                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3650                 for (i = 0; i < table->num_holes; ++i) {
3651                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3652                         encode_value (hole->clause, p, &p);
3653                         encode_value (hole->length, p, &p);
3654                         encode_value (hole->offset, p, &p);
3655                 }
3656         }
3657
3658         if (seq_points) {
3659                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3660
3661                 encode_value (seq_points->len, p, &p);
3662                 last_il_offset = last_native_offset = 0;
3663                 for (i = 0; i < seq_points->len; ++i) {
3664                         SeqPoint *sp = &seq_points->seq_points [i];
3665                         il_offset = sp->il_offset;
3666                         native_offset = sp->native_offset;
3667                         encode_value (il_offset - last_il_offset, p, &p);
3668                         encode_value (native_offset - last_native_offset, p, &p);
3669                         last_il_offset = il_offset;
3670                         last_native_offset = native_offset;
3671
3672                         encode_value (sp->next_len, p, &p);
3673                         for (j = 0; j < sp->next_len; ++j)
3674                                 encode_value (sp->next [j], p, &p);
3675                 }
3676         }
3677                 
3678
3679         g_assert (debug_info_size < buf_size);
3680
3681         encode_value (debug_info_size, p, &p);
3682         if (debug_info_size) {
3683                 memcpy (p, debug_info, debug_info_size);
3684                 p += debug_info_size;
3685                 g_free (debug_info);
3686         }
3687
3688         acfg->stats.ex_info_size += p - buf;
3689
3690         g_assert (p - buf < buf_size);
3691
3692         /* Emit info */
3693         cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3694         g_free (buf);
3695 }
3696
3697 static guint32
3698 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3699 {
3700         MonoClass *klass = mono_class_get (acfg->image, token);
3701         guint8 *p, *buf;
3702         int i, buf_size, res;
3703         gboolean no_special_static, cant_encode;
3704         gpointer iter = NULL;
3705
3706         if (!klass) {
3707                 buf_size = 16;
3708
3709                 p = buf = g_malloc (buf_size);
3710
3711                 /* Mark as unusable */
3712                 encode_value (-1, p, &p);
3713
3714                 res = add_to_blob (acfg, buf, p - buf);
3715                 g_free (buf);
3716
3717                 return res;
3718         }
3719                 
3720         buf_size = 10240 + (klass->vtable_size * 16);
3721         p = buf = g_malloc (buf_size);
3722
3723         g_assert (klass);
3724
3725         mono_class_init (klass);
3726
3727         mono_class_get_nested_types (klass, &iter);
3728         g_assert (klass->nested_classes_inited);
3729
3730         mono_class_setup_vtable (klass);
3731
3732         /* 
3733          * Emit all the information which is required for creating vtables so
3734          * the runtime does not need to create the MonoMethod structures which
3735          * take up a lot of space.
3736          */
3737
3738         no_special_static = !mono_class_has_special_static_fields (klass);
3739
3740         /* Check whenever we have enough info to encode the vtable */
3741         cant_encode = FALSE;
3742         for (i = 0; i < klass->vtable_size; ++i) {
3743                 MonoMethod *cm = klass->vtable [i];
3744
3745                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3746                         cant_encode = TRUE;
3747         }
3748
3749         if (klass->generic_container || cant_encode) {
3750                 encode_value (-1, p, &p);
3751         } else {
3752                 encode_value (klass->vtable_size, p, &p);
3753                 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);
3754                 if (klass->has_cctor)
3755                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3756                 if (klass->has_finalize)
3757                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3758  
3759                 encode_value (klass->instance_size, p, &p);
3760                 encode_value (mono_class_data_size (klass), p, &p);
3761                 encode_value (klass->packing_size, p, &p);
3762                 encode_value (klass->min_align, p, &p);
3763
3764                 for (i = 0; i < klass->vtable_size; ++i) {
3765                         MonoMethod *cm = klass->vtable [i];
3766
3767                         if (cm)
3768                                 encode_method_ref (acfg, cm, p, &p);
3769                         else
3770                                 encode_value (0, p, &p);
3771                 }
3772         }
3773
3774         acfg->stats.class_info_size += p - buf;
3775
3776         g_assert (p - buf < buf_size);
3777         res = add_to_blob (acfg, buf, p - buf);
3778         g_free (buf);
3779
3780         return res;
3781 }
3782
3783 /*
3784  * Calls made from AOTed code are routed through a table of jumps similar to the
3785  * ELF PLT (Program Linkage Table). The differences are the following:
3786  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3787  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3788  *   jumps. This means the jumps need to be patched when the address of the callee is
3789  *   known. Initially the PLT entries jump to code which transfers control to the
3790  *   AOT runtime through the first PLT entry.
3791  */
3792 static void
3793 emit_plt (MonoAotCompile *acfg)
3794 {
3795         char symbol [128];
3796         int i;
3797         GHashTable *cache;
3798
3799         cache = g_hash_table_new (g_str_hash, g_str_equal);
3800
3801         emit_line (acfg);
3802         sprintf (symbol, "plt");
3803
3804         emit_section_change (acfg, ".text", 0);
3805         emit_global (acfg, symbol, TRUE);
3806         emit_alignment (acfg, 16);
3807         emit_label (acfg, symbol);
3808         emit_label (acfg, acfg->plt_symbol);
3809
3810         for (i = 0; i < acfg->plt_offset; ++i) {
3811                 char label [128];
3812                 char *debug_sym = NULL;
3813                 MonoPltEntry *plt_entry = NULL;
3814                 MonoJumpInfo *ji;
3815
3816                 if (i == 0) {
3817                         /* 
3818                          * The first plt entry is used to transfer code to the AOT loader. 
3819                          */
3820                         arch_emit_plt_entry (acfg, i);
3821                         continue;
3822                 }
3823
3824                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3825                 ji = plt_entry->ji;
3826                 sprintf (label, "%s", plt_entry->symbol);
3827
3828                 if (acfg->llvm) {
3829                         /*
3830                          * If the target is directly callable, alias the plt symbol to point to
3831                          * the method code.
3832                          * FIXME: Use this to simplify emit_and_reloc_code ().
3833                          * FIXME: Avoid the got slot.
3834                          * FIXME: Add support to the binary writer.
3835                          */
3836                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3837                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3838                                 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3839                                 continue;
3840                         }
3841                 }
3842
3843                 emit_label (acfg, label);
3844
3845                 if (acfg->aot_opts.write_symbols) {
3846                         switch (ji->type) {
3847                         case MONO_PATCH_INFO_METHOD:
3848                                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3849                                 break;
3850                         case MONO_PATCH_INFO_INTERNAL_METHOD:
3851                                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3852                                 break;
3853                         case MONO_PATCH_INFO_CLASS_INIT:
3854                                 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3855                                 sanitize_symbol (debug_sym);
3856                                 break;
3857                         case MONO_PATCH_INFO_RGCTX_FETCH:
3858                                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3859                                 break;
3860                         case MONO_PATCH_INFO_ICALL_ADDR: {
3861                                 char *s = get_debug_sym (ji->data.method, "", cache);
3862                                         
3863                                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3864                                 g_free (s);
3865                                 break;
3866                         }
3867                         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3868                                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3869                                 break;
3870                         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3871                                 debug_sym = g_strdup_printf ("plt__generic_class_init");
3872                                 break;
3873                         default:
3874                                 break;
3875                         }
3876
3877                         if (debug_sym) {
3878                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3879                                 emit_label (acfg, debug_sym);
3880                         }
3881                 }
3882
3883                 arch_emit_plt_entry (acfg, i);
3884
3885                 if (debug_sym) {
3886                         emit_symbol_size (acfg, debug_sym, ".");
3887                         g_free (debug_sym);
3888                 }
3889         }
3890
3891         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3892
3893         sprintf (symbol, "plt_end");
3894         emit_global (acfg, symbol, TRUE);
3895         emit_label (acfg, symbol);
3896
3897         g_hash_table_destroy (cache);
3898 }
3899
3900 static G_GNUC_UNUSED void
3901 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3902 {
3903         char start_symbol [256];
3904         char symbol [256];
3905         guint32 buf_size, info_offset;
3906         MonoJumpInfo *patch_info;
3907         guint8 *buf, *p;
3908         GPtrArray *patches;
3909         char *name;
3910         guint8 *code;
3911         guint32 code_size;
3912         MonoJumpInfo *ji;
3913         GSList *unwind_ops;
3914
3915         name = info->name;
3916         code = info->code;
3917         code_size = info->code_size;
3918         ji = info->ji;
3919         unwind_ops = info->unwind_ops;
3920
3921 #ifdef __native_client_codegen__
3922         mono_nacl_fix_patches (code, ji);
3923 #endif
3924
3925         /* Emit code */
3926
3927         sprintf (start_symbol, "%s", name);
3928
3929         emit_section_change (acfg, ".text", 0);
3930         emit_global (acfg, start_symbol, TRUE);
3931         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
3932         emit_label (acfg, start_symbol);
3933
3934         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3935         emit_label (acfg, symbol);
3936
3937         /* 
3938          * The code should access everything through the GOT, so we pass
3939          * TRUE here.
3940          */
3941         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3942
3943         emit_symbol_size (acfg, start_symbol, ".");
3944
3945         /* Emit info */
3946
3947         /* Sort relocations */
3948         patches = g_ptr_array_new ();
3949         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3950                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3951                         g_ptr_array_add (patches, patch_info);
3952         g_ptr_array_sort (patches, compare_patches);
3953
3954         buf_size = patches->len * 128 + 128;
3955         buf = g_malloc (buf_size);
3956         p = buf;
3957
3958         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3959         g_assert (p - buf < buf_size);
3960
3961         sprintf (symbol, "%s_p", name);
3962
3963         info_offset = add_to_blob (acfg, buf, p - buf);
3964
3965         emit_section_change (acfg, RODATA_SECT, 0);
3966         emit_global (acfg, symbol, FALSE);
3967         emit_label (acfg, symbol);
3968
3969         emit_int32 (acfg, info_offset);
3970
3971         /* Emit debug info */
3972         if (unwind_ops) {
3973                 char symbol2 [256];
3974
3975                 sprintf (symbol, "%s", name);
3976                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3977
3978                 if (acfg->dwarf)
3979                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3980         }
3981 }
3982
3983 static void
3984 emit_trampolines (MonoAotCompile *acfg)
3985 {
3986         char symbol [256];
3987         int i, tramp_got_offset;
3988         MonoAotTrampoline ntype;
3989 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3990         int tramp_type;
3991         guint8 *code;
3992 #endif
3993
3994         if (!acfg->aot_opts.full_aot)
3995                 return;
3996         
3997         g_assert (acfg->image->assembly);
3998
3999         /* Currently, we emit most trampolines into the mscorlib AOT image. */
4000         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4001 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4002                 MonoTrampInfo *info;
4003
4004                 /*
4005                  * Emit the generic trampolines.
4006                  *
4007                  * We could save some code by treating the generic trampolines as a wrapper
4008                  * method, but that approach has its own complexities, so we choose the simpler
4009                  * method.
4010                  */
4011                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4012                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4013                         emit_trampoline (acfg, acfg->got_offset, info);
4014                 }
4015
4016                 mono_arch_get_nullified_class_init_trampoline (&info);
4017                 emit_trampoline (acfg, acfg->got_offset, info);
4018 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4019                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4020                 emit_trampoline (acfg, acfg->got_offset, info);
4021                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4022                 emit_trampoline (acfg, acfg->got_offset, info);
4023 #endif
4024
4025                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4026                 emit_trampoline (acfg, acfg->got_offset, info);
4027
4028                 /* Emit the exception related code pieces */
4029                 code = mono_arch_get_restore_context (&info, TRUE);
4030                 emit_trampoline (acfg, acfg->got_offset, info);
4031                 code = mono_arch_get_call_filter (&info, TRUE);
4032                 emit_trampoline (acfg, acfg->got_offset, info);
4033                 code = mono_arch_get_throw_exception (&info, TRUE);
4034                 emit_trampoline (acfg, acfg->got_offset, info);
4035                 code = mono_arch_get_rethrow_exception (&info, TRUE);
4036                 emit_trampoline (acfg, acfg->got_offset, info);
4037                 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4038                 emit_trampoline (acfg, acfg->got_offset, info);
4039
4040 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4041                 {
4042                         GSList *l = mono_arch_get_trampolines (TRUE);
4043
4044                         while (l) {
4045                                 MonoTrampInfo *info = l->data;
4046
4047                                 emit_trampoline (acfg, acfg->got_offset, info);
4048                                 l = l->next;
4049                         }
4050                 }
4051 #endif
4052
4053                 for (i = 0; i < 128; ++i) {
4054                         int offset;
4055
4056                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4057                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4058                         emit_trampoline (acfg, acfg->got_offset, info);
4059
4060                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4061                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4062                         emit_trampoline (acfg, acfg->got_offset, info);
4063                 }
4064
4065                 {
4066                         GSList *l;
4067
4068                         /* delegate_invoke_impl trampolines */
4069                         l = mono_arch_get_delegate_invoke_impls ();
4070                         while (l) {
4071                                 MonoTrampInfo *info = l->data;
4072
4073                                 emit_trampoline (acfg, acfg->got_offset, info);
4074                                 l = l->next;
4075                         }
4076                 }
4077
4078 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4079
4080                 /* Emit trampolines which are numerous */
4081
4082                 /*
4083                  * These include the following:
4084                  * - specific trampolines
4085                  * - static rgctx invoke trampolines
4086                  * - imt thunks
4087                  * These trampolines have the same code, they are parameterized by GOT 
4088                  * slots. 
4089                  * They are defined in this file, in the arch_... routines instead of
4090                  * in tramp-<ARCH>.c, since it is easier to do it this way.
4091                  */
4092
4093                 /*
4094                  * When running in aot-only mode, we can't create specific trampolines at 
4095                  * runtime, so we create a few, and save them in the AOT file. 
4096                  * Normal trampolines embed their argument as a literal inside the 
4097                  * trampoline code, we can't do that here, so instead we embed an offset
4098                  * which needs to be added to the trampoline address to get the address of
4099                  * the GOT slot which contains the argument value.
4100                  * The generated trampolines jump to the generic trampolines using another
4101                  * GOT slot, which will be setup by the AOT loader to point to the 
4102                  * generic trampoline code of the given type.
4103                  */
4104
4105                 /*
4106                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4107                  * each class).
4108                  */
4109
4110                 emit_section_change (acfg, ".text", 0);
4111
4112                 tramp_got_offset = acfg->got_offset;
4113
4114                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4115                         switch (ntype) {
4116                         case MONO_AOT_TRAMP_SPECIFIC:
4117                                 sprintf (symbol, "specific_trampolines");
4118                                 break;
4119                         case MONO_AOT_TRAMP_STATIC_RGCTX:
4120                                 sprintf (symbol, "static_rgctx_trampolines");
4121                                 break;
4122                         case MONO_AOT_TRAMP_IMT_THUNK:
4123                                 sprintf (symbol, "imt_thunks");
4124                                 break;
4125                         default:
4126                                 g_assert_not_reached ();
4127                         }
4128
4129                         emit_global (acfg, symbol, TRUE);
4130                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4131                         emit_label (acfg, symbol);
4132
4133                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4134
4135                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4136                                 int tramp_size = 0;
4137
4138                                 switch (ntype) {
4139                                 case MONO_AOT_TRAMP_SPECIFIC:
4140                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4141                                         tramp_got_offset += 2;
4142                                 break;
4143                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
4144                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
4145                                         tramp_got_offset += 2;
4146                                         break;
4147                                 case MONO_AOT_TRAMP_IMT_THUNK:
4148                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4149                                         tramp_got_offset += 1;
4150                                         break;
4151                                 default:
4152                                         g_assert_not_reached ();
4153                                 }
4154 #ifdef __native_client_codegen__
4155                                 /* align to avoid 32-byte boundary crossings */
4156                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4157 #endif
4158
4159                                 if (!acfg->trampoline_size [ntype]) {
4160                                         g_assert (tramp_size);
4161                                         acfg->trampoline_size [ntype] = tramp_size;
4162                                 }
4163                         }
4164                 }
4165
4166                 /* Reserve some entries at the end of the GOT for our use */
4167                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4168         }
4169
4170         acfg->got_offset += acfg->num_trampoline_got_entries;
4171 }
4172
4173 static gboolean
4174 str_begins_with (const char *str1, const char *str2)
4175 {
4176         int len = strlen (str2);
4177         return strncmp (str1, str2, len) == 0;
4178 }
4179
4180 static void
4181 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4182 {
4183         gchar **args, **ptr;
4184
4185         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4186         for (ptr = args; ptr && *ptr; ptr ++) {
4187                 const char *arg = *ptr;
4188
4189                 if (str_begins_with (arg, "outfile=")) {
4190                         opts->outfile = g_strdup (arg + strlen ("outfile="));
4191                 } else if (str_begins_with (arg, "save-temps")) {
4192                         opts->save_temps = TRUE;
4193                 } else if (str_begins_with (arg, "keep-temps")) {
4194                         opts->save_temps = TRUE;
4195                 } else if (str_begins_with (arg, "write-symbols")) {
4196                         opts->write_symbols = TRUE;
4197                 } else if (str_begins_with (arg, "metadata-only")) {
4198                         opts->metadata_only = TRUE;
4199                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4200                         opts->bind_to_runtime_version = TRUE;
4201                 } else if (str_begins_with (arg, "full")) {
4202                         opts->full_aot = TRUE;
4203                 } else if (str_begins_with (arg, "threads=")) {
4204                         opts->nthreads = atoi (arg + strlen ("threads="));
4205                 } else if (str_begins_with (arg, "static")) {
4206                         opts->static_link = TRUE;
4207                         opts->no_dlsym = TRUE;
4208                 } else if (str_begins_with (arg, "asmonly")) {
4209                         opts->asm_only = TRUE;
4210                 } else if (str_begins_with (arg, "asmwriter")) {
4211                         opts->asm_writer = TRUE;
4212                 } else if (str_begins_with (arg, "nodebug")) {
4213                         opts->nodebug = TRUE;
4214                 } else if (str_begins_with (arg, "ntrampolines=")) {
4215                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4216                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4217                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4218                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4219                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4220                 } else if (str_begins_with (arg, "autoreg")) {
4221                         opts->autoreg = TRUE;
4222                 } else if (str_begins_with (arg, "tool-prefix=")) {
4223                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4224                 } else if (str_begins_with (arg, "soft-debug")) {
4225                         opts->soft_debug = TRUE;
4226                 } else if (str_begins_with (arg, "print-skipped")) {
4227                         opts->print_skipped_methods = TRUE;
4228                 } else if (str_begins_with (arg, "stats")) {
4229                         opts->stats = TRUE;
4230                 } else {
4231                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4232                         exit (1);
4233                 }
4234         }
4235
4236         g_strfreev (args);
4237 }
4238
4239 static void
4240 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4241 {
4242         MonoMethod *method = (MonoMethod*)key;
4243         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4244         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4245         MonoAotCompile *acfg = user_data;
4246
4247         new_ji->image = ji->image;
4248         new_ji->token = ji->token;
4249         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4250 }
4251
4252 static gboolean
4253 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4254 {
4255         if (klass->type_token)
4256                 return TRUE;
4257         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4258                 return TRUE;
4259         if (klass->rank)
4260                 return can_encode_class (acfg, klass->element_class);
4261         return FALSE;
4262 }
4263
4264 static gboolean
4265 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4266 {
4267         switch (patch_info->type) {
4268         case MONO_PATCH_INFO_METHOD:
4269         case MONO_PATCH_INFO_METHODCONST: {
4270                 MonoMethod *method = patch_info->data.method;
4271
4272                 if (method->wrapper_type) {
4273                         switch (method->wrapper_type) {
4274                         case MONO_WRAPPER_NONE:
4275                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4276                         case MONO_WRAPPER_XDOMAIN_INVOKE:
4277                         case MONO_WRAPPER_STFLD:
4278                         case MONO_WRAPPER_LDFLD:
4279                         case MONO_WRAPPER_LDFLDA:
4280                         case MONO_WRAPPER_LDFLD_REMOTE:
4281                         case MONO_WRAPPER_STFLD_REMOTE:
4282                         case MONO_WRAPPER_STELEMREF:
4283                         case MONO_WRAPPER_ISINST:
4284                         case MONO_WRAPPER_PROXY_ISINST:
4285                         case MONO_WRAPPER_ALLOC:
4286                         case MONO_WRAPPER_REMOTING_INVOKE:
4287                         case MONO_WRAPPER_UNKNOWN:
4288                         case MONO_WRAPPER_WRITE_BARRIER:
4289                                 break;
4290                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
4291                                 if (!strcmp (method->name, "ElementAddr"))
4292                                         return TRUE;
4293                                 else
4294                                         return FALSE;
4295                         default:
4296                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4297                                 return FALSE;
4298                         }
4299                 } else {
4300                         if (!method->token) {
4301                                 /* The method is part of a constructed type like Int[,].Set (). */
4302                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4303                                         if (method->klass->rank)
4304                                                 return TRUE;
4305                                         return FALSE;
4306                                 }
4307                         }
4308                 }
4309                 break;
4310         }
4311         case MONO_PATCH_INFO_VTABLE:
4312         case MONO_PATCH_INFO_CLASS_INIT:
4313         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4314         case MONO_PATCH_INFO_CLASS:
4315         case MONO_PATCH_INFO_IID:
4316         case MONO_PATCH_INFO_ADJUSTED_IID:
4317                 if (!can_encode_class (acfg, patch_info->data.klass)) {
4318                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4319                         return FALSE;
4320                 }
4321                 break;
4322         case MONO_PATCH_INFO_RGCTX_FETCH: {
4323                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4324
4325                 if (!can_encode_patch (acfg, entry->data))
4326                         return FALSE;
4327                 break;
4328         }
4329         default:
4330                 break;
4331         }
4332
4333         return TRUE;
4334 }
4335
4336 /*
4337  * compile_method:
4338  *
4339  *   AOT compile a given method.
4340  * This function might be called by multiple threads, so it must be thread-safe.
4341  */
4342 static void
4343 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4344 {
4345         MonoCompile *cfg;
4346         MonoJumpInfo *patch_info;
4347         gboolean skip;
4348         int index, depth;
4349         MonoMethod *wrapped;
4350
4351         if (acfg->aot_opts.metadata_only)
4352                 return;
4353
4354         mono_acfg_lock (acfg);
4355         index = get_method_index (acfg, method);
4356         mono_acfg_unlock (acfg);
4357
4358         /* fixme: maybe we can also precompile wrapper methods */
4359         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4360                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4361                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4362                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4363                 return;
4364         }
4365
4366         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4367                 return;
4368
4369         wrapped = mono_marshal_method_from_wrapper (method);
4370         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4371                 // FIXME: The wrapper should be generic too, but it is not
4372                 return;
4373
4374         InterlockedIncrement (&acfg->stats.mcount);
4375
4376 #if 0
4377         if (method->is_generic || method->klass->generic_container) {
4378                 InterlockedIncrement (&acfg->stats.genericcount);
4379                 return;
4380         }
4381 #endif
4382
4383         //acfg->aot_opts.print_skipped_methods = TRUE;
4384
4385         /*
4386          * Since these methods are the only ones which are compiled with
4387          * AOT support, and they are not used by runtime startup/shutdown code,
4388          * the runtime will not see AOT methods during AOT compilation,so it
4389          * does not need to support them by creating a fake GOT etc.
4390          */
4391         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4392         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4393                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4394                 InterlockedIncrement (&acfg->stats.genericcount);
4395                 return;
4396         }
4397         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4398                 /* Let the exception happen at runtime */
4399                 return;
4400         }
4401
4402         if (cfg->disable_aot) {
4403                 if (acfg->aot_opts.print_skipped_methods)
4404                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4405                 InterlockedIncrement (&acfg->stats.ocount);
4406                 mono_destroy_compile (cfg);
4407                 return;
4408         }
4409
4410         /* Nullify patches which need no aot processing */
4411         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4412                 switch (patch_info->type) {
4413                 case MONO_PATCH_INFO_LABEL:
4414                 case MONO_PATCH_INFO_BB:
4415                         patch_info->type = MONO_PATCH_INFO_NONE;
4416                         break;
4417                 default:
4418                         break;
4419                 }
4420         }
4421
4422         /* Collect method->token associations from the cfg */
4423         mono_acfg_lock (acfg);
4424         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4425         mono_acfg_unlock (acfg);
4426
4427         /*
4428          * Check for absolute addresses.
4429          */
4430         skip = FALSE;
4431         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4432                 switch (patch_info->type) {
4433                 case MONO_PATCH_INFO_ABS:
4434                         /* unable to handle this */
4435                         skip = TRUE;    
4436                         break;
4437                 default:
4438                         break;
4439                 }
4440         }
4441
4442         if (skip) {
4443                 if (acfg->aot_opts.print_skipped_methods)
4444                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4445                 InterlockedIncrement (&acfg->stats.abscount);
4446                 mono_destroy_compile (cfg);
4447                 return;
4448         }
4449
4450         /* Lock for the rest of the code */
4451         mono_acfg_lock (acfg);
4452
4453         /*
4454          * Check for methods/klasses we can't encode.
4455          */
4456         skip = FALSE;
4457         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4458                 if (!can_encode_patch (acfg, patch_info))
4459                         skip = TRUE;
4460         }
4461
4462         if (skip) {
4463                 if (acfg->aot_opts.print_skipped_methods)
4464                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4465                 acfg->stats.ocount++;
4466                 mono_destroy_compile (cfg);
4467                 mono_acfg_unlock (acfg);
4468                 return;
4469         }
4470
4471         /* Adds generic instances referenced by this method */
4472         /* 
4473          * The depth is used to avoid infinite loops when generic virtual recursion is 
4474          * encountered.
4475          */
4476         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4477         if (depth < 32) {
4478                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4479                         switch (patch_info->type) {
4480                         case MONO_PATCH_INFO_METHOD: {
4481                                 MonoMethod *m = patch_info->data.method;
4482                                 if (m->is_inflated) {
4483                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
4484                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
4485                                                 !method_has_type_vars (m)) {
4486                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4487                                                         if (acfg->aot_opts.full_aot)
4488                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4489                                                 } else {
4490                                                         add_extra_method_with_depth (acfg, m, depth + 1);
4491                                                 }
4492                                         }
4493                                         add_generic_class_with_depth (acfg, m->klass, depth + 5);
4494                                 }
4495                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4496                                         add_extra_method_with_depth (acfg, m, depth + 1);
4497                                 break;
4498                         }
4499                         case MONO_PATCH_INFO_VTABLE: {
4500                                 MonoClass *klass = patch_info->data.klass;
4501
4502                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4503                                         add_generic_class_with_depth (acfg, klass, depth + 5);
4504                                 break;
4505                         }
4506                         default:
4507                                 break;
4508                         }
4509                 }
4510         }
4511
4512         /* Determine whenever the method has GOT slots */
4513         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4514                 switch (patch_info->type) {
4515                 case MONO_PATCH_INFO_GOT_OFFSET:
4516                 case MONO_PATCH_INFO_NONE:
4517                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4518                         break;
4519                 case MONO_PATCH_INFO_IMAGE:
4520                         /* The assembly is stored in GOT slot 0 */
4521                         if (patch_info->data.image != acfg->image)
4522                                 cfg->has_got_slots = TRUE;
4523                         break;
4524                 default:
4525                         if (!is_plt_patch (patch_info))
4526                                 cfg->has_got_slots = TRUE;
4527                         break;
4528                 }
4529         }
4530
4531         if (!cfg->has_got_slots)
4532                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4533
4534         /* 
4535          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4536          */
4537         /* Make a copy of the patch info which is in the mempool */
4538         {
4539                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4540
4541                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4542                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4543
4544                         if (!patches)
4545                                 patches = new_patch_info;
4546                         else
4547                                 patches_end->next = new_patch_info;
4548                         patches_end = new_patch_info;
4549                 }
4550                 cfg->patch_info = patches;
4551         }
4552         /* Make a copy of the unwind info */
4553         {
4554                 GSList *l, *unwind_ops;
4555                 MonoUnwindOp *op;
4556
4557                 unwind_ops = NULL;
4558                 for (l = cfg->unwind_ops; l; l = l->next) {
4559                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4560                         memcpy (op, l->data, sizeof (MonoUnwindOp));
4561                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4562                 }
4563                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4564         }
4565         /* Make a copy of the argument/local info */
4566         {
4567                 MonoInst **args, **locals;
4568                 MonoMethodSignature *sig;
4569                 MonoMethodHeader *header;
4570                 int i;
4571                 
4572                 sig = mono_method_signature (method);
4573                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4574                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4575                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4576                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4577                 }
4578                 cfg->args = args;
4579
4580                 header = mono_method_get_header (method);
4581                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4582                 for (i = 0; i < header->num_locals; ++i) {
4583                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4584                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4585                 }
4586                 cfg->locals = locals;
4587         }
4588
4589         /* Free some fields used by cfg to conserve memory */
4590         mono_mempool_destroy (cfg->mempool);
4591         cfg->mempool = NULL;
4592         g_free (cfg->varinfo);
4593         cfg->varinfo = NULL;
4594         g_free (cfg->vars);
4595         cfg->vars = NULL;
4596         if (cfg->rs) {
4597                 mono_regstate_free (cfg->rs);
4598                 cfg->rs = NULL;
4599         }
4600
4601         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
4602
4603         while (index >= acfg->cfgs_size) {
4604                 MonoCompile **new_cfgs;
4605                 int new_size;
4606
4607                 new_size = acfg->cfgs_size * 2;
4608                 new_cfgs = g_new0 (MonoCompile*, new_size);
4609                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4610                 g_free (acfg->cfgs);
4611                 acfg->cfgs = new_cfgs;
4612                 acfg->cfgs_size = new_size;
4613         }
4614         acfg->cfgs [index] = cfg;
4615
4616         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4617
4618         /*
4619         if (cfg->orig_method->wrapper_type)
4620                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4621         */
4622
4623         mono_acfg_unlock (acfg);
4624
4625         InterlockedIncrement (&acfg->stats.ccount);
4626 }
4627  
4628 static void
4629 compile_thread_main (gpointer *user_data)
4630 {
4631         MonoDomain *domain = user_data [0];
4632         MonoAotCompile *acfg = user_data [1];
4633         GPtrArray *methods = user_data [2];
4634         int i;
4635
4636         mono_thread_attach (domain);
4637
4638         for (i = 0; i < methods->len; ++i)
4639                 compile_method (acfg, g_ptr_array_index (methods, i));
4640 }
4641
4642 static void
4643 load_profile_files (MonoAotCompile *acfg)
4644 {
4645         FILE *infile;
4646         char *tmp;
4647         int file_index, res, method_index, i;
4648         char ver [256];
4649         guint32 token;
4650         GList *unordered;
4651
4652         file_index = 0;
4653         while (TRUE) {
4654                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4655
4656                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4657                         g_free (tmp);
4658                         break;
4659                 }
4660
4661                 infile = fopen (tmp, "r");
4662                 g_assert (infile);
4663
4664                 printf ("Using profile data file '%s'\n", tmp);
4665                 g_free (tmp);
4666
4667                 file_index ++;
4668
4669                 res = fscanf (infile, "%32s\n", ver);
4670                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4671                         printf ("Profile file has wrong version or invalid.\n");
4672                         fclose (infile);
4673                         continue;
4674                 }
4675
4676                 while (TRUE) {
4677                         char name [1024];
4678                         MonoMethodDesc *desc;
4679                         MonoMethod *method;
4680
4681                         if (fgets (name, 1023, infile) == NULL)
4682                                 break;
4683
4684                         /* Kill the newline */
4685                         if (strlen (name) > 0)
4686                                 name [strlen (name) - 1] = '\0';
4687
4688                         desc = mono_method_desc_new (name, TRUE);
4689
4690                         method = mono_method_desc_search_in_image (desc, acfg->image);
4691
4692                         if (method && mono_method_get_token (method)) {
4693                                 token = mono_method_get_token (method);
4694                                 method_index = mono_metadata_token_index (token) - 1;
4695
4696                                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4697                                         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4698                                 }
4699                         } else {
4700                                 //printf ("No method found matching '%s'.\n", name);
4701                         }
4702                 }
4703                 fclose (infile);
4704         }
4705
4706         /* Add missing methods */
4707         unordered = NULL;
4708         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4709                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4710                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4711         }
4712         unordered = g_list_reverse (unordered);
4713         if (acfg->method_order)
4714                 g_list_last (acfg->method_order)->next = unordered;
4715         else
4716                 acfg->method_order = unordered;
4717 }
4718  
4719 /* Used by the LLVM backend */
4720 guint32
4721 mono_aot_get_got_offset (MonoJumpInfo *ji)
4722 {
4723         return get_got_offset (llvm_acfg, ji);
4724 }
4725
4726 char*
4727 mono_aot_get_method_name (MonoCompile *cfg)
4728 {
4729         guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4730
4731         return g_strdup_printf ("m_%x", method_index);
4732 }
4733
4734 char*
4735 mono_aot_get_method_debug_name (MonoCompile *cfg)
4736 {
4737         return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4738 }
4739
4740 char*
4741 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4742 {
4743         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4744         MonoPltEntry *plt_entry;
4745
4746         ji->type = type;
4747         ji->data.target = data;
4748
4749         if (!can_encode_patch (llvm_acfg, ji))
4750                 return NULL;
4751
4752         plt_entry = get_plt_entry (llvm_acfg, ji);
4753
4754         return g_strdup_printf (plt_entry->symbol);
4755 }
4756
4757 MonoJumpInfo*
4758 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4759 {
4760         MonoJumpInfo *res;
4761
4762         mono_acfg_lock (llvm_acfg);
4763         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4764         mono_acfg_unlock (llvm_acfg);
4765
4766         return res;
4767 }
4768
4769 #ifdef ENABLE_LLVM
4770
4771 /*
4772  * emit_llvm_file:
4773  *
4774  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4775  * tools.
4776  */
4777 static void
4778 emit_llvm_file (MonoAotCompile *acfg)
4779 {
4780         char *command, *opts;
4781         int i;
4782         MonoJumpInfo *patch_info;
4783         const char *llc_extra_args;
4784
4785         /*
4786          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4787          * to it.
4788          */
4789
4790         /* Compute the final size of the got */
4791         for (i = 0; i < acfg->nmethods; ++i) {
4792                 if (acfg->cfgs [i]) {
4793                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4794                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4795                                         if (!is_plt_patch (patch_info))
4796                                                 get_got_offset (acfg, patch_info);
4797                                         else
4798                                                 get_plt_entry (acfg, patch_info);
4799                                 }
4800                         }
4801                 }
4802         }
4803
4804         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4805
4806         if (acfg->aot_opts.full_aot) {
4807                 int ntype;
4808
4809                 /* 
4810                  * Need to add the got entries used by the trampolines.
4811                  * This is only a conservative approximation.
4812                  */
4813                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4814                         /* For the generic + rgctx trampolines */
4815                         acfg->final_got_size += 200;
4816                         /* For the specific trampolines */
4817                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4818                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4819                 }
4820         }
4821
4822
4823         mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4824
4825         /*
4826          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4827          * a lot of time, and doesn't seem to save much space.
4828          * The following optimizations cannot be enabled:
4829          * - 'tailcallelim'
4830          * - 'jump-threading' changes our blockaddress references to int constants.
4831          * The opt list below was produced by taking the output of:
4832          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4833          * then removing tailcallelim + the global opts, and adding a second gvn.
4834          */
4835         opts = g_strdup ("-instcombine -simplifycfg");
4836         opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -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 -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
4837 #if 1
4838         command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4839         printf ("Executing opt: %s\n", command);
4840         if (system (command) != 0) {
4841                 exit (1);
4842         }
4843 #endif
4844         g_free (opts);
4845
4846 #if !LLVM_CHECK_VERSION(2, 8)
4847         /* LLVM 2.8 removed the -f flag ??? */
4848         llc_extra_args = "-f";
4849 #else
4850         llc_extra_args = "";
4851 #endif
4852         command = g_strdup_printf ("llc %s %s -relocation-model=pic -unwind-tables -o %s temp.opt.bc", LLC_TARGET_ARGS, llc_extra_args, acfg->tmpfname);
4853
4854         printf ("Executing llc: %s\n", command);
4855
4856         if (system (command) != 0) {
4857                 exit (1);
4858         }
4859 }
4860 #endif
4861
4862 static void
4863 emit_code (MonoAotCompile *acfg)
4864 {
4865         int i;
4866         char symbol [256];
4867         char end_symbol [256];
4868         GList *l;
4869
4870 #if defined(TARGET_POWERPC64)
4871         sprintf (symbol, ".Lgot_addr");
4872         emit_section_change (acfg, ".text", 0);
4873         emit_alignment (acfg, 8);
4874         emit_label (acfg, symbol);
4875         emit_pointer (acfg, acfg->got_symbol);
4876 #endif
4877
4878         /* 
4879          * This global symbol is used to compute the address of each method using the
4880          * code_offsets array. It is also used to compute the memory ranges occupied by
4881          * AOT code, so it must be equal to the address of the first emitted method.
4882          */
4883         sprintf (symbol, "methods");
4884         emit_section_change (acfg, ".text", 0);
4885         emit_global (acfg, symbol, TRUE);
4886         emit_alignment (acfg, 8);
4887         if (acfg->llvm) {
4888                 for (i = 0; i < acfg->nmethods; ++i) {
4889                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4890                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4891                                 break;
4892                         }
4893                 }
4894                 if (i == acfg->nmethods)
4895                         /* No LLVM compiled methods */
4896                         emit_label (acfg, symbol);
4897         } else {
4898                 emit_label (acfg, symbol);
4899         }
4900
4901         /* 
4902          * Emit some padding so the local symbol for the first method doesn't have the
4903          * same address as 'methods'.
4904          */
4905         emit_zero_bytes (acfg, 16);
4906
4907         for (l = acfg->method_order; l != NULL; l = l->next) {
4908                 MonoCompile *cfg;
4909                 MonoMethod *method;
4910
4911                 i = GPOINTER_TO_UINT (l->data);
4912
4913                 cfg = acfg->cfgs [i];
4914
4915                 if (!cfg)
4916                         continue;
4917
4918                 method = cfg->orig_method;
4919
4920                 /* Emit unbox trampoline */
4921                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4922                         char call_target [256];
4923
4924                         if (!method->wrapper_type && !method->is_inflated) {
4925                                 g_assert (method->token);
4926                                 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4927                         } else {
4928                                 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4929                         }
4930
4931                         emit_section_change (acfg, ".text", 0);
4932 #ifdef __native_client_codegen__
4933                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4934 #endif
4935                         emit_global (acfg, symbol, TRUE);
4936                         emit_label (acfg, symbol);
4937
4938                         sprintf (call_target, "%s", cfg->asm_symbol);
4939
4940                         arch_emit_unbox_trampoline (acfg, cfg->orig_method, call_target);
4941                 }
4942
4943                 if (cfg->compile_llvm)
4944                         acfg->stats.llvm_count ++;
4945                 else
4946                         emit_method_code (acfg, cfg);
4947         }
4948
4949         sprintf (symbol, "methods_end");
4950         emit_section_change (acfg, ".text", 0);
4951         emit_global (acfg, symbol, FALSE);
4952         emit_alignment (acfg, 8);
4953         emit_label (acfg, symbol);
4954
4955         sprintf (symbol, "code_offsets");
4956         emit_section_change (acfg, RODATA_SECT, 1);
4957         emit_global (acfg, symbol, FALSE);
4958         emit_alignment (acfg, 8);
4959         emit_label (acfg, symbol);
4960
4961         acfg->stats.offsets_size += acfg->nmethods * 4;
4962
4963         sprintf (end_symbol, "methods");
4964         for (i = 0; i < acfg->nmethods; ++i) {
4965                 if (acfg->cfgs [i]) {
4966                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4967                 } else {
4968                         emit_int32 (acfg, 0xffffffff);
4969                 }
4970         }
4971         emit_line (acfg);
4972 }
4973
4974 static void
4975 emit_info (MonoAotCompile *acfg)
4976 {
4977         int i;
4978         char symbol [256];
4979         GList *l;
4980         gint32 *offsets;
4981
4982         offsets = g_new0 (gint32, acfg->nmethods);
4983
4984         for (l = acfg->method_order; l != NULL; l = l->next) {
4985                 i = GPOINTER_TO_UINT (l->data);
4986
4987                 if (acfg->cfgs [i]) {
4988                         emit_method_info (acfg, acfg->cfgs [i]);
4989                         offsets [i] = acfg->cfgs [i]->method_info_offset;
4990                 } else {
4991                         offsets [i] = 0;
4992                 }
4993         }
4994
4995         sprintf (symbol, "method_info_offsets");
4996         emit_section_change (acfg, RODATA_SECT, 1);
4997         emit_global (acfg, symbol, FALSE);
4998         emit_alignment (acfg, 8);
4999         emit_label (acfg, symbol);
5000
5001         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5002
5003         g_free (offsets);
5004 }
5005
5006 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5007
5008 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5009 #define mix(a,b,c) { \
5010         a -= c;  a ^= rot(c, 4);  c += b; \
5011         b -= a;  b ^= rot(a, 6);  a += c; \
5012         c -= b;  c ^= rot(b, 8);  b += a; \
5013         a -= c;  a ^= rot(c,16);  c += b; \
5014         b -= a;  b ^= rot(a,19);  a += c; \
5015         c -= b;  c ^= rot(b, 4);  b += a; \
5016 }
5017 #define final(a,b,c) { \
5018         c ^= b; c -= rot(b,14); \
5019         a ^= c; a -= rot(c,11); \
5020         b ^= a; b -= rot(a,25); \
5021         c ^= b; c -= rot(b,16); \
5022         a ^= c; a -= rot(c,4);  \
5023         b ^= a; b -= rot(a,14); \
5024         c ^= b; c -= rot(b,24); \
5025 }
5026
5027 static guint
5028 mono_aot_type_hash (MonoType *t1)
5029 {
5030         guint hash = t1->type;
5031
5032         hash |= t1->byref << 6; /* do not collide with t1->type values */
5033         switch (t1->type) {
5034         case MONO_TYPE_VALUETYPE:
5035         case MONO_TYPE_CLASS:
5036         case MONO_TYPE_SZARRAY:
5037                 /* check if the distribution is good enough */
5038                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5039         case MONO_TYPE_PTR:
5040                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5041         case MONO_TYPE_ARRAY:
5042                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5043         case MONO_TYPE_GENERICINST:
5044                 return ((hash << 5) - hash) ^ 0;
5045         }
5046         return hash;
5047 }
5048
5049 /*
5050  * mono_aot_method_hash:
5051  *
5052  *   Return a hash code for methods which only depends on metadata.
5053  */
5054 guint32
5055 mono_aot_method_hash (MonoMethod *method)
5056 {
5057         MonoMethodSignature *sig;
5058         MonoClass *klass;
5059         int i, hindex;
5060         int hashes_count;
5061         guint32 *hashes_start, *hashes;
5062         guint32 a, b, c;
5063         MonoGenericInst *ginst = NULL;
5064
5065         /* Similar to the hash in mono_method_get_imt_slot () */
5066
5067         sig = mono_method_signature (method);
5068
5069         if (method->is_inflated)
5070                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5071
5072         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5073         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5074         hashes = hashes_start;
5075
5076         /* Some wrappers are assigned to random classes */
5077         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5078                 klass = method->klass;
5079         else
5080                 klass = mono_defaults.object_class;
5081
5082         if (!method->wrapper_type) {
5083                 char *full_name = mono_type_full_name (&klass->byval_arg);
5084
5085                 hashes [0] = mono_metadata_str_hash (full_name);
5086                 hashes [1] = 0;
5087                 g_free (full_name);
5088         } else {
5089                 hashes [0] = mono_metadata_str_hash (klass->name);
5090                 hashes [1] = mono_metadata_str_hash (klass->name_space);
5091         }
5092         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5093                 /* The method name includes a stringified pointer */
5094                 hashes [2] = 0;
5095         else
5096                 hashes [2] = mono_metadata_str_hash (method->name);
5097         hashes [3] = method->wrapper_type;
5098         hashes [4] = mono_aot_type_hash (sig->ret);
5099         hindex = 5;
5100         for (i = 0; i < sig->param_count; i++) {
5101                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5102         }
5103         if (ginst) {
5104                 for (i = 0; i < ginst->type_argc; ++i)
5105                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5106         }               
5107         g_assert (hindex == hashes_count);
5108
5109         /* Setup internal state */
5110         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5111
5112         /* Handle most of the hashes */
5113         while (hashes_count > 3) {
5114                 a += hashes [0];
5115                 b += hashes [1];
5116                 c += hashes [2];
5117                 mix (a,b,c);
5118                 hashes_count -= 3;
5119                 hashes += 3;
5120         }
5121
5122         /* Handle the last 3 hashes (all the case statements fall through) */
5123         switch (hashes_count) { 
5124         case 3 : c += hashes [2];
5125         case 2 : b += hashes [1];
5126         case 1 : a += hashes [0];
5127                 final (a,b,c);
5128         case 0: /* nothing left to add */
5129                 break;
5130         }
5131         
5132         free (hashes_start);
5133         
5134         return c;
5135 }
5136 #undef rot
5137 #undef mix
5138 #undef final
5139
5140 /*
5141  * mono_aot_wrapper_name:
5142  *
5143  *   Return a string which uniqely identifies the given wrapper method.
5144  */
5145 char*
5146 mono_aot_wrapper_name (MonoMethod *method)
5147 {
5148         char *name, *tmpsig, *klass_desc;
5149
5150         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5151
5152         switch (method->wrapper_type) {
5153         case MONO_WRAPPER_RUNTIME_INVOKE:
5154                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5155                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5156                 else
5157                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5158                 break;
5159         default:
5160                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5161                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5162                 g_free (klass_desc);
5163                 break;
5164         }
5165
5166         g_free (tmpsig);
5167
5168         return name;
5169 }
5170
5171 /*
5172  * mono_aot_get_array_helper_from_wrapper;
5173  *
5174  * Get the helper method in Array called by an array wrapper method.
5175  */
5176 MonoMethod*
5177 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5178 {
5179         MonoMethod *m;
5180         const char *prefix;
5181         MonoGenericContext ctx;
5182         MonoType *args [16];
5183         char *mname, *iname, *s, *s2, *helper_name = NULL;
5184
5185         prefix = "System.Collections.Generic";
5186         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5187         s2 = strstr (s, "`1.");
5188         g_assert (s2);
5189         s2 [0] = '\0';
5190         iname = s;
5191         mname = s2 + 3;
5192
5193         //printf ("X: %s %s\n", iname, mname);
5194
5195         if (!strcmp (iname, "IList"))
5196                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5197         else
5198                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5199         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5200         g_assert (m);
5201         g_free (helper_name);
5202         g_free (s);
5203
5204         if (m->is_generic) {
5205                 memset (&ctx, 0, sizeof (ctx));
5206                 args [0] = &method->klass->element_class->byval_arg;
5207                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5208                 m = mono_class_inflate_generic_method (m, &ctx);
5209         }
5210
5211         return m;
5212 }
5213
5214 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5215
5216 typedef struct HashEntry {
5217     guint32 key, value, index;
5218         struct HashEntry *next;
5219 } HashEntry;
5220
5221 /*
5222  * emit_extra_methods:
5223  *
5224  * Emit methods which are not in the METHOD table, like wrappers.
5225  */
5226 static void
5227 emit_extra_methods (MonoAotCompile *acfg)
5228 {
5229         int i, table_size, buf_size;
5230         char symbol [256];
5231         guint8 *p, *buf;
5232         guint32 *info_offsets;
5233         guint32 hash;
5234         GPtrArray *table;
5235         HashEntry *entry, *new_entry;
5236         int nmethods, max_chain_length;
5237         int *chain_lengths;
5238
5239         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5240
5241         /* Emit method info */
5242         nmethods = 0;
5243         for (i = 0; i < acfg->extra_methods->len; ++i) {
5244                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5245                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5246                 char *name;
5247
5248                 if (!cfg)
5249                         continue;
5250
5251                 buf_size = 10240;
5252                 p = buf = g_malloc (buf_size);
5253
5254                 nmethods ++;
5255
5256                 method = cfg->method_to_register;
5257
5258                 name = NULL;
5259                 if (method->wrapper_type) {
5260                         /* 
5261                          * We encode some wrappers using their name, since encoding them
5262                          * directly would be difficult. This also avoids creating the wrapper
5263                          * methods at runtime, since they are not needed anyway.
5264                          */
5265                         switch (method->wrapper_type) {
5266                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5267                         case MONO_WRAPPER_SYNCHRONIZED:
5268                                 /* encode_method_ref () can handle these */
5269                                 break;
5270                         case MONO_WRAPPER_RUNTIME_INVOKE:
5271                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5272                                         /* Direct wrapper, encode normally */
5273                                         break;
5274                                 /* Fall through */
5275                         default:
5276                                 name = mono_aot_wrapper_name (method);
5277                                 break;
5278                         }
5279                 }
5280
5281                 if (name) {
5282                         encode_value (1, p, &p);
5283                         encode_value (method->wrapper_type, p, &p);
5284                         strcpy ((char*)p, name);
5285                         p += strlen (name ) + 1;
5286                         g_free (name);
5287                 } else {
5288                         encode_value (0, p, &p);
5289                         encode_method_ref (acfg, method, p, &p);
5290                 }
5291
5292                 g_assert ((p - buf) < buf_size);
5293
5294                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5295                 g_free (buf);
5296         }
5297
5298         /*
5299          * Construct a chained hash table for mapping indexes in extra_method_info to
5300          * method indexes.
5301          */
5302         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5303         table = g_ptr_array_sized_new (table_size);
5304         for (i = 0; i < table_size; ++i)
5305                 g_ptr_array_add (table, NULL);
5306         chain_lengths = g_new0 (int, table_size);
5307         max_chain_length = 0;
5308         for (i = 0; i < acfg->extra_methods->len; ++i) {
5309                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5310                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5311                 guint32 key, value;
5312
5313                 if (!cfg)
5314                         continue;
5315
5316                 key = info_offsets [i];
5317                 value = get_method_index (acfg, method);
5318
5319                 hash = mono_aot_method_hash (method) % table_size;
5320
5321                 chain_lengths [hash] ++;
5322                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5323
5324                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5325                 new_entry->key = key;
5326                 new_entry->value = value;
5327
5328                 entry = g_ptr_array_index (table, hash);
5329                 if (entry == NULL) {
5330                         new_entry->index = hash;
5331                         g_ptr_array_index (table, hash) = new_entry;
5332                 } else {
5333                         while (entry->next)
5334                                 entry = entry->next;
5335                         
5336                         entry->next = new_entry;
5337                         new_entry->index = table->len;
5338                         g_ptr_array_add (table, new_entry);
5339                 }
5340         }
5341
5342         //printf ("MAX: %d\n", max_chain_length);
5343
5344         /* Emit the table */
5345         sprintf (symbol, "extra_method_table");
5346         emit_section_change (acfg, RODATA_SECT, 0);
5347         emit_global (acfg, symbol, FALSE);
5348         emit_alignment (acfg, 8);
5349         emit_label (acfg, symbol);
5350
5351         emit_int32 (acfg, table_size);
5352         for (i = 0; i < table->len; ++i) {
5353                 HashEntry *entry = g_ptr_array_index (table, i);
5354
5355                 if (entry == NULL) {
5356                         emit_int32 (acfg, 0);
5357                         emit_int32 (acfg, 0);
5358                         emit_int32 (acfg, 0);
5359                 } else {
5360                         //g_assert (entry->key > 0);
5361                         emit_int32 (acfg, entry->key);
5362                         emit_int32 (acfg, entry->value);
5363                         if (entry->next)
5364                                 emit_int32 (acfg, entry->next->index);
5365                         else
5366                                 emit_int32 (acfg, 0);
5367                 }
5368         }
5369
5370         /* 
5371          * Emit a table reverse mapping method indexes to their index in extra_method_info.
5372          * This is used by mono_aot_find_jit_info ().
5373          */
5374         sprintf (symbol, "extra_method_info_offsets");
5375         emit_section_change (acfg, RODATA_SECT, 0);
5376         emit_global (acfg, symbol, FALSE);
5377         emit_alignment (acfg, 8);
5378         emit_label (acfg, symbol);
5379
5380         emit_int32 (acfg, acfg->extra_methods->len);
5381         for (i = 0; i < acfg->extra_methods->len; ++i) {
5382                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5383
5384                 emit_int32 (acfg, get_method_index (acfg, method));
5385                 emit_int32 (acfg, info_offsets [i]);
5386         }
5387 }       
5388
5389 static void
5390 emit_exception_info (MonoAotCompile *acfg)
5391 {
5392         int i;
5393         char symbol [256];
5394         gint32 *offsets;
5395
5396         offsets = g_new0 (gint32, acfg->nmethods);
5397         for (i = 0; i < acfg->nmethods; ++i) {
5398                 if (acfg->cfgs [i]) {
5399                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
5400                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
5401                 } else {
5402                         offsets [i] = 0;
5403                 }
5404         }
5405
5406         sprintf (symbol, "ex_info_offsets");
5407         emit_section_change (acfg, RODATA_SECT, 1);
5408         emit_global (acfg, symbol, FALSE);
5409         emit_alignment (acfg, 8);
5410         emit_label (acfg, symbol);
5411
5412         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5413         g_free (offsets);
5414 }
5415
5416 static void
5417 emit_unwind_info (MonoAotCompile *acfg)
5418 {
5419         int i;
5420         char symbol [128];
5421
5422         /* 
5423          * The unwind info contains a lot of duplicates so we emit each unique
5424          * entry once, and only store the offset from the start of the table in the
5425          * exception info.
5426          */
5427
5428         sprintf (symbol, "unwind_info");
5429         emit_section_change (acfg, RODATA_SECT, 1);
5430         emit_alignment (acfg, 8);
5431         emit_label (acfg, symbol);
5432         emit_global (acfg, symbol, FALSE);
5433
5434         for (i = 0; i < acfg->unwind_ops->len; ++i) {
5435                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5436                 guint8 *unwind_info;
5437                 guint32 unwind_info_len;
5438                 guint8 buf [16];
5439                 guint8 *p;
5440
5441                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5442
5443                 p = buf;
5444                 encode_value (unwind_info_len, p, &p);
5445                 emit_bytes (acfg, buf, p - buf);
5446                 emit_bytes (acfg, unwind_info, unwind_info_len);
5447
5448                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5449         }
5450 }
5451
5452 static void
5453 emit_class_info (MonoAotCompile *acfg)
5454 {
5455         int i;
5456         char symbol [256];
5457         gint32 *offsets;
5458
5459         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5460         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5461                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5462
5463         sprintf (symbol, "class_info_offsets");
5464         emit_section_change (acfg, RODATA_SECT, 1);
5465         emit_global (acfg, symbol, FALSE);
5466         emit_alignment (acfg, 8);
5467         emit_label (acfg, symbol);
5468
5469         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5470         g_free (offsets);
5471 }
5472
5473 typedef struct ClassNameTableEntry {
5474         guint32 token, index;
5475         struct ClassNameTableEntry *next;
5476 } ClassNameTableEntry;
5477
5478 static void
5479 emit_class_name_table (MonoAotCompile *acfg)
5480 {
5481         int i, table_size;
5482         guint32 token, hash;
5483         MonoClass *klass;
5484         GPtrArray *table;
5485         char *full_name;
5486         char symbol [256];
5487         ClassNameTableEntry *entry, *new_entry;
5488
5489         /*
5490          * Construct a chained hash table for mapping class names to typedef tokens.
5491          */
5492         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5493         table = g_ptr_array_sized_new (table_size);
5494         for (i = 0; i < table_size; ++i)
5495                 g_ptr_array_add (table, NULL);
5496         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5497                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5498                 klass = mono_class_get (acfg->image, token);
5499                 if (!klass)
5500                         continue;
5501                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5502                 hash = mono_metadata_str_hash (full_name) % table_size;
5503                 g_free (full_name);
5504
5505                 /* FIXME: Allocate from the mempool */
5506                 new_entry = g_new0 (ClassNameTableEntry, 1);
5507                 new_entry->token = token;
5508
5509                 entry = g_ptr_array_index (table, hash);
5510                 if (entry == NULL) {
5511                         new_entry->index = hash;
5512                         g_ptr_array_index (table, hash) = new_entry;
5513                 } else {
5514                         while (entry->next)
5515                                 entry = entry->next;
5516                         
5517                         entry->next = new_entry;
5518                         new_entry->index = table->len;
5519                         g_ptr_array_add (table, new_entry);
5520                 }
5521         }
5522
5523         /* Emit the table */
5524         sprintf (symbol, "class_name_table");
5525         emit_section_change (acfg, RODATA_SECT, 0);
5526         emit_global (acfg, symbol, FALSE);
5527         emit_alignment (acfg, 8);
5528         emit_label (acfg, symbol);
5529
5530         /* FIXME: Optimize memory usage */
5531         g_assert (table_size < 65000);
5532         emit_int16 (acfg, table_size);
5533         g_assert (table->len < 65000);
5534         for (i = 0; i < table->len; ++i) {
5535                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5536
5537                 if (entry == NULL) {
5538                         emit_int16 (acfg, 0);
5539                         emit_int16 (acfg, 0);
5540                 } else {
5541                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
5542                         if (entry->next)
5543                                 emit_int16 (acfg, entry->next->index);
5544                         else
5545                                 emit_int16 (acfg, 0);
5546                 }
5547         }
5548 }
5549
5550 static void
5551 emit_image_table (MonoAotCompile *acfg)
5552 {
5553         int i;
5554         char symbol [256];
5555
5556         /*
5557          * The image table is small but referenced in a lot of places.
5558          * So we emit it at once, and reference its elements by an index.
5559          */
5560
5561         sprintf (symbol, "mono_image_table");
5562         emit_section_change (acfg, RODATA_SECT, 1);
5563         emit_global (acfg, symbol, FALSE);
5564         emit_alignment (acfg, 8);
5565         emit_label (acfg, symbol);
5566
5567         emit_int32 (acfg, acfg->image_table->len);
5568         for (i = 0; i < acfg->image_table->len; i++) {
5569                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5570                 MonoAssemblyName *aname = &image->assembly->aname;
5571
5572                 /* FIXME: Support multi-module assemblies */
5573                 g_assert (image->assembly->image == image);
5574
5575                 emit_string (acfg, image->assembly_name);
5576                 emit_string (acfg, image->guid);
5577                 emit_string (acfg, aname->culture ? aname->culture : "");
5578                 emit_string (acfg, (const char*)aname->public_key_token);
5579
5580                 emit_alignment (acfg, 8);
5581                 emit_int32 (acfg, aname->flags);
5582                 emit_int32 (acfg, aname->major);
5583                 emit_int32 (acfg, aname->minor);
5584                 emit_int32 (acfg, aname->build);
5585                 emit_int32 (acfg, aname->revision);
5586         }
5587 }
5588
5589 static void
5590 emit_got_info (MonoAotCompile *acfg)
5591 {
5592         char symbol [256];
5593         int i, first_plt_got_patch, buf_size;
5594         guint8 *p, *buf;
5595         guint32 *got_info_offsets;
5596
5597         /* Add the patches needed by the PLT to the GOT */
5598         acfg->plt_got_offset_base = acfg->got_offset;
5599         first_plt_got_patch = acfg->got_patches->len;
5600         for (i = 1; i < acfg->plt_offset; ++i) {
5601                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5602
5603                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5604         }
5605
5606         acfg->got_offset += acfg->plt_offset;
5607
5608         /**
5609          * FIXME: 
5610          * - optimize offsets table.
5611          * - reduce number of exported symbols.
5612          * - emit info for a klass only once.
5613          * - determine when a method uses a GOT slot which is guaranteed to be already 
5614          *   initialized.
5615          * - clean up and document the code.
5616          * - use String.Empty in class libs.
5617          */
5618
5619         /* Encode info required to decode shared GOT entries */
5620         buf_size = acfg->got_patches->len * 128;
5621         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5622         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5623         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5624         /* Unused */
5625         if (acfg->plt_offset)
5626                 acfg->plt_got_info_offsets [0] = 0;
5627         for (i = 0; i < acfg->got_patches->len; ++i) {
5628                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5629
5630                 p = buf;
5631
5632                 encode_value (ji->type, p, &p);
5633                 encode_patch (acfg, ji, p, &p);
5634
5635                 g_assert (p - buf <= buf_size);
5636                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5637
5638                 if (i >= first_plt_got_patch)
5639                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5640                 acfg->stats.got_info_size += p - buf;
5641         }
5642
5643         /* Emit got_info_offsets table */
5644         sprintf (symbol, "got_info_offsets");
5645         emit_section_change (acfg, RODATA_SECT, 1);
5646         emit_global (acfg, symbol, FALSE);
5647         emit_alignment (acfg, 8);
5648         emit_label (acfg, symbol);
5649
5650         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5651         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5652 }
5653
5654 static void
5655 emit_got (MonoAotCompile *acfg)
5656 {
5657         char symbol [256];
5658
5659         if (!acfg->llvm) {
5660                 /* Don't make GOT global so accesses to it don't need relocations */
5661                 sprintf (symbol, "%s", acfg->got_symbol);
5662                 emit_section_change (acfg, ".bss", 0);
5663                 emit_alignment (acfg, 8);
5664                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5665                 emit_label (acfg, symbol);
5666                 if (acfg->got_offset > 0)
5667                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5668
5669                 sprintf (symbol, "got_end");
5670                 emit_label (acfg, symbol);
5671         }
5672
5673         sprintf (symbol, "mono_aot_got_addr");
5674         emit_section_change (acfg, ".data", 0);
5675         emit_global (acfg, symbol, FALSE);
5676         emit_alignment (acfg, 8);
5677         emit_label (acfg, symbol);
5678         emit_pointer (acfg, acfg->got_symbol);
5679 }
5680
5681 typedef struct GlobalsTableEntry {
5682         guint32 value, index;
5683         struct GlobalsTableEntry *next;
5684 } GlobalsTableEntry;
5685
5686 static void
5687 emit_globals_table (MonoAotCompile *acfg)
5688 {
5689         int i, table_size;
5690         guint32 hash;
5691         GPtrArray *table;
5692         char symbol [256];
5693         GlobalsTableEntry *entry, *new_entry;
5694
5695         /*
5696          * Construct a chained hash table for mapping global names to their index in
5697          * the globals table.
5698          */
5699         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5700         table = g_ptr_array_sized_new (table_size);
5701         for (i = 0; i < table_size; ++i)
5702                 g_ptr_array_add (table, NULL);
5703         for (i = 0; i < acfg->globals->len; ++i) {
5704                 char *name = g_ptr_array_index (acfg->globals, i);
5705
5706                 hash = mono_metadata_str_hash (name) % table_size;
5707
5708                 /* FIXME: Allocate from the mempool */
5709                 new_entry = g_new0 (GlobalsTableEntry, 1);
5710                 new_entry->value = i;
5711
5712                 entry = g_ptr_array_index (table, hash);
5713                 if (entry == NULL) {
5714                         new_entry->index = hash;
5715                         g_ptr_array_index (table, hash) = new_entry;
5716                 } else {
5717                         while (entry->next)
5718                                 entry = entry->next;
5719                         
5720                         entry->next = new_entry;
5721                         new_entry->index = table->len;
5722                         g_ptr_array_add (table, new_entry);
5723                 }
5724         }
5725
5726         /* Emit the table */
5727         sprintf (symbol, ".Lglobals_hash");
5728         emit_section_change (acfg, RODATA_SECT, 0);
5729         emit_alignment (acfg, 8);
5730         emit_label (acfg, symbol);
5731
5732         /* FIXME: Optimize memory usage */
5733         g_assert (table_size < 65000);
5734         emit_int16 (acfg, table_size);
5735         for (i = 0; i < table->len; ++i) {
5736                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5737
5738                 if (entry == NULL) {
5739                         emit_int16 (acfg, 0);
5740                         emit_int16 (acfg, 0);
5741                 } else {
5742                         emit_int16 (acfg, entry->value + 1);
5743                         if (entry->next)
5744                                 emit_int16 (acfg, entry->next->index);
5745                         else
5746                                 emit_int16 (acfg, 0);
5747                 }
5748         }
5749
5750         /* Emit the names */
5751         for (i = 0; i < acfg->globals->len; ++i) {
5752                 char *name = g_ptr_array_index (acfg->globals, i);
5753
5754                 sprintf (symbol, "name_%d", i);
5755                 emit_section_change (acfg, RODATA_SECT, 1);
5756                 emit_label (acfg, symbol);
5757                 emit_string (acfg, name);
5758         }
5759
5760         /* Emit the globals table */
5761         sprintf (symbol, ".Lglobals");
5762         emit_section_change (acfg, ".data", 0);
5763         /* This is not a global, since it is accessed by the init function */
5764         emit_alignment (acfg, 8);
5765         emit_label (acfg, symbol);
5766
5767         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5768         emit_pointer (acfg, symbol);
5769
5770         for (i = 0; i < acfg->globals->len; ++i) {
5771                 char *name = g_ptr_array_index (acfg->globals, i);
5772
5773                 sprintf (symbol, "name_%d", i);
5774                 emit_pointer (acfg, symbol);
5775
5776                 sprintf (symbol, "%s", name);
5777                 emit_pointer (acfg, symbol);
5778         }
5779         /* Null terminate the table */
5780         emit_int32 (acfg, 0);
5781         emit_int32 (acfg, 0);
5782 }
5783
5784 static void
5785 emit_globals (MonoAotCompile *acfg)
5786 {
5787         char *build_info;
5788
5789         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5790
5791         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5792
5793         if (acfg->aot_opts.bind_to_runtime_version) {
5794                 build_info = mono_get_runtime_build_info ();
5795                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5796                 g_free (build_info);
5797         } else {
5798                 emit_string_symbol (acfg, "mono_runtime_version", "");
5799         }
5800
5801         /* 
5802          * When static linking, we emit a global which will point to the symbol table.
5803          */
5804         if (acfg->aot_opts.static_link) {
5805                 char symbol [256];
5806                 char *p;
5807
5808                 /* Emit a string holding the assembly name */
5809                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5810
5811                 emit_globals_table (acfg);
5812
5813                 /* 
5814                  * Emit a global symbol which can be passed by an embedding app to
5815                  * mono_aot_register_module ().
5816                  */
5817 #if defined(__MACH__) && !defined(__native_client_codegen__)
5818                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5819 #else
5820                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5821 #endif
5822
5823                 /* Get rid of characters which cannot occur in symbols */
5824                 p = symbol;
5825                 for (p = symbol; *p; ++p) {
5826                         if (!(isalnum (*p) || *p == '_'))
5827                                 *p = '_';
5828                 }
5829                 acfg->static_linking_symbol = g_strdup (symbol);
5830                 emit_global_inner (acfg, symbol, FALSE);
5831                 emit_alignment (acfg, 8);
5832                 emit_label (acfg, symbol);
5833                 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5834                 emit_pointer (acfg, symbol);
5835         }
5836 }
5837
5838 static void
5839 emit_autoreg (MonoAotCompile *acfg)
5840 {
5841         char *symbol;
5842
5843         /*
5844          * Emit a function into the .ctor section which will be called by the ELF
5845          * loader to register this module with the runtime.
5846          */
5847         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5848                 return;
5849
5850         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5851
5852         arch_emit_autoreg (acfg, symbol);
5853
5854         g_free (symbol);
5855 }       
5856
5857 static void
5858 emit_mem_end (MonoAotCompile *acfg)
5859 {
5860         char symbol [128];
5861
5862         sprintf (symbol, "mem_end");
5863         emit_section_change (acfg, ".text", 1);
5864         emit_global (acfg, symbol, FALSE);
5865         emit_alignment (acfg, 8);
5866         emit_label (acfg, symbol);
5867 }
5868
5869 /*
5870  * Emit a structure containing all the information not stored elsewhere.
5871  */
5872 static void
5873 emit_file_info (MonoAotCompile *acfg)
5874 {
5875         char symbol [128];
5876         int i;
5877         int gc_name_offset;
5878         const char *gc_name;
5879
5880         /*
5881          * The managed allocators are GC specific, so can't use an AOT image created by one GC
5882          * in another.
5883          */
5884         gc_name = mono_gc_get_gc_name ();
5885         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
5886
5887         sprintf (symbol, "mono_aot_file_info");
5888         emit_section_change (acfg, ".data", 0);
5889         emit_alignment (acfg, 8);
5890         emit_label (acfg, symbol);
5891         emit_global (acfg, symbol, FALSE);
5892
5893         /* The data emitted here must match MonoAotFileInfo. */
5894         emit_int32 (acfg, acfg->plt_got_offset_base);
5895         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5896         emit_int32 (acfg, acfg->plt_offset);
5897         emit_int32 (acfg, acfg->nmethods);
5898         emit_int32 (acfg, acfg->flags);
5899         emit_int32 (acfg, acfg->opts);
5900         emit_int32 (acfg, gc_name_offset);
5901
5902         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5903                 emit_int32 (acfg, acfg->num_trampolines [i]);
5904         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5905                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5906         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5907                 emit_int32 (acfg, acfg->trampoline_size [i]);
5908 }
5909
5910 static void
5911 emit_blob (MonoAotCompile *acfg)
5912 {
5913         char symbol [128];
5914
5915         sprintf (symbol, "blob");
5916         emit_section_change (acfg, RODATA_SECT, 1);
5917         emit_global (acfg, symbol, FALSE);
5918         emit_alignment (acfg, 8);
5919         emit_label (acfg, symbol);
5920
5921         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5922 }
5923
5924 static void
5925 emit_dwarf_info (MonoAotCompile *acfg)
5926 {
5927 #ifdef EMIT_DWARF_INFO
5928         int i;
5929         char symbol [128], symbol2 [128];
5930
5931         /* DIEs for methods */
5932         for (i = 0; i < acfg->nmethods; ++i) {
5933                 MonoCompile *cfg = acfg->cfgs [i];
5934
5935                 if (!cfg)
5936                         continue;
5937
5938                 // FIXME: LLVM doesn't define .Lme_...
5939                 if (cfg->compile_llvm)
5940                         continue;
5941
5942                 sprintf (symbol, "%s", cfg->asm_symbol);
5943                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5944
5945                 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 ()));
5946         }
5947 #endif
5948 }
5949
5950 static void
5951 collect_methods (MonoAotCompile *acfg)
5952 {
5953         int i;
5954         MonoImage *image = acfg->image;
5955
5956         /* Collect methods */
5957         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5958                 MonoMethod *method;
5959                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5960
5961                 method = mono_get_method (acfg->image, token, NULL);
5962
5963                 if (!method) {
5964                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5965                         exit (1);
5966                 }
5967                         
5968                 /* Load all methods eagerly to skip the slower lazy loading code */
5969                 mono_class_setup_methods (method->klass);
5970
5971                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5972                         /* Compile the wrapper instead */
5973                         /* We do this here instead of add_wrappers () because it is easy to do it here */
5974                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5975                         method = wrapper;
5976                 }
5977
5978                 /* FIXME: Some mscorlib methods don't have debug info */
5979                 /*
5980                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5981                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5982                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5983                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5984                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5985                                 if (!mono_debug_lookup_method (method)) {
5986                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5987                                         exit (1);
5988                                 }
5989                         }
5990                 }
5991                 */
5992
5993                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5994                 add_method_with_index (acfg, method, i, FALSE);
5995                 acfg->method_index ++;
5996         }
5997
5998         add_generic_instances (acfg);
5999
6000         if (acfg->aot_opts.full_aot)
6001                 add_wrappers (acfg);
6002 }
6003
6004 static void
6005 compile_methods (MonoAotCompile *acfg)
6006 {
6007         int i, methods_len;
6008
6009         if (acfg->aot_opts.nthreads > 0) {
6010                 GPtrArray *frag;
6011                 int len, j;
6012                 GPtrArray *threads;
6013                 HANDLE handle;
6014                 gpointer *user_data;
6015                 MonoMethod **methods;
6016
6017                 methods_len = acfg->methods->len;
6018
6019                 len = acfg->methods->len / acfg->aot_opts.nthreads;
6020                 g_assert (len > 0);
6021                 /* 
6022                  * Partition the list of methods into fragments, and hand it to threads to
6023                  * process.
6024                  */
6025                 threads = g_ptr_array_new ();
6026                 /* Make a copy since acfg->methods is modified by compile_method () */
6027                 methods = g_new0 (MonoMethod*, methods_len);
6028                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6029                 for (i = 0; i < methods_len; ++i)
6030                         methods [i] = g_ptr_array_index (acfg->methods, i);
6031                 i = 0;
6032                 while (i < methods_len) {
6033                         frag = g_ptr_array_new ();
6034                         for (j = 0; j < len; ++j) {
6035                                 if (i < methods_len) {
6036                                         g_ptr_array_add (frag, methods [i]);
6037                                         i ++;
6038                                 }
6039                         }
6040
6041                         user_data = g_new0 (gpointer, 3);
6042                         user_data [0] = mono_domain_get ();
6043                         user_data [1] = acfg;
6044                         user_data [2] = frag;
6045                         
6046                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6047                         g_ptr_array_add (threads, handle);
6048                 }
6049                 g_free (methods);
6050
6051                 for (i = 0; i < threads->len; ++i) {
6052                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6053                 }
6054         } else {
6055                 methods_len = 0;
6056         }
6057
6058         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6059         for (i = methods_len; i < acfg->methods->len; ++i) {
6060                 /* This can new methods to acfg->methods */
6061                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6062         }
6063 }
6064
6065 static int
6066 compile_asm (MonoAotCompile *acfg)
6067 {
6068         char *command, *objfile;
6069         char *outfile_name, *tmp_outfile_name;
6070         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6071
6072 #if defined(TARGET_AMD64)
6073 #define AS_OPTIONS "--64"
6074 #elif defined(TARGET_POWERPC64)
6075 #define AS_OPTIONS "-a64 -mppc64"
6076 #define LD_OPTIONS "-m elf64ppc"
6077 #elif defined(sparc) && SIZEOF_VOID_P == 8
6078 #define AS_OPTIONS "-xarch=v9"
6079 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6080 #define AS_OPTIONS "-arch i386 -W"
6081 #else
6082 #define AS_OPTIONS ""
6083 #endif
6084
6085 #ifdef __native_client_codegen__
6086 #define AS_NAME "nacl-as"
6087 #else
6088 #define AS_NAME "as"
6089 #endif
6090
6091 #ifndef LD_OPTIONS
6092 #define LD_OPTIONS ""
6093 #endif
6094
6095 #ifdef ENABLE_LLVM
6096 #define EH_LD_OPTIONS "--eh-frame-hdr"
6097 #else
6098 #define EH_LD_OPTIONS ""
6099 #endif
6100
6101         if (acfg->aot_opts.asm_only) {
6102                 printf ("Output file: '%s'.\n", acfg->tmpfname);
6103                 if (acfg->aot_opts.static_link)
6104                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6105                 return 0;
6106         }
6107
6108         if (acfg->aot_opts.static_link) {
6109                 if (acfg->aot_opts.outfile)
6110                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6111                 else
6112                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
6113         } else {
6114                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6115         }
6116         command = g_strdup_printf ("%s%s %s %s -o %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->tmpfname, objfile);
6117         printf ("Executing the native assembler: %s\n", command);
6118         if (system (command) != 0) {
6119                 g_free (command);
6120                 g_free (objfile);
6121                 return 1;
6122         }
6123
6124         g_free (command);
6125
6126         if (acfg->aot_opts.static_link) {
6127                 printf ("Output file: '%s'.\n", objfile);
6128                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6129                 g_free (objfile);
6130                 return 0;
6131         }
6132
6133         if (acfg->aot_opts.outfile)
6134                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6135         else
6136                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6137
6138         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6139
6140 #if defined(sparc)
6141         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6142 #elif defined(__ppc__) && defined(__MACH__)
6143         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6144 #elif defined(HOST_WIN32)
6145         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6146 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6147         command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6148 #else
6149         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6150 #endif
6151         printf ("Executing the native linker: %s\n", command);
6152         if (system (command) != 0) {
6153                 g_free (tmp_outfile_name);
6154                 g_free (outfile_name);
6155                 g_free (command);
6156                 g_free (objfile);
6157                 return 1;
6158         }
6159
6160         g_free (command);
6161         unlink (objfile);
6162         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6163         printf ("Stripping the binary: %s\n", com);
6164         system (com);
6165         g_free (com);*/
6166
6167 #if defined(TARGET_ARM) && !defined(__MACH__)
6168         /* 
6169          * gas generates 'mapping symbols' each time code and data is mixed, which 
6170          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6171          */
6172         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6173         printf ("Stripping the binary: %s\n", command);
6174         if (system (command) != 0) {
6175                 g_free (tmp_outfile_name);
6176                 g_free (outfile_name);
6177                 g_free (command);
6178                 g_free (objfile);
6179                 return 1;
6180         }
6181 #endif
6182
6183         rename (tmp_outfile_name, outfile_name);
6184
6185         g_free (tmp_outfile_name);
6186         g_free (outfile_name);
6187         g_free (objfile);
6188
6189         if (acfg->aot_opts.save_temps)
6190                 printf ("Retained input file.\n");
6191         else
6192                 unlink (acfg->tmpfname);
6193
6194         return 0;
6195 }
6196
6197 static MonoAotCompile*
6198 acfg_create (MonoAssembly *ass, guint32 opts)
6199 {
6200         MonoImage *image = ass->image;
6201         MonoAotCompile *acfg;
6202         int i;
6203
6204         acfg = g_new0 (MonoAotCompile, 1);
6205         acfg->methods = g_ptr_array_new ();
6206         acfg->method_indexes = g_hash_table_new (NULL, NULL);
6207         acfg->method_depth = g_hash_table_new (NULL, NULL);
6208         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6209         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6210         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6211         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6212         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6213                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6214         acfg->got_patches = g_ptr_array_new ();
6215         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6216         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6217         acfg->image_hash = g_hash_table_new (NULL, NULL);
6218         acfg->image_table = g_ptr_array_new ();
6219         acfg->globals = g_ptr_array_new ();
6220         acfg->image = image;
6221         acfg->opts = opts;
6222         acfg->mempool = mono_mempool_new ();
6223         acfg->extra_methods = g_ptr_array_new ();
6224         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6225         acfg->unwind_ops = g_ptr_array_new ();
6226         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6227         InitializeCriticalSection (&acfg->mutex);
6228
6229         return acfg;
6230 }
6231
6232 static void
6233 acfg_free (MonoAotCompile *acfg)
6234 {
6235         int i;
6236
6237         img_writer_destroy (acfg->w);
6238         for (i = 0; i < acfg->nmethods; ++i)
6239                 if (acfg->cfgs [i])
6240                         g_free (acfg->cfgs [i]);
6241         g_free (acfg->cfgs);
6242         g_free (acfg->static_linking_symbol);
6243         g_free (acfg->got_symbol);
6244         g_free (acfg->plt_symbol);
6245         g_ptr_array_free (acfg->methods, TRUE);
6246         g_ptr_array_free (acfg->got_patches, TRUE);
6247         g_ptr_array_free (acfg->image_table, TRUE);
6248         g_ptr_array_free (acfg->globals, TRUE);
6249         g_ptr_array_free (acfg->unwind_ops, TRUE);
6250         g_hash_table_destroy (acfg->method_indexes);
6251         g_hash_table_destroy (acfg->method_depth);
6252         g_hash_table_destroy (acfg->plt_offset_to_entry);
6253         g_hash_table_destroy (acfg->patch_to_plt_entry);
6254         g_hash_table_destroy (acfg->patch_to_got_offset);
6255         g_hash_table_destroy (acfg->method_to_cfg);
6256         g_hash_table_destroy (acfg->token_info_hash);
6257         g_hash_table_destroy (acfg->image_hash);
6258         g_hash_table_destroy (acfg->unwind_info_offsets);
6259         g_hash_table_destroy (acfg->method_label_hash);
6260         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6261                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6262         g_free (acfg->patch_to_got_offset_by_type);
6263         mono_mempool_destroy (acfg->mempool);
6264         g_free (acfg);
6265 }
6266
6267 int
6268 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6269 {
6270         MonoImage *image = ass->image;
6271         int i, res;
6272         MonoAotCompile *acfg;
6273         char *outfile_name, *tmp_outfile_name, *p;
6274         TV_DECLARE (atv);
6275         TV_DECLARE (btv);
6276
6277         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6278
6279         acfg = acfg_create (ass, opts);
6280
6281         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6282         acfg->aot_opts.write_symbols = TRUE;
6283         acfg->aot_opts.ntrampolines = 1024;
6284         acfg->aot_opts.nrgctx_trampolines = 1024;
6285         acfg->aot_opts.nimt_trampolines = 128;
6286
6287         mono_aot_parse_options (aot_options, &acfg->aot_opts);
6288
6289         if (acfg->aot_opts.static_link)
6290                 acfg->aot_opts.autoreg = TRUE;
6291
6292         //acfg->aot_opts.print_skipped_methods = TRUE;
6293
6294 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6295         if (acfg->aot_opts.full_aot) {
6296                 printf ("--aot=full is not supported on this platform.\n");
6297                 return 1;
6298         }
6299 #endif
6300
6301         if (acfg->aot_opts.static_link)
6302                 acfg->aot_opts.asm_writer = TRUE;
6303
6304         if (acfg->aot_opts.soft_debug) {
6305                 MonoDebugOptions *opt = mini_get_debug_options ();
6306
6307                 opt->mdb_optimizations = TRUE;
6308                 opt->gen_seq_points = TRUE;
6309
6310                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6311                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6312                         return 1;
6313                 }
6314                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6315         }
6316
6317         if (mono_use_llvm) {
6318                 acfg->llvm = TRUE;
6319                 acfg->aot_opts.asm_writer = TRUE;
6320                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6321         }
6322
6323         if (acfg->aot_opts.full_aot)
6324                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6325
6326         load_profile_files (acfg);
6327
6328         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6329 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6330         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6331 #endif
6332         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6333
6334         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6335         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6336
6337         /* Get rid of characters which cannot occur in symbols */
6338         for (p = acfg->got_symbol_base; *p; ++p) {
6339                 if (!(isalnum (*p) || *p == '_'))
6340                         *p = '_';
6341         }
6342         for (p = acfg->plt_symbol; *p; ++p) {
6343                 if (!(isalnum (*p) || *p == '_'))
6344                         *p = '_';
6345         }
6346
6347         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6348
6349         /*
6350          * The prefix LLVM likes to put in front of symbol names on darwin.
6351          * The mach-os specs require this for globals, but LLVM puts them in front of all
6352          * symbols. We need to handle this, since we need to refer to LLVM generated
6353          * symbols.
6354          */
6355         acfg->llvm_label_prefix = "";
6356         if (acfg->llvm)
6357                 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6358
6359         acfg->method_index = 1;
6360
6361         collect_methods (acfg);
6362
6363         acfg->cfgs_size = acfg->methods->len + 32;
6364         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6365
6366         /* PLT offset 0 is reserved for the PLT trampoline */
6367         acfg->plt_offset = 1;
6368
6369 #ifdef ENABLE_LLVM
6370         if (acfg->llvm) {
6371                 llvm_acfg = acfg;
6372                 mono_llvm_create_aot_module (acfg->got_symbol_base);
6373         }
6374 #endif
6375
6376         /* GOT offset 0 is reserved for the address of the current assembly */
6377         {
6378                 MonoJumpInfo *ji;
6379
6380                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6381                 ji->type = MONO_PATCH_INFO_IMAGE;
6382                 ji->data.image = acfg->image;
6383
6384                 get_got_offset (acfg, ji);
6385
6386                 /* Slot 1 is reserved for the mscorlib got addr */
6387                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6388                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6389                 get_got_offset (acfg, ji);
6390
6391                 /* This is very common */
6392                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6393                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6394                 get_got_offset (acfg, ji);
6395         }
6396
6397         TV_GETTIME (atv);
6398
6399         compile_methods (acfg);
6400
6401         TV_GETTIME (btv);
6402
6403         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6404
6405         TV_GETTIME (atv);
6406
6407 #ifdef ENABLE_LLVM
6408         if (acfg->llvm) {
6409                 if (acfg->aot_opts.asm_only) {
6410                         if (acfg->aot_opts.outfile)
6411                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6412                         else
6413                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6414                 } else {
6415                         acfg->tmpfname = g_strdup ("temp.s");
6416                 }
6417
6418                 emit_llvm_file (acfg);
6419         }
6420 #endif
6421
6422         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6423                 if (acfg->aot_opts.outfile)
6424                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6425                 else
6426                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6427
6428                 /* 
6429                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
6430                  * it might be in another file system so the rename () won't work.
6431                  */
6432                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6433
6434                 acfg->fp = fopen (tmp_outfile_name, "w");
6435                 if (!acfg->fp) {
6436                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6437                         return 1;
6438                 }
6439
6440                 acfg->w = img_writer_create (acfg->fp, TRUE);
6441                 acfg->use_bin_writer = TRUE;
6442         } else {
6443                 if (acfg->llvm) {
6444                         /* Append to the .s file created by llvm */
6445                         /* FIXME: Use multiple files instead */
6446                         acfg->fp = fopen (acfg->tmpfname, "a+");
6447                 } else {
6448                         if (acfg->aot_opts.asm_only) {
6449                                 if (acfg->aot_opts.outfile)
6450                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6451                                 else
6452                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6453                                 acfg->fp = fopen (acfg->tmpfname, "w+");
6454                         } else {
6455                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6456                                 acfg->fp = fdopen (i, "w+");
6457                         }
6458                         g_assert (acfg->fp);
6459                 }
6460                 acfg->w = img_writer_create (acfg->fp, FALSE);
6461                 
6462                 tmp_outfile_name = NULL;
6463                 outfile_name = NULL;
6464         }
6465
6466         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6467
6468         /* Compute symbols for methods */
6469         for (i = 0; i < acfg->nmethods; ++i) {
6470                 if (acfg->cfgs [i]) {
6471                         MonoCompile *cfg = acfg->cfgs [i];
6472                         int method_index = get_method_index (acfg, cfg->orig_method);
6473
6474                         cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6475                 }
6476         }
6477
6478         if (!acfg->aot_opts.nodebug)
6479                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6480
6481         img_writer_emit_start (acfg->w);
6482
6483         if (acfg->dwarf)
6484                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6485
6486         emit_code (acfg);
6487
6488         emit_info (acfg);
6489
6490         emit_extra_methods (acfg);
6491
6492         emit_trampolines (acfg);
6493
6494         emit_class_name_table (acfg);
6495
6496         emit_got_info (acfg);
6497
6498         emit_exception_info (acfg);
6499
6500         emit_unwind_info (acfg);
6501
6502         emit_class_info (acfg);
6503
6504         emit_plt (acfg);
6505
6506         emit_image_table (acfg);
6507
6508         emit_got (acfg);
6509
6510         emit_file_info (acfg);
6511
6512         emit_blob (acfg);
6513
6514         emit_globals (acfg);
6515
6516         emit_autoreg (acfg);
6517
6518         if (acfg->dwarf) {
6519                 emit_dwarf_info (acfg);
6520                 mono_dwarf_writer_close (acfg->dwarf);
6521         }
6522
6523         emit_mem_end (acfg);
6524
6525         TV_GETTIME (btv);
6526
6527         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6528
6529         if (acfg->llvm)
6530                 g_assert (acfg->got_offset <= acfg->final_got_size);
6531
6532         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);
6533
6534         TV_GETTIME (atv);
6535         res = img_writer_emit_writeout (acfg->w);
6536         if (res != 0) {
6537                 acfg_free (acfg);
6538                 return res;
6539         }
6540         if (acfg->use_bin_writer) {
6541                 int err = rename (tmp_outfile_name, outfile_name);
6542
6543                 if (err) {
6544                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6545                         return 1;
6546                 }
6547         } else {
6548                 res = compile_asm (acfg);
6549                 if (res != 0) {
6550                         acfg_free (acfg);
6551                         return res;
6552                 }
6553         }
6554         TV_GETTIME (btv);
6555         acfg->stats.link_time = TV_ELAPSED (atv, btv);
6556
6557         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);
6558         if (acfg->stats.genericcount)
6559                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6560         if (acfg->stats.abscount)
6561                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6562         if (acfg->stats.lmfcount)
6563                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6564         if (acfg->stats.ocount)
6565                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6566         if (acfg->llvm)
6567                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6568         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);
6569         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6570
6571         if (acfg->aot_opts.stats) {
6572                 int i;
6573
6574                 printf ("GOT slot distribution:\n");
6575                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6576                         if (acfg->stats.got_slot_types [i])
6577                                 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6578         }
6579
6580         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);
6581
6582         acfg_free (acfg);
6583         
6584         return 0;
6585 }
6586
6587 #else
6588
6589 /* AOT disabled */
6590
6591 int
6592 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6593 {
6594         return 0;
6595 }
6596
6597 #endif