Fix another AOT crash if a signature cannot be loaded.
[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->data [0] = 0;
1442         sh->index ++;
1443 }
1444
1445 static void
1446 make_room_in_stream (MonoDynamicStream *stream, int size)
1447 {
1448         if (size <= stream->alloc_size)
1449                 return;
1450         
1451         while (stream->alloc_size <= size) {
1452                 if (stream->alloc_size < 4096)
1453                         stream->alloc_size = 4096;
1454                 else
1455                         stream->alloc_size *= 2;
1456         }
1457         
1458         stream->data = g_realloc (stream->data, stream->alloc_size);
1459 }
1460
1461 static guint32
1462 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1463 {
1464         guint32 idx;
1465         
1466         make_room_in_stream (stream, stream->index + len);
1467         memcpy (stream->data + stream->index, data, len);
1468         idx = stream->index;
1469         stream->index += len;
1470         return idx;
1471 }
1472
1473 /*
1474  * add_to_blob:
1475  *
1476  *   Add data to the binary blob inside the aot image. Returns the offset inside the
1477  * blob where the data was stored.
1478  */
1479 static guint32
1480 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1481 {
1482         if (acfg->blob.alloc_size == 0)
1483                 stream_init (&acfg->blob);
1484
1485         return add_stream_data (&acfg->blob, (char*)data, data_len);
1486 }
1487
1488 /*
1489  * emit_offset_table:
1490  *
1491  *   Emit a table of increasing offsets in a compact form using differential encoding.
1492  * There is an index entry for each GROUP_SIZE number of entries. The greater the
1493  * group size, the more compact the table becomes, but the slower it becomes to compute
1494  * a given entry. Returns the size of the table.
1495  */
1496 static guint32
1497 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1498 {
1499         gint32 current_offset;
1500         int i, buf_size, ngroups, index_entry_size;
1501         guint8 *p, *buf;
1502         guint32 *index_offsets;
1503
1504         ngroups = (noffsets + (group_size - 1)) / group_size;
1505
1506         index_offsets = g_new0 (guint32, ngroups);
1507
1508         buf_size = noffsets * 4;
1509         p = buf = g_malloc0 (buf_size);
1510
1511         current_offset = 0;
1512         for (i = 0; i < noffsets; ++i) {
1513                 //printf ("D: %d -> %d\n", i, offsets [i]);
1514                 if ((i % group_size) == 0) {
1515                         index_offsets [i / group_size] = p - buf;
1516                         /* Emit the full value for these entries */
1517                         encode_value (offsets [i], p, &p);
1518                 } else {
1519                         /* The offsets are allowed to be non-increasing */
1520                         //g_assert (offsets [i] >= current_offset);
1521                         encode_value (offsets [i] - current_offset, p, &p);
1522                 }
1523                 current_offset = offsets [i];
1524         }
1525
1526         if (ngroups && index_offsets [ngroups - 1] < 65000)
1527                 index_entry_size = 2;
1528         else
1529                 index_entry_size = 4;
1530
1531         /* Emit the header */
1532         emit_int32 (acfg, noffsets);
1533         emit_int32 (acfg, group_size);
1534         emit_int32 (acfg, ngroups);
1535         emit_int32 (acfg, index_entry_size);
1536
1537         /* Emit the index */
1538         for (i = 0; i < ngroups; ++i) {
1539                 if (index_entry_size == 2)
1540                         emit_int16 (acfg, index_offsets [i]);
1541                 else
1542                         emit_int32 (acfg, index_offsets [i]);
1543         }
1544
1545         /* Emit the data */
1546         emit_bytes (acfg, buf, p - buf);
1547
1548     return (int)(p - buf) + (ngroups * 4);
1549 }
1550
1551 static guint32
1552 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1553 {
1554         guint32 index;
1555
1556         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1557         if (index)
1558                 return index - 1;
1559         else {
1560                 index = g_hash_table_size (cfg->image_hash);
1561                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1562                 g_ptr_array_add (cfg->image_table, image);
1563                 return index;
1564         }
1565 }
1566
1567 static guint32
1568 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1569 {
1570         int i;
1571         int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1572
1573         /* FIXME: Search referenced images as well */
1574         if (!acfg->typespec_classes) {
1575                 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1576                 for (i = 0; i < len; ++i) {
1577                         acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1578                 }
1579         }
1580         for (i = 0; i < len; ++i) {
1581                 if (acfg->typespec_classes [i] == klass)
1582                         break;
1583         }
1584
1585         if (i < len)
1586                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1587         else
1588                 return 0;
1589 }
1590
1591 static void
1592 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1593
1594 /*
1595  * encode_klass_ref:
1596  *
1597  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
1598  * standard metadata encoding.
1599  */
1600 static void
1601 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1602 {
1603         guint8 *p = buf;
1604
1605         if (klass->generic_class) {
1606                 guint32 token;
1607                 g_assert (klass->type_token);
1608
1609                 /* Find a typespec for a class if possible */
1610                 token = find_typespec_for_class (acfg, klass);
1611                 if (token) {
1612                         encode_value (token, p, &p);
1613                         encode_value (get_image_index (acfg, acfg->image), p, &p);
1614                 } else {
1615                         MonoClass *gclass = klass->generic_class->container_class;
1616                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
1617                         int i;
1618
1619                         /* Encode it ourselves */
1620                         /* Marker */
1621                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1622                         encode_value (MONO_TYPE_GENERICINST, p, &p);
1623                         encode_klass_ref (acfg, gclass, p, &p);
1624                         encode_value (inst->type_argc, p, &p);
1625                         for (i = 0; i < inst->type_argc; ++i)
1626                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1627                 }
1628         } else if (klass->type_token) {
1629                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1630                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1631                 encode_value (get_image_index (acfg, klass->image), p, &p);
1632         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1633                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1634                 g_assert (container);
1635
1636                 /* Marker */
1637                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1638                 encode_value (klass->byval_arg.type, p, &p);
1639
1640                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1641                 
1642                 encode_value (container->is_method, p, &p);
1643                 if (container->is_method)
1644                         encode_method_ref (acfg, container->owner.method, p, &p);
1645                 else
1646                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1647         } else {
1648                 /* Array class */
1649                 g_assert (klass->rank > 0);
1650                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1651                 encode_value (get_image_index (acfg, klass->image), p, &p);
1652                 encode_value (klass->rank, p, &p);
1653                 encode_klass_ref (acfg, klass->element_class, p, &p);
1654         }
1655         *endbuf = p;
1656 }
1657
1658 static void
1659 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1660 {
1661         guint32 token = mono_get_field_token (field);
1662         guint8 *p = buf;
1663
1664         encode_klass_ref (cfg, field->parent, p, &p);
1665         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1666         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1667         *endbuf = p;
1668 }
1669
1670 static void
1671 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1672 {
1673         guint8 *p = buf;
1674         int i;
1675         MonoGenericInst *inst;
1676
1677         /* Encode the context */
1678         inst = context->class_inst;
1679         encode_value (inst ? 1 : 0, p, &p);
1680         if (inst) {
1681                 encode_value (inst->type_argc, p, &p);
1682                 for (i = 0; i < inst->type_argc; ++i)
1683                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1684         }
1685         inst = context->method_inst;
1686         encode_value (inst ? 1 : 0, p, &p);
1687         if (inst) {
1688                 encode_value (inst->type_argc, p, &p);
1689                 for (i = 0; i < inst->type_argc; ++i)
1690                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1691         }
1692
1693         *endbuf = p;
1694 }
1695
1696 #define MAX_IMAGE_INDEX 250
1697
1698 static void
1699 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1700 {
1701         guint32 image_index = get_image_index (acfg, method->klass->image);
1702         guint32 token = method->token;
1703         MonoJumpInfoToken *ji;
1704         guint8 *p = buf;
1705         char *name;
1706
1707         /*
1708          * The encoding for most methods is as follows:
1709          * - image index encoded as a leb128
1710          * - token index encoded as a leb128
1711          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1712          * types of method encodings.
1713          */
1714
1715         g_assert (image_index < MONO_AOT_METHODREF_MIN);
1716
1717         /* Mark methods which can't use aot trampolines because they need the further 
1718          * processing in mono_magic_trampoline () which requires a MonoMethod*.
1719          */
1720         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1721                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1722                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1723
1724         /* 
1725          * Some wrapper methods are shared using their signature, encode their 
1726          * stringified signature instead.
1727          * FIXME: Optimize disk usage
1728          */
1729         name = NULL;
1730         if (method->wrapper_type) {
1731                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1732                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1733                         if (strcmp (method->name, "runtime_invoke_dynamic")) {
1734                                 name = mono_aot_wrapper_name (method);
1735                         } else if (mono_marshal_method_from_wrapper (method) != method) {
1736                                 /* Direct wrapper, encode it normally */
1737                         } else {
1738                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1739                         }
1740                         g_free (tmpsig);
1741                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1742                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1743                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1744                         g_free (tmpsig);
1745                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1746                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1747                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1748                         g_free (tmpsig);
1749                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1750                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1751                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1752                         g_free (tmpsig);
1753                 }
1754         }
1755
1756         if (name) {
1757                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1758                 strcpy ((char*)p, name);
1759                 p += strlen (name) + 1;
1760                 g_free (name);
1761         } else if (method->wrapper_type) {
1762                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1763
1764                 encode_value (method->wrapper_type, p, &p);
1765
1766                 switch (method->wrapper_type) {
1767                 case MONO_WRAPPER_REMOTING_INVOKE:
1768                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1769                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1770                         MonoMethod *m;
1771
1772                         m = mono_marshal_method_from_wrapper (method);
1773                         g_assert (m);
1774                         encode_method_ref (acfg, m, p, &p);
1775                         break;
1776                 }
1777                 case MONO_WRAPPER_PROXY_ISINST:
1778                 case MONO_WRAPPER_LDFLD:
1779                 case MONO_WRAPPER_LDFLDA:
1780                 case MONO_WRAPPER_STFLD:
1781                 case MONO_WRAPPER_ISINST: {
1782                         MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1783                         encode_klass_ref (acfg, proxy_class, p, &p);
1784                         break;
1785                 }
1786                 case MONO_WRAPPER_LDFLD_REMOTE:
1787                 case MONO_WRAPPER_STFLD_REMOTE:
1788                         break;
1789                 case MONO_WRAPPER_ALLOC: {
1790                         AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1791
1792                         /* The GC name is saved once in MonoAotFileInfo */
1793                         g_assert (info->alloc_type != -1);
1794                         encode_value (info->alloc_type, p, &p);
1795                         break;
1796                 }
1797                 case MONO_WRAPPER_WRITE_BARRIER:
1798                         break;
1799                 case MONO_WRAPPER_STELEMREF: {
1800                         MonoClass *klass = mono_marshal_get_wrapper_info (method);
1801
1802                         /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
1803                         g_assert (!klass);
1804                         break;
1805                 }
1806                 case MONO_WRAPPER_UNKNOWN:
1807                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1808                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1809                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1810                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1811                         else
1812                                 g_assert_not_reached ();
1813                         break;
1814                 case MONO_WRAPPER_SYNCHRONIZED:
1815                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1816                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1817                         MonoMethod *m;
1818
1819                         m = mono_marshal_method_from_wrapper (method);
1820                         g_assert (m);
1821                         g_assert (m != method);
1822                         encode_method_ref (acfg, m, p, &p);
1823                         break;
1824                 }
1825                 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1826                         if (!strcmp (method->name, "ElementAddr")) {
1827                                 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1828
1829                                 g_assert (info);
1830                                 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1831                                 encode_value (info->rank, p, &p);
1832                                 encode_value (info->elem_size, p, &p);
1833                         } else {
1834                                 g_assert_not_reached ();
1835                         }
1836                         break;
1837                 default:
1838                         g_assert_not_reached ();
1839                 }
1840         } else if (mono_method_signature (method)->is_inflated) {
1841                 /* 
1842                  * This is a generic method, find the original token which referenced it and
1843                  * encode that.
1844                  * Obtain the token from information recorded by the JIT.
1845                  */
1846                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1847                 if (ji) {
1848                         image_index = get_image_index (acfg, ji->image);
1849                         g_assert (image_index < MAX_IMAGE_INDEX);
1850                         token = ji->token;
1851
1852                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1853                         encode_value (image_index, p, &p);
1854                         encode_value (token, p, &p);
1855                 } else {
1856                         MonoMethod *declaring;
1857                         MonoGenericContext *context = mono_method_get_context (method);
1858
1859                         g_assert (method->is_inflated);
1860                         declaring = ((MonoMethodInflated*)method)->declaring;
1861
1862                         /*
1863                          * This might be a non-generic method of a generic instance, which 
1864                          * doesn't have a token since the reference is generated by the JIT 
1865                          * like Nullable:Box/Unbox, or by generic sharing.
1866                          */
1867
1868                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1869                         /* Encode the klass */
1870                         encode_klass_ref (acfg, method->klass, p, &p);
1871                         /* Encode the method */
1872                         image_index = get_image_index (acfg, method->klass->image);
1873                         g_assert (image_index < MAX_IMAGE_INDEX);
1874                         g_assert (declaring->token);
1875                         token = declaring->token;
1876                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1877                         encode_value (image_index, p, &p);
1878                         encode_value (token, p, &p);
1879                         encode_generic_context (acfg, context, p, &p);
1880                 }
1881         } else if (token == 0) {
1882                 /* This might be a method of a constructed type like int[,].Set */
1883                 /* Obtain the token from information recorded by the JIT */
1884                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1885                 if (ji) {
1886                         image_index = get_image_index (acfg, ji->image);
1887                         g_assert (image_index < MAX_IMAGE_INDEX);
1888                         token = ji->token;
1889
1890                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1891                         encode_value (image_index, p, &p);
1892                         encode_value (token, p, &p);
1893                 } else {
1894                         /* Array methods */
1895                         g_assert (method->klass->rank);
1896
1897                         /* Encode directly */
1898                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1899                         encode_klass_ref (acfg, method->klass, p, &p);
1900                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1901                                 encode_value (0, p, &p);
1902                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1903                                 encode_value (1, p, &p);
1904                         else if (!strcmp (method->name, "Get"))
1905                                 encode_value (2, p, &p);
1906                         else if (!strcmp (method->name, "Address"))
1907                                 encode_value (3, p, &p);
1908                         else if (!strcmp (method->name, "Set"))
1909                                 encode_value (4, p, &p);
1910                         else
1911                                 g_assert_not_reached ();
1912                 }
1913         } else {
1914                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1915                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1916         }
1917         *endbuf = p;
1918 }
1919
1920 static gint
1921 compare_patches (gconstpointer a, gconstpointer b)
1922 {
1923         int i, j;
1924
1925         i = (*(MonoJumpInfo**)a)->ip.i;
1926         j = (*(MonoJumpInfo**)b)->ip.i;
1927
1928         if (i < j)
1929                 return -1;
1930         else
1931                 if (i > j)
1932                         return 1;
1933         else
1934                 return 0;
1935 }
1936
1937 static G_GNUC_UNUSED char*
1938 patch_to_string (MonoJumpInfo *patch_info)
1939 {
1940         GString *str;
1941
1942         str = g_string_new ("");
1943
1944         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
1945
1946         switch (patch_info->type) {
1947         case MONO_PATCH_INFO_VTABLE:
1948                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
1949                 break;
1950         default:
1951                 break;
1952         }
1953         g_string_append_printf (str, ")");
1954         return g_string_free (str, FALSE);
1955 }
1956
1957 /*
1958  * is_plt_patch:
1959  *
1960  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1961  * PLT entry.
1962  */
1963 static inline gboolean
1964 is_plt_patch (MonoJumpInfo *patch_info)
1965 {
1966         switch (patch_info->type) {
1967         case MONO_PATCH_INFO_METHOD:
1968         case MONO_PATCH_INFO_INTERNAL_METHOD:
1969         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1970         case MONO_PATCH_INFO_ICALL_ADDR:
1971         case MONO_PATCH_INFO_CLASS_INIT:
1972         case MONO_PATCH_INFO_RGCTX_FETCH:
1973         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1974         case MONO_PATCH_INFO_MONITOR_ENTER:
1975         case MONO_PATCH_INFO_MONITOR_EXIT:
1976         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1977                 return TRUE;
1978         default:
1979                 return FALSE;
1980         }
1981 }
1982
1983 /*
1984  * get_plt_symbol:
1985  *
1986  *   Return the symbol identifying the plt entry PLT_OFFSET.
1987  */
1988 static char*
1989 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
1990 {
1991 #ifdef __MACH__
1992         /* 
1993          * The Apple linker reorganizes object files, so it doesn't like branches to local
1994          * labels, since those have no relocations.
1995          */
1996         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
1997 #else
1998         return g_strdup_printf ("%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
1999 #endif
2000 }
2001
2002 /*
2003  * get_plt_entry:
2004  *
2005  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2006  */
2007 static MonoPltEntry*
2008 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2009 {
2010         MonoPltEntry *res;
2011
2012         if (!is_plt_patch (patch_info))
2013                 return NULL;
2014
2015         res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2016
2017         // FIXME: This breaks the calculation of final_got_size         
2018         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2019                 /* 
2020                  * Allocate a separate PLT slot for each such patch, since some plt
2021                  * entries will refer to the method itself, and some will refer to the
2022                  * wrapper.
2023                  */
2024                 res = NULL;
2025         }
2026
2027         if (!res) {
2028                 MonoJumpInfo *new_ji;
2029
2030                 g_assert (!acfg->final_got_size);
2031
2032                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2033
2034                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2035                 res->plt_offset = acfg->plt_offset;
2036                 res->ji = new_ji;
2037                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2038
2039                 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2040
2041                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2042
2043                 acfg->plt_offset ++;
2044         }
2045
2046         return res;
2047 }
2048
2049 /**
2050  * get_got_offset:
2051  *
2052  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
2053  * JI could be found if it exists, otherwise allocates a new one.
2054  */
2055 static guint32
2056 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2057 {
2058         guint32 got_offset;
2059
2060         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2061         if (got_offset)
2062                 return got_offset - 1;
2063
2064         got_offset = acfg->got_offset;
2065         acfg->got_offset ++;
2066
2067         if (acfg->final_got_size)
2068                 g_assert (got_offset < acfg->final_got_size);
2069
2070         acfg->stats.got_slots ++;
2071         acfg->stats.got_slot_types [ji->type] ++;
2072
2073         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2074         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2075         g_ptr_array_add (acfg->got_patches, ji);
2076
2077         return got_offset;
2078 }
2079
2080 /* Add a method to the list of methods which need to be emitted */
2081 static void
2082 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2083 {
2084         g_assert (method);
2085         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2086                 g_ptr_array_add (acfg->methods, method);
2087                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2088                 acfg->nmethods = acfg->methods->len + 1;
2089         }
2090
2091         if (method->wrapper_type || extra)
2092                 g_ptr_array_add (acfg->extra_methods, method);
2093 }
2094
2095 static guint32
2096 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2097 {
2098         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2099         
2100         g_assert (index);
2101
2102         return index - 1;
2103 }
2104
2105 static int
2106 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2107 {
2108         int index;
2109
2110         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2111         if (index)
2112                 return index - 1;
2113
2114         index = acfg->method_index;
2115         add_method_with_index (acfg, method, index, extra);
2116
2117         /* FIXME: Fix quadratic behavior */
2118         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2119
2120         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2121
2122         acfg->method_index ++;
2123
2124         return index;
2125 }
2126
2127 static int
2128 add_method (MonoAotCompile *acfg, MonoMethod *method)
2129 {
2130         return add_method_full (acfg, method, FALSE, 0);
2131 }
2132
2133 static void
2134 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2135 {
2136         add_method_full (acfg, method, TRUE, 0);
2137 }
2138
2139 static void
2140 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2141 {
2142         add_method_full (acfg, method, TRUE, depth);
2143 }
2144
2145 static void
2146 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2147 {
2148         MonoAotCompile *acfg = user_data;
2149         MonoJitICallInfo *callinfo = value;
2150         MonoMethod *wrapper;
2151         char *name;
2152
2153         if (!callinfo->sig)
2154                 return;
2155
2156         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2157         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2158         g_free (name);
2159
2160         add_method (acfg, wrapper);
2161 }
2162
2163 static MonoMethod*
2164 get_runtime_invoke_sig (MonoMethodSignature *sig)
2165 {
2166         MonoMethodBuilder *mb;
2167         MonoMethod *m;
2168
2169         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2170         m = mono_mb_create_method (mb, sig, 16);
2171         return mono_marshal_get_runtime_invoke (m, FALSE);
2172 }
2173
2174 static gboolean
2175 can_marshal_struct (MonoClass *klass)
2176 {
2177         MonoClassField *field;
2178         gboolean can_marshal = TRUE;
2179         gpointer iter = NULL;
2180
2181         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2182                 return FALSE;
2183
2184         /* Only allow a few field types to avoid asserts in the marshalling code */
2185         while ((field = mono_class_get_fields (klass, &iter))) {
2186                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2187                         continue;
2188
2189                 switch (field->type->type) {
2190                 case MONO_TYPE_I4:
2191                 case MONO_TYPE_U4:
2192                 case MONO_TYPE_I1:
2193                 case MONO_TYPE_U1:
2194                 case MONO_TYPE_BOOLEAN:
2195                 case MONO_TYPE_I2:
2196                 case MONO_TYPE_U2:
2197                 case MONO_TYPE_CHAR:
2198                 case MONO_TYPE_I8:
2199                 case MONO_TYPE_U8:
2200                 case MONO_TYPE_I:
2201                 case MONO_TYPE_U:
2202                 case MONO_TYPE_PTR:
2203                 case MONO_TYPE_R4:
2204                 case MONO_TYPE_R8:
2205                 case MONO_TYPE_STRING:
2206                         break;
2207                 case MONO_TYPE_VALUETYPE:
2208                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2209                                 can_marshal = FALSE;
2210                         break;
2211                 default:
2212                         can_marshal = FALSE;
2213                         break;
2214                 }
2215         }
2216
2217         /* Special cases */
2218         /* Its hard to compute whenever these can be marshalled or not */
2219         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2220                 return TRUE;
2221
2222         return can_marshal;
2223 }
2224
2225 static void
2226 add_wrappers (MonoAotCompile *acfg)
2227 {
2228         MonoMethod *method, *m;
2229         int i, j;
2230         MonoMethodSignature *sig, *csig;
2231         guint32 token;
2232
2233         /* 
2234          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2235          * so there is only one wrapper of a given type, or inlining their contents into their
2236          * callers.
2237          */
2238
2239         /* 
2240          * FIXME: This depends on the fact that different wrappers have different 
2241          * names.
2242          */
2243
2244         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2245                 MonoMethod *method;
2246                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2247                 gboolean skip = FALSE;
2248
2249                 method = mono_get_method (acfg->image, token, NULL);
2250
2251                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2252                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2253                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2254                         skip = TRUE;
2255
2256                 if (method->is_generic || method->klass->generic_container)
2257                         skip = TRUE;
2258
2259                 /* Skip methods which can not be handled by get_runtime_invoke () */
2260                 sig = mono_method_signature (method);
2261                 if (!sig)
2262                         continue;
2263                 if ((sig->ret->type == MONO_TYPE_PTR) ||
2264                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2265                         skip = TRUE;
2266
2267                 for (j = 0; j < sig->param_count; j++) {
2268                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2269                                 skip = TRUE;
2270                 }
2271
2272 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2273                 if (!method->klass->contextbound) {
2274                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2275                         gboolean has_nullable = FALSE;
2276
2277                         for (j = 0; j < sig->param_count; j++) {
2278                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2279                                         has_nullable = TRUE;
2280                         }
2281
2282                         if (info && !has_nullable) {
2283                                 /* Supported by the dynamic runtime-invoke wrapper */
2284                                 skip = TRUE;
2285                                 g_free (info);
2286                         }
2287                 }
2288 #endif
2289
2290                 if (!skip) {
2291                         //printf ("%s\n", mono_method_full_name (method, TRUE));
2292                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2293                 }
2294         }
2295
2296         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2297 #ifdef MONO_ARCH_HAVE_TLS_GET
2298                 MonoMethodDesc *desc;
2299                 MonoMethod *orig_method;
2300                 int nallocators;
2301 #endif
2302
2303                 /* Runtime invoke wrappers */
2304
2305                 /* void runtime-invoke () [.cctor] */
2306                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2307                 csig->ret = &mono_defaults.void_class->byval_arg;
2308                 add_method (acfg, get_runtime_invoke_sig (csig));
2309
2310                 /* void runtime-invoke () [Finalize] */
2311                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2312                 csig->hasthis = 1;
2313                 csig->ret = &mono_defaults.void_class->byval_arg;
2314                 add_method (acfg, get_runtime_invoke_sig (csig));
2315
2316                 /* void runtime-invoke (string) [exception ctor] */
2317                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2318                 csig->hasthis = 1;
2319                 csig->ret = &mono_defaults.void_class->byval_arg;
2320                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2321                 add_method (acfg, get_runtime_invoke_sig (csig));
2322
2323                 /* void runtime-invoke (string, string) [exception ctor] */
2324                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2325                 csig->hasthis = 1;
2326                 csig->ret = &mono_defaults.void_class->byval_arg;
2327                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2328                 csig->params [1] = &mono_defaults.string_class->byval_arg;
2329                 add_method (acfg, get_runtime_invoke_sig (csig));
2330
2331                 /* string runtime-invoke () [Exception.ToString ()] */
2332                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2333                 csig->hasthis = 1;
2334                 csig->ret = &mono_defaults.string_class->byval_arg;
2335                 add_method (acfg, get_runtime_invoke_sig (csig));
2336
2337                 /* void runtime-invoke (string, Exception) [exception ctor] */
2338                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2339                 csig->hasthis = 1;
2340                 csig->ret = &mono_defaults.void_class->byval_arg;
2341                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2342                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2343                 add_method (acfg, get_runtime_invoke_sig (csig));
2344
2345                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2346                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2347                 csig->hasthis = 1;
2348                 csig->ret = &(mono_class_from_name (
2349                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2350                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2351                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2352                 add_method (acfg, get_runtime_invoke_sig (csig));
2353
2354                 /* runtime-invoke used by finalizers */
2355                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2356
2357                 /* This is used by mono_runtime_capture_context () */
2358                 method = mono_get_context_capture_method ();
2359                 if (method)
2360                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2361
2362 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2363                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2364 #endif
2365
2366                 /* JIT icall wrappers */
2367                 /* FIXME: locking */
2368                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2369
2370                 /* stelemref */
2371                 add_method (acfg, mono_marshal_get_stelemref ());
2372
2373 #ifdef MONO_ARCH_HAVE_TLS_GET
2374                 /* Managed Allocators */
2375                 nallocators = mono_gc_get_managed_allocator_types ();
2376                 for (i = 0; i < nallocators; ++i) {
2377                         m = mono_gc_get_managed_allocator_by_type (i);
2378                         if (m)
2379                                 add_method (acfg, m);
2380                 }
2381
2382                 /* Monitor Enter/Exit */
2383                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2384                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2385                 g_assert (orig_method);
2386                 mono_method_desc_free (desc);
2387                 method = mono_monitor_get_fast_path (orig_method);
2388                 if (method)
2389                         add_method (acfg, method);
2390
2391                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2392                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2393                 g_assert (orig_method);
2394                 mono_method_desc_free (desc);
2395                 method = mono_monitor_get_fast_path (orig_method);
2396                 if (method)
2397                         add_method (acfg, method);
2398 #endif
2399
2400                 /* Stelemref wrappers */
2401                 /* There is only a constant number of these, iterating over all types should handle them all */
2402                 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2403                         MonoClass *klass;
2404                 
2405                         token = MONO_TOKEN_TYPE_DEF | (i + 1);
2406                         klass = mono_class_get (acfg->image, token);
2407                         if (klass)
2408                                 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2409                 }
2410         }
2411
2412         /* 
2413          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2414          * we use the original method instead at runtime.
2415          * Since full-aot doesn't support remoting, this is not a problem.
2416          */
2417 #if 0
2418         /* remoting-invoke wrappers */
2419         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2420                 MonoMethodSignature *sig;
2421                 
2422                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2423                 method = mono_get_method (acfg->image, token, NULL);
2424
2425                 sig = mono_method_signature (method);
2426
2427                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2428                         m = mono_marshal_get_remoting_invoke_with_check (method);
2429
2430                         add_method (acfg, m);
2431                 }
2432         }
2433 #endif
2434
2435         /* delegate-invoke wrappers */
2436         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2437                 MonoClass *klass;
2438                 
2439                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2440                 klass = mono_class_get (acfg->image, token);
2441
2442                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2443                         method = mono_get_delegate_invoke (klass);
2444
2445                         m = mono_marshal_get_delegate_invoke (method, NULL);
2446
2447                         add_method (acfg, m);
2448
2449                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2450                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2451
2452                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2453                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2454                 }
2455         }
2456
2457         /* Synchronized wrappers */
2458         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2459                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2460                 method = mono_get_method (acfg->image, token, NULL);
2461
2462                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2463                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2464         }
2465
2466         /* pinvoke wrappers */
2467         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2468                 MonoMethod *method;
2469                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2470
2471                 method = mono_get_method (acfg->image, token, NULL);
2472
2473                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2474                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2475                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2476                 }
2477         }
2478  
2479         /* native-to-managed wrappers */
2480         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2481                 MonoMethod *method;
2482                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2483                 MonoCustomAttrInfo *cattr;
2484                 int j;
2485
2486                 method = mono_get_method (acfg->image, token, NULL);
2487
2488                 /* 
2489                  * Only generate native-to-managed wrappers for methods which have an
2490                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2491                  * name to avoid defining a new assembly to contain it.
2492                  */
2493                 cattr = mono_custom_attrs_from_method (method);
2494
2495                 if (cattr) {
2496                         for (j = 0; j < cattr->num_attrs; ++j)
2497                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2498                                         break;
2499                         if (j < cattr->num_attrs) {
2500                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
2501                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2502                                 const char *p = (const char*)e->data;
2503                                 int slen;
2504                                 char *n;
2505                                 MonoType *t;
2506                                 MonoClass *klass;
2507
2508                                 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2509
2510                                 g_assert (sig->param_count == 1);
2511                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2512
2513                                 /* 
2514                                  * Decode the cattr manually since we can't create objects
2515                                  * during aot compilation.
2516                                  */
2517                                         
2518                                 /* Skip prolog */
2519                                 p += 2;
2520
2521                                 /* From load_cattr_value () in reflection.c */
2522                                 slen = mono_metadata_decode_value (p, &p);
2523                                 n = g_memdup (p, slen + 1);
2524                                 n [slen] = 0;
2525                                 t = mono_reflection_type_from_name (n, acfg->image);
2526                                 g_assert (t);
2527                                 g_free (n);
2528
2529                                 klass = mono_class_from_mono_type (t);
2530                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2531
2532                                 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2533                         }
2534                 }
2535
2536                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2537                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2538                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2539                 }
2540         }
2541
2542         /* StructureToPtr/PtrToStructure wrappers */
2543         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2544                 MonoClass *klass;
2545                 
2546                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2547                 klass = mono_class_get (acfg->image, token);
2548
2549                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2550                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2551                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2552                 }
2553         }
2554 }
2555
2556 static gboolean
2557 has_type_vars (MonoClass *klass)
2558 {
2559         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2560                 return TRUE;
2561         if (klass->rank)
2562                 return has_type_vars (klass->element_class);
2563         if (klass->generic_class) {
2564                 MonoGenericContext *context = &klass->generic_class->context;
2565                 if (context->class_inst) {
2566                         int i;
2567
2568                         for (i = 0; i < context->class_inst->type_argc; ++i)
2569                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2570                                         return TRUE;
2571                 }
2572         }
2573         return FALSE;
2574 }
2575
2576 static gboolean
2577 method_has_type_vars (MonoMethod *method)
2578 {
2579         if (has_type_vars (method->klass))
2580                 return TRUE;
2581
2582         if (method->is_inflated) {
2583                 MonoGenericContext *context = mono_method_get_context (method);
2584                 if (context->method_inst) {
2585                         int i;
2586
2587                         for (i = 0; i < context->method_inst->type_argc; ++i)
2588                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2589                                         return TRUE;
2590                 }
2591         }
2592         return FALSE;
2593 }
2594
2595 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2596
2597 static void
2598 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2599 {
2600         /* This might lead to a huge code blowup so only do it if neccesary */
2601         if (!acfg->aot_opts.full_aot && !force)
2602                 return;
2603
2604         add_generic_class_with_depth (acfg, klass, 0);
2605 }
2606
2607 /*
2608  * add_generic_class:
2609  *
2610  *   Add all methods of a generic class.
2611  */
2612 static void
2613 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2614 {
2615         MonoMethod *method;
2616         gpointer iter;
2617
2618         mono_class_init (klass);
2619
2620         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2621                 return;
2622
2623         if (has_type_vars (klass))
2624                 return;
2625
2626         if (!klass->generic_class && !klass->rank)
2627                 return;
2628
2629         iter = NULL;
2630         while ((method = mono_class_get_methods (klass, &iter))) {
2631                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2632                         /* Already added */
2633                         continue;
2634
2635                 if (method->is_generic)
2636                         /* FIXME: */
2637                         continue;
2638
2639                 /*
2640                  * FIXME: Instances which are referenced by these methods are not added,
2641                  * for example Array.Resize<int> for List<int>.Add ().
2642                  */
2643                 add_extra_method_with_depth (acfg, method, depth);
2644         }
2645
2646         if (klass->delegate) {
2647                 method = mono_get_delegate_invoke (klass);
2648
2649                 method = mono_marshal_get_delegate_invoke (method, NULL);
2650
2651                 add_method (acfg, method);
2652         }
2653
2654         /* 
2655          * For ICollection<T>, add instances of the helper methods
2656          * in Array, since a T[] could be cast to ICollection<T>.
2657          */
2658         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2659                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2660                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2661                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2662                 gpointer iter;
2663                 char *name_prefix;
2664
2665                 if (!strcmp (klass->name, "IEnumerator`1"))
2666                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2667                 else
2668                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2669
2670                 /* Add the T[]/InternalEnumerator class */
2671                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2672                         MonoClass *nclass;
2673
2674                         iter = NULL;
2675                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2676                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2677                                         break;
2678                         }
2679                         g_assert (nclass);
2680                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2681                         add_generic_class (acfg, nclass, FALSE);
2682                 }
2683
2684                 iter = NULL;
2685                 while ((method = mono_class_get_methods (array_class, &iter))) {
2686                         if (strstr (method->name, name_prefix)) {
2687                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2688                                 add_extra_method_with_depth (acfg, m, depth);
2689                         }
2690                 }
2691
2692                 g_free (name_prefix);
2693         }
2694
2695         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2696         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2697                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2698                 MonoClass *icomparable, *gcomparer;
2699                 MonoGenericContext ctx;
2700                 MonoType *args [16];
2701
2702                 memset (&ctx, 0, sizeof (ctx));
2703
2704                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2705                 g_assert (icomparable);
2706                 args [0] = &tclass->byval_arg;
2707                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2708
2709                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2710                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2711                         g_assert (gcomparer);
2712                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2713                 }
2714         }
2715
2716         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2717         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2718                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2719                 MonoClass *iface, *gcomparer;
2720                 MonoGenericContext ctx;
2721                 MonoType *args [16];
2722
2723                 memset (&ctx, 0, sizeof (ctx));
2724
2725                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2726                 g_assert (iface);
2727                 args [0] = &tclass->byval_arg;
2728                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2729
2730                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2731                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2732                         g_assert (gcomparer);
2733                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2734                 }
2735         }
2736 }
2737
2738 static void
2739 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
2740 {
2741         int i;
2742         MonoGenericContext ctx;
2743         MonoType *args [16];
2744
2745         memset (&ctx, 0, sizeof (ctx));
2746
2747         for (i = 0; i < ninsts; ++i) {
2748                 args [0] = insts [i];
2749                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2750                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
2751         }
2752 }
2753
2754 /*
2755  * add_generic_instances:
2756  *
2757  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2758  */
2759 static void
2760 add_generic_instances (MonoAotCompile *acfg)
2761 {
2762         int i;
2763         guint32 token;
2764         MonoMethod *method;
2765         MonoMethodHeader *header;
2766         MonoMethodSignature *sig;
2767         MonoGenericContext *context;
2768
2769         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2770                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2771                 method = mono_get_method (acfg->image, token, NULL);
2772
2773                 if (!method)
2774                         continue;
2775
2776                 if (method->klass->image != acfg->image)
2777                         continue;
2778
2779                 context = mono_method_get_context (method);
2780
2781                 if (context && ((context->class_inst && context->class_inst->is_open)))
2782                         continue;
2783
2784                 /*
2785                  * For open methods, create an instantiation which can be passed to the JIT.
2786                  * FIXME: Handle class_inst as well.
2787                  */
2788                 if (context && context->method_inst && context->method_inst->is_open) {
2789                         MonoGenericContext shared_context;
2790                         MonoGenericInst *inst;
2791                         MonoType **type_argv;
2792                         int i;
2793                         MonoMethod *declaring_method;
2794                         gboolean supported = TRUE;
2795
2796                         /* Check that the context doesn't contain open constructed types */
2797                         if (context->class_inst) {
2798                                 inst = context->class_inst;
2799                                 for (i = 0; i < inst->type_argc; ++i) {
2800                                         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)
2801                                                 continue;
2802                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2803                                                 supported = FALSE;
2804                                 }
2805                         }
2806                         if (context->method_inst) {
2807                                 inst = context->method_inst;
2808                                 for (i = 0; i < inst->type_argc; ++i) {
2809                                         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)
2810                                                 continue;
2811                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2812                                                 supported = FALSE;
2813                                 }
2814                         }
2815
2816                         if (!supported)
2817                                 continue;
2818
2819                         memset (&shared_context, 0, sizeof (MonoGenericContext));
2820
2821                         inst = context->class_inst;
2822                         if (inst) {
2823                                 type_argv = g_new0 (MonoType*, inst->type_argc);
2824                                 for (i = 0; i < inst->type_argc; ++i) {
2825                                         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)
2826                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
2827                                         else
2828                                                 type_argv [i] = inst->type_argv [i];
2829                                 }
2830                                 
2831                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2832                                 g_free (type_argv);
2833                         }
2834
2835                         inst = context->method_inst;
2836                         if (inst) {
2837                                 type_argv = g_new0 (MonoType*, inst->type_argc);
2838                                 for (i = 0; i < inst->type_argc; ++i) {
2839                                         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)
2840                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
2841                                         else
2842                                                 type_argv [i] = inst->type_argv [i];
2843                                 }
2844
2845                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2846                                 g_free (type_argv);
2847                         }
2848
2849                         if (method->is_generic || method->klass->generic_container)
2850                                 declaring_method = method;
2851                         else
2852                                 declaring_method = mono_method_get_declaring_generic_method (method);
2853
2854                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2855                 }
2856
2857                 /* 
2858                  * If the method is fully sharable, it was already added in place of its
2859                  * generic definition.
2860                  */
2861                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2862                         continue;
2863
2864                 /*
2865                  * FIXME: Partially shared methods are not shared here, so we end up with
2866                  * many identical methods.
2867                  */
2868                 add_extra_method (acfg, method);
2869         }
2870
2871         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2872                 MonoClass *klass;
2873
2874                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2875
2876                 klass = mono_class_get (acfg->image, token);
2877                 if (!klass || klass->rank)
2878                         continue;
2879
2880                 add_generic_class (acfg, klass, FALSE);
2881         }
2882
2883         /* Add types of args/locals */
2884         for (i = 0; i < acfg->methods->len; ++i) {
2885                 int j;
2886
2887                 method = g_ptr_array_index (acfg->methods, i);
2888
2889                 sig = mono_method_signature (method);
2890
2891                 if (sig) {
2892                         for (j = 0; j < sig->param_count; ++j)
2893                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2894                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]), FALSE);
2895                 }
2896
2897                 header = mono_method_get_header (method);
2898
2899                 if (header) {
2900                         for (j = 0; j < header->num_locals; ++j)
2901                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2902                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]), FALSE);
2903                 }
2904         }
2905
2906         if (acfg->image == mono_defaults.corlib) {
2907                 MonoClass *klass;
2908                 MonoType *insts [256];
2909                 int ninsts = 0;
2910
2911                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2912                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2913                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2914                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2915                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2916                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2917                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2918                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2919                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2920                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2921                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2922                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2923
2924                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2925                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2926                 if (klass)
2927                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2928                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2929                 if (klass)
2930                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2931
2932                 /* Add instances of the array generic interfaces for primitive types */
2933                 /* This will add instances of the InternalArray_ helper methods in Array too */
2934                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2935                 if (klass)
2936                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2937                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2938                 if (klass)
2939                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2940                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2941                 if (klass)
2942                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
2943
2944                 /* 
2945                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2946                  * used for all instances of GetGenericValueImpl by the AOT runtime.
2947                  */
2948                 {
2949                         MonoGenericContext ctx;
2950                         MonoType *args [16];
2951                         MonoMethod *get_method;
2952                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2953
2954                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2955
2956                         if (get_method) {
2957                                 memset (&ctx, 0, sizeof (ctx));
2958                                 args [0] = &mono_defaults.object_class->byval_arg;
2959                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2960                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2961                         }
2962                 }
2963         }
2964 }
2965
2966 /*
2967  * is_direct_callable:
2968  *
2969  *   Return whenever the method identified by JI is directly callable without 
2970  * going through the PLT.
2971  */
2972 static gboolean
2973 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2974 {
2975         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2976                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2977                 if (callee_cfg) {
2978                         gboolean direct_callable = TRUE;
2979
2980                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2981                                 direct_callable = FALSE;
2982                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2983                                 // FIXME: Maybe call the wrapper directly ?
2984                                 direct_callable = FALSE;
2985
2986                         if (direct_callable)
2987                                 return TRUE;
2988                 }
2989         }
2990
2991         return FALSE;
2992 }
2993
2994 /*
2995  * emit_and_reloc_code:
2996  *
2997  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2998  * is true, calls are made through the GOT too. This is used for emitting trampolines
2999  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3000  * since trampolines are needed to make PTL work.
3001  */
3002 static void
3003 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3004 {
3005         int i, pindex, start_index, method_index;
3006         GPtrArray *patches;
3007         MonoJumpInfo *patch_info;
3008         MonoMethodHeader *header;
3009         gboolean skip, direct_call;
3010         guint32 got_slot;
3011         char direct_call_target [128];
3012
3013         if (method) {
3014                 header = mono_method_get_header (method);
3015
3016                 method_index = get_method_index (acfg, method);
3017         }
3018
3019         /* Collect and sort relocations */
3020         patches = g_ptr_array_new ();
3021         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3022                 g_ptr_array_add (patches, patch_info);
3023         g_ptr_array_sort (patches, compare_patches);
3024
3025         start_index = 0;
3026         for (i = 0; i < code_len; i++) {
3027                 patch_info = NULL;
3028                 for (pindex = start_index; pindex < patches->len; ++pindex) {
3029                         patch_info = g_ptr_array_index (patches, pindex);
3030                         if (patch_info->ip.i >= i)
3031                                 break;
3032                 }
3033
3034 #ifdef MONO_ARCH_AOT_SUPPORTED
3035                 skip = FALSE;
3036                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3037                         start_index = pindex;
3038
3039                         switch (patch_info->type) {
3040                         case MONO_PATCH_INFO_NONE:
3041                                 break;
3042                         case MONO_PATCH_INFO_GOT_OFFSET: {
3043                                 int code_size;
3044  
3045                                 arch_emit_got_offset (acfg, code + i, &code_size);
3046                                 i += code_size - 1;
3047                                 skip = TRUE;
3048                                 patch_info->type = MONO_PATCH_INFO_NONE;
3049                                 break;
3050                         }
3051                         default: {
3052                                 /*
3053                                  * If this patch is a call, try emitting a direct call instead of
3054                                  * through a PLT entry. This is possible if the called method is in
3055                                  * the same assembly and requires no initialization.
3056                                  */
3057                                 direct_call = FALSE;
3058                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3059                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3060                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3061                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3062                                                 direct_call = TRUE;
3063                                                 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3064                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3065                                                 acfg->stats.direct_calls ++;
3066                                         }
3067
3068                                         acfg->stats.all_calls ++;
3069                                 }
3070
3071                                 if (!got_only && !direct_call) {
3072                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3073                                         if (plt_entry) {
3074                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3075                                                 direct_call = TRUE;
3076                                                 sprintf (direct_call_target, "%s", plt_entry->symbol);
3077                 
3078                                                 /* Nullify the patch */
3079                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3080                                         }
3081                                 }
3082
3083                                 if (direct_call) {
3084                                         int call_size;
3085
3086                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
3087                                         i += call_size - 1;
3088                                 } else {
3089                                         int code_size;
3090
3091                                         got_slot = get_got_offset (acfg, patch_info);
3092
3093                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3094                                         i += code_size - 1;
3095                                 }
3096                                 skip = TRUE;
3097                         }
3098                         }
3099                 }
3100 #endif /* MONO_ARCH_AOT_SUPPORTED */
3101
3102                 if (!skip) {
3103                         /* Find next patch */
3104                         patch_info = NULL;
3105                         for (pindex = start_index; pindex < patches->len; ++pindex) {
3106                                 patch_info = g_ptr_array_index (patches, pindex);
3107                                 if (patch_info->ip.i >= i)
3108                                         break;
3109                         }
3110
3111                         /* Try to emit multiple bytes at once */
3112                         if (pindex < patches->len && patch_info->ip.i > i) {
3113                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3114                                 i = patch_info->ip.i - 1;
3115                         } else {
3116                                 emit_bytes (acfg, code + i, 1);
3117                         }
3118                 }
3119         }
3120 }
3121
3122 /*
3123  * sanitize_symbol:
3124  *
3125  *   Modify SYMBOL so it only includes characters permissible in symbols.
3126  */
3127 static void
3128 sanitize_symbol (char *symbol)
3129 {
3130         int i, len = strlen (symbol);
3131
3132         for (i = 0; i < len; ++i)
3133                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3134                         symbol [i] = '_';
3135 }
3136
3137 static char*
3138 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3139 {
3140         char *name1, *name2, *cached;
3141         int i, j, len, count;
3142                 
3143         name1 = mono_method_full_name (method, TRUE);
3144         len = strlen (name1);
3145         name2 = malloc (strlen (prefix) + len + 16);
3146         memcpy (name2, prefix, strlen (prefix));
3147         j = strlen (prefix);
3148         for (i = 0; i < len; ++i) {
3149                 if (isalnum (name1 [i])) {
3150                         name2 [j ++] = name1 [i];
3151                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3152                         i += 2;
3153                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3154                         name2 [j ++] = '_';
3155                         i++;
3156                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3157                 } else
3158                         name2 [j ++] = '_';
3159         }
3160         name2 [j] = '\0';
3161
3162         g_free (name1);
3163
3164         count = 0;
3165         while (g_hash_table_lookup (cache, name2)) {
3166                 sprintf (name2 + j, "_%d", count);
3167                 count ++;
3168         }
3169
3170         cached = g_strdup (name2);
3171         g_hash_table_insert (cache, cached, cached);
3172
3173         return name2;
3174 }
3175
3176 static void
3177 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3178 {
3179         MonoMethod *method;
3180         int method_index;
3181         guint8 *code;
3182         char *debug_sym = NULL;
3183         char symbol [128];
3184         int func_alignment = AOT_FUNC_ALIGNMENT;
3185         MonoMethodHeader *header;
3186
3187         method = cfg->orig_method;
3188         code = cfg->native_code;
3189         header = cfg->header;
3190
3191         method_index = get_method_index (acfg, method);
3192
3193         /* Make the labels local */
3194         sprintf (symbol, "%s", cfg->asm_symbol);
3195
3196         emit_section_change (acfg, ".text", 0);
3197         emit_alignment (acfg, func_alignment);
3198         emit_label (acfg, symbol);
3199
3200         if (acfg->aot_opts.write_symbols) {
3201                 /* 
3202                  * Write a C style symbol for every method, this has two uses:
3203                  * - it works on platforms where the dwarf debugging info is not
3204                  *   yet supported.
3205                  * - it allows the setting of breakpoints of aot-ed methods.
3206                  */
3207                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3208
3209                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3210                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3211                 emit_label (acfg, debug_sym);
3212         }
3213
3214         if (cfg->verbose_level > 0)
3215                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3216
3217         acfg->stats.code_size += cfg->code_len;
3218
3219         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3220
3221         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3222
3223         emit_line (acfg);
3224
3225         if (acfg->aot_opts.write_symbols) {
3226                 emit_symbol_size (acfg, debug_sym, ".");
3227                 g_free (debug_sym);
3228         }
3229
3230         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3231         emit_label (acfg, symbol);
3232 }
3233
3234 /**
3235  * encode_patch:
3236  *
3237  *  Encode PATCH_INFO into its disk representation.
3238  */
3239 static void
3240 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3241 {
3242         guint8 *p = buf;
3243
3244         switch (patch_info->type) {
3245         case MONO_PATCH_INFO_NONE:
3246                 break;
3247         case MONO_PATCH_INFO_IMAGE:
3248                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3249                 break;
3250         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3251         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3252                 break;
3253         case MONO_PATCH_INFO_METHOD_REL:
3254                 encode_value ((gint)patch_info->data.offset, p, &p);
3255                 break;
3256         case MONO_PATCH_INFO_SWITCH: {
3257                 gpointer *table = (gpointer *)patch_info->data.table->table;
3258                 int k;
3259
3260                 encode_value (patch_info->data.table->table_size, p, &p);
3261                 for (k = 0; k < patch_info->data.table->table_size; k++)
3262                         encode_value ((int)(gssize)table [k], p, &p);
3263                 break;
3264         }
3265         case MONO_PATCH_INFO_METHODCONST:
3266         case MONO_PATCH_INFO_METHOD:
3267         case MONO_PATCH_INFO_METHOD_JUMP:
3268         case MONO_PATCH_INFO_ICALL_ADDR:
3269         case MONO_PATCH_INFO_METHOD_RGCTX:
3270                 encode_method_ref (acfg, patch_info->data.method, p, &p);
3271                 break;
3272         case MONO_PATCH_INFO_INTERNAL_METHOD:
3273         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3274                 guint32 len = strlen (patch_info->data.name);
3275
3276                 encode_value (len, p, &p);
3277
3278                 memcpy (p, patch_info->data.name, len);
3279                 p += len;
3280                 *p++ = '\0';
3281                 break;
3282         }
3283         case MONO_PATCH_INFO_LDSTR: {
3284                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3285                 guint32 token = patch_info->data.token->token;
3286                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3287                 encode_value (image_index, p, &p);
3288                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3289                 break;
3290         }
3291         case MONO_PATCH_INFO_RVA:
3292         case MONO_PATCH_INFO_DECLSEC:
3293         case MONO_PATCH_INFO_LDTOKEN:
3294         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3295                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3296                 encode_value (patch_info->data.token->token, p, &p);
3297                 encode_value (patch_info->data.token->has_context, p, &p);
3298                 if (patch_info->data.token->has_context)
3299                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3300                 break;
3301         case MONO_PATCH_INFO_EXC_NAME: {
3302                 MonoClass *ex_class;
3303
3304                 ex_class =
3305                         mono_class_from_name (mono_defaults.exception_class->image,
3306                                                                   "System", patch_info->data.target);
3307                 g_assert (ex_class);
3308                 encode_klass_ref (acfg, ex_class, p, &p);
3309                 break;
3310         }
3311         case MONO_PATCH_INFO_R4:
3312                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3313                 break;
3314         case MONO_PATCH_INFO_R8:
3315                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3316                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3317                 break;
3318         case MONO_PATCH_INFO_VTABLE:
3319         case MONO_PATCH_INFO_CLASS:
3320         case MONO_PATCH_INFO_IID:
3321         case MONO_PATCH_INFO_ADJUSTED_IID:
3322                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3323                 break;
3324         case MONO_PATCH_INFO_CLASS_INIT:
3325         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3326                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3327                 break;
3328         case MONO_PATCH_INFO_FIELD:
3329         case MONO_PATCH_INFO_SFLDA:
3330                 encode_field_info (acfg, patch_info->data.field, p, &p);
3331                 break;
3332         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3333                 break;
3334         case MONO_PATCH_INFO_RGCTX_FETCH: {
3335                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3336
3337                 encode_method_ref (acfg, entry->method, p, &p);
3338                 encode_value (entry->in_mrgctx, p, &p);
3339                 encode_value (entry->info_type, p, &p);
3340                 encode_value (entry->data->type, p, &p);
3341                 encode_patch (acfg, entry->data, p, &p);
3342                 break;
3343         }
3344         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3345         case MONO_PATCH_INFO_MONITOR_ENTER:
3346         case MONO_PATCH_INFO_MONITOR_EXIT:
3347         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3348                 break;
3349         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3350                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3351                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3352                 break;
3353         default:
3354                 g_warning ("unable to handle jump info %d", patch_info->type);
3355                 g_assert_not_reached ();
3356         }
3357
3358         *endbuf = p;
3359 }
3360
3361 static void
3362 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3363 {
3364         guint8 *p = buf;
3365         guint32 pindex, offset;
3366         MonoJumpInfo *patch_info;
3367
3368         encode_value (n_patches, p, &p);
3369
3370         for (pindex = 0; pindex < patches->len; ++pindex) {
3371                 patch_info = g_ptr_array_index (patches, pindex);
3372
3373                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3374                         /* Nothing to do */
3375                         continue;
3376
3377                 offset = get_got_offset (acfg, patch_info);
3378                 encode_value (offset, p, &p);
3379         }
3380
3381         *endbuf = p;
3382 }
3383
3384 static void
3385 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3386 {
3387         MonoMethod *method;
3388         GList *l;
3389         int pindex, buf_size, n_patches;
3390         guint8 *code;
3391         GPtrArray *patches;
3392         MonoJumpInfo *patch_info;
3393         MonoMethodHeader *header;
3394         guint32 method_index;
3395         guint8 *p, *buf;
3396         guint32 first_got_offset;
3397
3398         method = cfg->orig_method;
3399         code = cfg->native_code;
3400         header = mono_method_get_header (method);
3401
3402         method_index = get_method_index (acfg, method);
3403
3404         /* Sort relocations */
3405         patches = g_ptr_array_new ();
3406         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3407                 g_ptr_array_add (patches, patch_info);
3408         g_ptr_array_sort (patches, compare_patches);
3409
3410         first_got_offset = acfg->cfgs [method_index]->got_offset;
3411
3412         /**********************/
3413         /* Encode method info */
3414         /**********************/
3415
3416         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3417         p = buf = g_malloc (buf_size);
3418
3419         if (mono_class_get_cctor (method->klass))
3420                 encode_klass_ref (acfg, method->klass, p, &p);
3421         else
3422                 /* Not needed when loading the method */
3423                 encode_value (0, p, &p);
3424
3425         /* String table */
3426         if (cfg->opt & MONO_OPT_SHARED) {
3427                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3428                 for (l = cfg->ldstr_list; l; l = l->next) {
3429                         encode_value ((long)l->data, p, &p);
3430                 }
3431         }
3432         else
3433                 /* Used only in shared mode */
3434                 g_assert (!cfg->ldstr_list);
3435
3436         n_patches = 0;
3437         for (pindex = 0; pindex < patches->len; ++pindex) {
3438                 patch_info = g_ptr_array_index (patches, pindex);
3439                 
3440                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3441                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
3442                         patch_info->type = MONO_PATCH_INFO_NONE;
3443                         /* Nothing to do */
3444                         continue;
3445                 }
3446
3447                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
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 (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3454                         /* Stored in a GOT slot initialized at module load time */
3455                         patch_info->type = MONO_PATCH_INFO_NONE;
3456                         continue;
3457                 }
3458
3459                 if (is_plt_patch (patch_info)) {
3460                         /* Calls are made through the PLT */
3461                         patch_info->type = MONO_PATCH_INFO_NONE;
3462                         continue;
3463                 }
3464
3465                 n_patches ++;
3466         }
3467
3468         if (n_patches)
3469                 g_assert (cfg->has_got_slots);
3470
3471         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3472
3473         acfg->stats.info_size += p - buf;
3474
3475         g_assert (p - buf < buf_size);
3476
3477         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3478         g_free (buf);
3479 }
3480
3481 static guint32
3482 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3483 {
3484         guint32 cache_index;
3485         guint32 offset;
3486
3487         /* Reuse the unwind module to canonize and store unwind info entries */
3488         cache_index = mono_cache_unwind_info (encoded, encoded_len);
3489
3490         /* Use +/- 1 to distinguish 0s from missing entries */
3491         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3492         if (offset)
3493                 return offset - 1;
3494         else {
3495                 guint8 buf [16];
3496                 guint8 *p;
3497
3498                 /* 
3499                  * It would be easier to use assembler symbols, but the caller needs an
3500                  * offset now.
3501                  */
3502                 offset = acfg->unwind_info_offset;
3503                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3504                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3505
3506                 p = buf;
3507                 encode_value (encoded_len, p, &p);
3508
3509                 acfg->unwind_info_offset += encoded_len + (p - buf);
3510                 return offset;
3511         }
3512 }
3513
3514 static void
3515 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3516 {
3517         MonoMethod *method;
3518         int i, k, buf_size, method_index;
3519         guint32 debug_info_size;
3520         guint8 *code;
3521         MonoMethodHeader *header;
3522         guint8 *p, *buf, *debug_info;
3523         MonoJitInfo *jinfo = cfg->jit_info;
3524         guint32 flags;
3525         gboolean use_unwind_ops = FALSE;
3526         MonoSeqPointInfo *seq_points;
3527
3528         method = cfg->orig_method;
3529         code = cfg->native_code;
3530         header = cfg->header;
3531
3532         method_index = get_method_index (acfg, method);
3533
3534         if (!acfg->aot_opts.nodebug) {
3535                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3536         } else {
3537                 debug_info = NULL;
3538                 debug_info_size = 0;
3539         }
3540
3541         seq_points = cfg->seq_point_info;
3542
3543         buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3544         p = buf = g_malloc (buf_size);
3545
3546 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3547         use_unwind_ops = cfg->unwind_ops != NULL;
3548 #endif
3549
3550         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);
3551
3552         encode_value (flags, p, &p);
3553
3554         if (use_unwind_ops) {
3555                 guint32 encoded_len;
3556                 guint8 *encoded;
3557
3558                 /* 
3559                  * This is a duplicate of the data in the .debug_frame section, but that
3560                  * section cannot be accessed using the dl interface.
3561                  */
3562                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3563                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3564                 g_free (encoded);
3565         } else {
3566                 encode_value (jinfo->used_regs, p, &p);
3567         }
3568
3569         /*Encode the number of holes before the number of clauses to make decoding easier*/
3570         if (jinfo->has_try_block_holes) {
3571                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3572                 encode_value (table->num_holes, p, &p);
3573         }
3574
3575         /* Exception table */
3576         if (cfg->compile_llvm) {
3577                 /*
3578                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3579                  * since the information is only available to llc. Instead, we let llc save the data
3580                  * into the LSDA, and read it from there at runtime.
3581                  */
3582                 /* The assembly might be CIL stripped so emit the data ourselves */
3583                 if (header->num_clauses)
3584                         encode_value (header->num_clauses, p, &p);
3585
3586                 for (k = 0; k < header->num_clauses; ++k) {
3587                         MonoExceptionClause *clause;
3588
3589                         clause = &header->clauses [k];
3590
3591                         encode_value (clause->flags, p, &p);
3592                         if (clause->data.catch_class) {
3593                                 encode_value (1, p, &p);
3594                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3595                         } else {
3596                                 encode_value (0, p, &p);
3597                         }
3598
3599                         /* Emit a list of nesting clauses */
3600                         for (i = 0; i < header->num_clauses; ++i) {
3601                                 gint32 cindex1 = k;
3602                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3603                                 gint32 cindex2 = i;
3604                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3605
3606                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3607                                         encode_value (i, p, &p);
3608                         }
3609                         encode_value (-1, p, &p);
3610                 }
3611         } else {
3612                 if (jinfo->num_clauses)
3613                         encode_value (jinfo->num_clauses, p, &p);
3614
3615                 for (k = 0; k < jinfo->num_clauses; ++k) {
3616                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3617
3618                         encode_value (ei->flags, p, &p);
3619                         encode_value (ei->exvar_offset, p, &p);
3620
3621                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3622                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3623                         else {
3624                                 if (ei->data.catch_class) {
3625                                         encode_value (1, p, &p);
3626                                         encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3627                                 } else {
3628                                         encode_value (0, p, &p);
3629                                 }
3630                         }
3631
3632                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3633                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3634                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3635                 }
3636         }
3637
3638         if (jinfo->has_generic_jit_info) {
3639                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3640
3641                 if (!cfg->compile_llvm) {
3642                         encode_value (gi->has_this ? 1 : 0, p, &p);
3643                         encode_value (gi->this_reg, p, &p);
3644                         encode_value (gi->this_offset, p, &p);
3645                 }
3646
3647                 /* 
3648                  * Need to encode jinfo->method too, since it is not equal to 'method'
3649                  * when using generic sharing.
3650                  */
3651                 encode_method_ref (acfg, jinfo->method, p, &p);
3652         }
3653
3654         if (jinfo->has_try_block_holes) {
3655                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3656                 for (i = 0; i < table->num_holes; ++i) {
3657                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3658                         encode_value (hole->clause, p, &p);
3659                         encode_value (hole->length, p, &p);
3660                         encode_value (hole->offset, p, &p);
3661                 }
3662         }
3663
3664         if (seq_points) {
3665                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3666
3667                 encode_value (seq_points->len, p, &p);
3668                 last_il_offset = last_native_offset = 0;
3669                 for (i = 0; i < seq_points->len; ++i) {
3670                         SeqPoint *sp = &seq_points->seq_points [i];
3671                         il_offset = sp->il_offset;
3672                         native_offset = sp->native_offset;
3673                         encode_value (il_offset - last_il_offset, p, &p);
3674                         encode_value (native_offset - last_native_offset, p, &p);
3675                         last_il_offset = il_offset;
3676                         last_native_offset = native_offset;
3677
3678                         encode_value (sp->next_len, p, &p);
3679                         for (j = 0; j < sp->next_len; ++j)
3680                                 encode_value (sp->next [j], p, &p);
3681                 }
3682         }
3683                 
3684
3685         g_assert (debug_info_size < buf_size);
3686
3687         encode_value (debug_info_size, p, &p);
3688         if (debug_info_size) {
3689                 memcpy (p, debug_info, debug_info_size);
3690                 p += debug_info_size;
3691                 g_free (debug_info);
3692         }
3693
3694         acfg->stats.ex_info_size += p - buf;
3695
3696         g_assert (p - buf < buf_size);
3697
3698         /* Emit info */
3699         cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3700         g_free (buf);
3701 }
3702
3703 static guint32
3704 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3705 {
3706         MonoClass *klass = mono_class_get (acfg->image, token);
3707         guint8 *p, *buf;
3708         int i, buf_size, res;
3709         gboolean no_special_static, cant_encode;
3710         gpointer iter = NULL;
3711
3712         if (!klass) {
3713                 buf_size = 16;
3714
3715                 p = buf = g_malloc (buf_size);
3716
3717                 /* Mark as unusable */
3718                 encode_value (-1, p, &p);
3719
3720                 res = add_to_blob (acfg, buf, p - buf);
3721                 g_free (buf);
3722
3723                 return res;
3724         }
3725                 
3726         buf_size = 10240 + (klass->vtable_size * 16);
3727         p = buf = g_malloc (buf_size);
3728
3729         g_assert (klass);
3730
3731         mono_class_init (klass);
3732
3733         mono_class_get_nested_types (klass, &iter);
3734         g_assert (klass->nested_classes_inited);
3735
3736         mono_class_setup_vtable (klass);
3737
3738         /* 
3739          * Emit all the information which is required for creating vtables so
3740          * the runtime does not need to create the MonoMethod structures which
3741          * take up a lot of space.
3742          */
3743
3744         no_special_static = !mono_class_has_special_static_fields (klass);
3745
3746         /* Check whenever we have enough info to encode the vtable */
3747         cant_encode = FALSE;
3748         for (i = 0; i < klass->vtable_size; ++i) {
3749                 MonoMethod *cm = klass->vtable [i];
3750
3751                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3752                         cant_encode = TRUE;
3753         }
3754
3755         if (klass->generic_container || cant_encode) {
3756                 encode_value (-1, p, &p);
3757         } else {
3758                 encode_value (klass->vtable_size, p, &p);
3759                 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);
3760                 if (klass->has_cctor)
3761                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3762                 if (klass->has_finalize)
3763                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3764  
3765                 encode_value (klass->instance_size, p, &p);
3766                 encode_value (mono_class_data_size (klass), p, &p);
3767                 encode_value (klass->packing_size, p, &p);
3768                 encode_value (klass->min_align, p, &p);
3769
3770                 for (i = 0; i < klass->vtable_size; ++i) {
3771                         MonoMethod *cm = klass->vtable [i];
3772
3773                         if (cm)
3774                                 encode_method_ref (acfg, cm, p, &p);
3775                         else
3776                                 encode_value (0, p, &p);
3777                 }
3778         }
3779
3780         acfg->stats.class_info_size += p - buf;
3781
3782         g_assert (p - buf < buf_size);
3783         res = add_to_blob (acfg, buf, p - buf);
3784         g_free (buf);
3785
3786         return res;
3787 }
3788
3789 /*
3790  * Calls made from AOTed code are routed through a table of jumps similar to the
3791  * ELF PLT (Program Linkage Table). The differences are the following:
3792  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3793  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3794  *   jumps. This means the jumps need to be patched when the address of the callee is
3795  *   known. Initially the PLT entries jump to code which transfers control to the
3796  *   AOT runtime through the first PLT entry.
3797  */
3798 static void
3799 emit_plt (MonoAotCompile *acfg)
3800 {
3801         char symbol [128];
3802         int i;
3803         GHashTable *cache;
3804
3805         cache = g_hash_table_new (g_str_hash, g_str_equal);
3806
3807         emit_line (acfg);
3808         sprintf (symbol, "plt");
3809
3810         emit_section_change (acfg, ".text", 0);
3811         emit_global (acfg, symbol, TRUE);
3812         emit_alignment (acfg, 16);
3813         emit_label (acfg, symbol);
3814         emit_label (acfg, acfg->plt_symbol);
3815
3816         for (i = 0; i < acfg->plt_offset; ++i) {
3817                 char label [128];
3818                 char *debug_sym = NULL;
3819                 MonoPltEntry *plt_entry = NULL;
3820                 MonoJumpInfo *ji;
3821
3822                 if (i == 0) {
3823                         /* 
3824                          * The first plt entry is used to transfer code to the AOT loader. 
3825                          */
3826                         arch_emit_plt_entry (acfg, i);
3827                         continue;
3828                 }
3829
3830                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3831                 ji = plt_entry->ji;
3832                 sprintf (label, "%s", plt_entry->symbol);
3833
3834                 if (acfg->llvm) {
3835                         /*
3836                          * If the target is directly callable, alias the plt symbol to point to
3837                          * the method code.
3838                          * FIXME: Use this to simplify emit_and_reloc_code ().
3839                          * FIXME: Avoid the got slot.
3840                          * FIXME: Add support to the binary writer.
3841                          */
3842                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3843                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3844                                 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3845                                 continue;
3846                         }
3847                 }
3848
3849                 emit_label (acfg, label);
3850
3851                 if (acfg->aot_opts.write_symbols) {
3852                         switch (ji->type) {
3853                         case MONO_PATCH_INFO_METHOD:
3854                                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3855                                 break;
3856                         case MONO_PATCH_INFO_INTERNAL_METHOD:
3857                                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3858                                 break;
3859                         case MONO_PATCH_INFO_CLASS_INIT:
3860                                 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3861                                 sanitize_symbol (debug_sym);
3862                                 break;
3863                         case MONO_PATCH_INFO_RGCTX_FETCH:
3864                                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3865                                 break;
3866                         case MONO_PATCH_INFO_ICALL_ADDR: {
3867                                 char *s = get_debug_sym (ji->data.method, "", cache);
3868                                         
3869                                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3870                                 g_free (s);
3871                                 break;
3872                         }
3873                         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3874                                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3875                                 break;
3876                         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3877                                 debug_sym = g_strdup_printf ("plt__generic_class_init");
3878                                 break;
3879                         default:
3880                                 break;
3881                         }
3882
3883                         if (debug_sym) {
3884                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3885                                 emit_label (acfg, debug_sym);
3886                         }
3887                 }
3888
3889                 arch_emit_plt_entry (acfg, i);
3890
3891                 if (debug_sym) {
3892                         emit_symbol_size (acfg, debug_sym, ".");
3893                         g_free (debug_sym);
3894                 }
3895         }
3896
3897         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3898
3899         sprintf (symbol, "plt_end");
3900         emit_global (acfg, symbol, TRUE);
3901         emit_label (acfg, symbol);
3902
3903         g_hash_table_destroy (cache);
3904 }
3905
3906 static G_GNUC_UNUSED void
3907 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3908 {
3909         char start_symbol [256];
3910         char symbol [256];
3911         guint32 buf_size, info_offset;
3912         MonoJumpInfo *patch_info;
3913         guint8 *buf, *p;
3914         GPtrArray *patches;
3915         char *name;
3916         guint8 *code;
3917         guint32 code_size;
3918         MonoJumpInfo *ji;
3919         GSList *unwind_ops;
3920
3921         name = info->name;
3922         code = info->code;
3923         code_size = info->code_size;
3924         ji = info->ji;
3925         unwind_ops = info->unwind_ops;
3926
3927 #ifdef __native_client_codegen__
3928         mono_nacl_fix_patches (code, ji);
3929 #endif
3930
3931         /* Emit code */
3932
3933         sprintf (start_symbol, "%s", name);
3934
3935         emit_section_change (acfg, ".text", 0);
3936         emit_global (acfg, start_symbol, TRUE);
3937         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
3938         emit_label (acfg, start_symbol);
3939
3940         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3941         emit_label (acfg, symbol);
3942
3943         /* 
3944          * The code should access everything through the GOT, so we pass
3945          * TRUE here.
3946          */
3947         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3948
3949         emit_symbol_size (acfg, start_symbol, ".");
3950
3951         /* Emit info */
3952
3953         /* Sort relocations */
3954         patches = g_ptr_array_new ();
3955         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3956                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3957                         g_ptr_array_add (patches, patch_info);
3958         g_ptr_array_sort (patches, compare_patches);
3959
3960         buf_size = patches->len * 128 + 128;
3961         buf = g_malloc (buf_size);
3962         p = buf;
3963
3964         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3965         g_assert (p - buf < buf_size);
3966
3967         sprintf (symbol, "%s_p", name);
3968
3969         info_offset = add_to_blob (acfg, buf, p - buf);
3970
3971         emit_section_change (acfg, RODATA_SECT, 0);
3972         emit_global (acfg, symbol, FALSE);
3973         emit_label (acfg, symbol);
3974
3975         emit_int32 (acfg, info_offset);
3976
3977         /* Emit debug info */
3978         if (unwind_ops) {
3979                 char symbol2 [256];
3980
3981                 sprintf (symbol, "%s", name);
3982                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3983
3984                 if (acfg->dwarf)
3985                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3986         }
3987 }
3988
3989 static void
3990 emit_trampolines (MonoAotCompile *acfg)
3991 {
3992         char symbol [256];
3993         int i, tramp_got_offset;
3994         MonoAotTrampoline ntype;
3995 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3996         int tramp_type;
3997         guint8 *code;
3998 #endif
3999
4000         if (!acfg->aot_opts.full_aot)
4001                 return;
4002         
4003         g_assert (acfg->image->assembly);
4004
4005         /* Currently, we emit most trampolines into the mscorlib AOT image. */
4006         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4007 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4008                 MonoTrampInfo *info;
4009
4010                 /*
4011                  * Emit the generic trampolines.
4012                  *
4013                  * We could save some code by treating the generic trampolines as a wrapper
4014                  * method, but that approach has its own complexities, so we choose the simpler
4015                  * method.
4016                  */
4017                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4018                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4019                         emit_trampoline (acfg, acfg->got_offset, info);
4020                 }
4021
4022                 mono_arch_get_nullified_class_init_trampoline (&info);
4023                 emit_trampoline (acfg, acfg->got_offset, info);
4024 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4025                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4026                 emit_trampoline (acfg, acfg->got_offset, info);
4027                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4028                 emit_trampoline (acfg, acfg->got_offset, info);
4029 #endif
4030
4031                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4032                 emit_trampoline (acfg, acfg->got_offset, info);
4033
4034                 /* Emit the exception related code pieces */
4035                 code = mono_arch_get_restore_context (&info, TRUE);
4036                 emit_trampoline (acfg, acfg->got_offset, info);
4037                 code = mono_arch_get_call_filter (&info, TRUE);
4038                 emit_trampoline (acfg, acfg->got_offset, info);
4039                 code = mono_arch_get_throw_exception (&info, TRUE);
4040                 emit_trampoline (acfg, acfg->got_offset, info);
4041                 code = mono_arch_get_rethrow_exception (&info, TRUE);
4042                 emit_trampoline (acfg, acfg->got_offset, info);
4043                 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4044                 emit_trampoline (acfg, acfg->got_offset, info);
4045
4046 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4047                 {
4048                         GSList *l = mono_arch_get_trampolines (TRUE);
4049
4050                         while (l) {
4051                                 MonoTrampInfo *info = l->data;
4052
4053                                 emit_trampoline (acfg, acfg->got_offset, info);
4054                                 l = l->next;
4055                         }
4056                 }
4057 #endif
4058
4059                 for (i = 0; i < 128; ++i) {
4060                         int offset;
4061
4062                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4063                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4064                         emit_trampoline (acfg, acfg->got_offset, info);
4065
4066                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4067                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4068                         emit_trampoline (acfg, acfg->got_offset, info);
4069                 }
4070
4071                 {
4072                         GSList *l;
4073
4074                         /* delegate_invoke_impl trampolines */
4075                         l = mono_arch_get_delegate_invoke_impls ();
4076                         while (l) {
4077                                 MonoTrampInfo *info = l->data;
4078
4079                                 emit_trampoline (acfg, acfg->got_offset, info);
4080                                 l = l->next;
4081                         }
4082                 }
4083
4084 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4085
4086                 /* Emit trampolines which are numerous */
4087
4088                 /*
4089                  * These include the following:
4090                  * - specific trampolines
4091                  * - static rgctx invoke trampolines
4092                  * - imt thunks
4093                  * These trampolines have the same code, they are parameterized by GOT 
4094                  * slots. 
4095                  * They are defined in this file, in the arch_... routines instead of
4096                  * in tramp-<ARCH>.c, since it is easier to do it this way.
4097                  */
4098
4099                 /*
4100                  * When running in aot-only mode, we can't create specific trampolines at 
4101                  * runtime, so we create a few, and save them in the AOT file. 
4102                  * Normal trampolines embed their argument as a literal inside the 
4103                  * trampoline code, we can't do that here, so instead we embed an offset
4104                  * which needs to be added to the trampoline address to get the address of
4105                  * the GOT slot which contains the argument value.
4106                  * The generated trampolines jump to the generic trampolines using another
4107                  * GOT slot, which will be setup by the AOT loader to point to the 
4108                  * generic trampoline code of the given type.
4109                  */
4110
4111                 /*
4112                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4113                  * each class).
4114                  */
4115
4116                 emit_section_change (acfg, ".text", 0);
4117
4118                 tramp_got_offset = acfg->got_offset;
4119
4120                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4121                         switch (ntype) {
4122                         case MONO_AOT_TRAMP_SPECIFIC:
4123                                 sprintf (symbol, "specific_trampolines");
4124                                 break;
4125                         case MONO_AOT_TRAMP_STATIC_RGCTX:
4126                                 sprintf (symbol, "static_rgctx_trampolines");
4127                                 break;
4128                         case MONO_AOT_TRAMP_IMT_THUNK:
4129                                 sprintf (symbol, "imt_thunks");
4130                                 break;
4131                         default:
4132                                 g_assert_not_reached ();
4133                         }
4134
4135                         emit_global (acfg, symbol, TRUE);
4136                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4137                         emit_label (acfg, symbol);
4138
4139                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4140
4141                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4142                                 int tramp_size = 0;
4143
4144                                 switch (ntype) {
4145                                 case MONO_AOT_TRAMP_SPECIFIC:
4146                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4147                                         tramp_got_offset += 2;
4148                                 break;
4149                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
4150                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
4151                                         tramp_got_offset += 2;
4152                                         break;
4153                                 case MONO_AOT_TRAMP_IMT_THUNK:
4154                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4155                                         tramp_got_offset += 1;
4156                                         break;
4157                                 default:
4158                                         g_assert_not_reached ();
4159                                 }
4160 #ifdef __native_client_codegen__
4161                                 /* align to avoid 32-byte boundary crossings */
4162                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4163 #endif
4164
4165                                 if (!acfg->trampoline_size [ntype]) {
4166                                         g_assert (tramp_size);
4167                                         acfg->trampoline_size [ntype] = tramp_size;
4168                                 }
4169                         }
4170                 }
4171
4172                 /* Reserve some entries at the end of the GOT for our use */
4173                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4174         }
4175
4176         acfg->got_offset += acfg->num_trampoline_got_entries;
4177 }
4178
4179 static gboolean
4180 str_begins_with (const char *str1, const char *str2)
4181 {
4182         int len = strlen (str2);
4183         return strncmp (str1, str2, len) == 0;
4184 }
4185
4186 static void
4187 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4188 {
4189         gchar **args, **ptr;
4190
4191         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4192         for (ptr = args; ptr && *ptr; ptr ++) {
4193                 const char *arg = *ptr;
4194
4195                 if (str_begins_with (arg, "outfile=")) {
4196                         opts->outfile = g_strdup (arg + strlen ("outfile="));
4197                 } else if (str_begins_with (arg, "save-temps")) {
4198                         opts->save_temps = TRUE;
4199                 } else if (str_begins_with (arg, "keep-temps")) {
4200                         opts->save_temps = TRUE;
4201                 } else if (str_begins_with (arg, "write-symbols")) {
4202                         opts->write_symbols = TRUE;
4203                 } else if (str_begins_with (arg, "metadata-only")) {
4204                         opts->metadata_only = TRUE;
4205                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4206                         opts->bind_to_runtime_version = TRUE;
4207                 } else if (str_begins_with (arg, "full")) {
4208                         opts->full_aot = TRUE;
4209                 } else if (str_begins_with (arg, "threads=")) {
4210                         opts->nthreads = atoi (arg + strlen ("threads="));
4211                 } else if (str_begins_with (arg, "static")) {
4212                         opts->static_link = TRUE;
4213                         opts->no_dlsym = TRUE;
4214                 } else if (str_begins_with (arg, "asmonly")) {
4215                         opts->asm_only = TRUE;
4216                 } else if (str_begins_with (arg, "asmwriter")) {
4217                         opts->asm_writer = TRUE;
4218                 } else if (str_begins_with (arg, "nodebug")) {
4219                         opts->nodebug = TRUE;
4220                 } else if (str_begins_with (arg, "ntrampolines=")) {
4221                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4222                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4223                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4224                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4225                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4226                 } else if (str_begins_with (arg, "autoreg")) {
4227                         opts->autoreg = TRUE;
4228                 } else if (str_begins_with (arg, "tool-prefix=")) {
4229                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4230                 } else if (str_begins_with (arg, "soft-debug")) {
4231                         opts->soft_debug = TRUE;
4232                 } else if (str_begins_with (arg, "print-skipped")) {
4233                         opts->print_skipped_methods = TRUE;
4234                 } else if (str_begins_with (arg, "stats")) {
4235                         opts->stats = TRUE;
4236                 } else {
4237                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4238                         exit (1);
4239                 }
4240         }
4241
4242         g_strfreev (args);
4243 }
4244
4245 static void
4246 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4247 {
4248         MonoMethod *method = (MonoMethod*)key;
4249         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4250         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4251         MonoAotCompile *acfg = user_data;
4252
4253         new_ji->image = ji->image;
4254         new_ji->token = ji->token;
4255         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4256 }
4257
4258 static gboolean
4259 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4260 {
4261         if (klass->type_token)
4262                 return TRUE;
4263         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4264                 return TRUE;
4265         if (klass->rank)
4266                 return can_encode_class (acfg, klass->element_class);
4267         return FALSE;
4268 }
4269
4270 static gboolean
4271 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4272 {
4273         switch (patch_info->type) {
4274         case MONO_PATCH_INFO_METHOD:
4275         case MONO_PATCH_INFO_METHODCONST: {
4276                 MonoMethod *method = patch_info->data.method;
4277
4278                 if (method->wrapper_type) {
4279                         switch (method->wrapper_type) {
4280                         case MONO_WRAPPER_NONE:
4281                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4282                         case MONO_WRAPPER_XDOMAIN_INVOKE:
4283                         case MONO_WRAPPER_STFLD:
4284                         case MONO_WRAPPER_LDFLD:
4285                         case MONO_WRAPPER_LDFLDA:
4286                         case MONO_WRAPPER_LDFLD_REMOTE:
4287                         case MONO_WRAPPER_STFLD_REMOTE:
4288                         case MONO_WRAPPER_STELEMREF:
4289                         case MONO_WRAPPER_ISINST:
4290                         case MONO_WRAPPER_PROXY_ISINST:
4291                         case MONO_WRAPPER_ALLOC:
4292                         case MONO_WRAPPER_REMOTING_INVOKE:
4293                         case MONO_WRAPPER_UNKNOWN:
4294                         case MONO_WRAPPER_WRITE_BARRIER:
4295                                 break;
4296                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
4297                                 if (!strcmp (method->name, "ElementAddr"))
4298                                         return TRUE;
4299                                 else
4300                                         return FALSE;
4301                         default:
4302                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4303                                 return FALSE;
4304                         }
4305                 } else {
4306                         if (!method->token) {
4307                                 /* The method is part of a constructed type like Int[,].Set (). */
4308                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4309                                         if (method->klass->rank)
4310                                                 return TRUE;
4311                                         return FALSE;
4312                                 }
4313                         }
4314                 }
4315                 break;
4316         }
4317         case MONO_PATCH_INFO_VTABLE:
4318         case MONO_PATCH_INFO_CLASS_INIT:
4319         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4320         case MONO_PATCH_INFO_CLASS:
4321         case MONO_PATCH_INFO_IID:
4322         case MONO_PATCH_INFO_ADJUSTED_IID:
4323                 if (!can_encode_class (acfg, patch_info->data.klass)) {
4324                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4325                         return FALSE;
4326                 }
4327                 break;
4328         case MONO_PATCH_INFO_RGCTX_FETCH: {
4329                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4330
4331                 if (!can_encode_patch (acfg, entry->data))
4332                         return FALSE;
4333                 break;
4334         }
4335         default:
4336                 break;
4337         }
4338
4339         return TRUE;
4340 }
4341
4342 /*
4343  * compile_method:
4344  *
4345  *   AOT compile a given method.
4346  * This function might be called by multiple threads, so it must be thread-safe.
4347  */
4348 static void
4349 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4350 {
4351         MonoCompile *cfg;
4352         MonoJumpInfo *patch_info;
4353         gboolean skip;
4354         int index, depth;
4355         MonoMethod *wrapped;
4356
4357         if (acfg->aot_opts.metadata_only)
4358                 return;
4359
4360         mono_acfg_lock (acfg);
4361         index = get_method_index (acfg, method);
4362         mono_acfg_unlock (acfg);
4363
4364         /* fixme: maybe we can also precompile wrapper methods */
4365         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4366                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4367                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4368                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4369                 return;
4370         }
4371
4372         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4373                 return;
4374
4375         wrapped = mono_marshal_method_from_wrapper (method);
4376         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4377                 // FIXME: The wrapper should be generic too, but it is not
4378                 return;
4379
4380         InterlockedIncrement (&acfg->stats.mcount);
4381
4382 #if 0
4383         if (method->is_generic || method->klass->generic_container) {
4384                 InterlockedIncrement (&acfg->stats.genericcount);
4385                 return;
4386         }
4387 #endif
4388
4389         //acfg->aot_opts.print_skipped_methods = TRUE;
4390
4391         /*
4392          * Since these methods are the only ones which are compiled with
4393          * AOT support, and they are not used by runtime startup/shutdown code,
4394          * the runtime will not see AOT methods during AOT compilation,so it
4395          * does not need to support them by creating a fake GOT etc.
4396          */
4397         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4398         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4399                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4400                 InterlockedIncrement (&acfg->stats.genericcount);
4401                 return;
4402         }
4403         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4404                 /* Let the exception happen at runtime */
4405                 return;
4406         }
4407
4408         if (cfg->disable_aot) {
4409                 if (acfg->aot_opts.print_skipped_methods)
4410                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4411                 InterlockedIncrement (&acfg->stats.ocount);
4412                 mono_destroy_compile (cfg);
4413                 return;
4414         }
4415
4416         /* Nullify patches which need no aot processing */
4417         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4418                 switch (patch_info->type) {
4419                 case MONO_PATCH_INFO_LABEL:
4420                 case MONO_PATCH_INFO_BB:
4421                         patch_info->type = MONO_PATCH_INFO_NONE;
4422                         break;
4423                 default:
4424                         break;
4425                 }
4426         }
4427
4428         /* Collect method->token associations from the cfg */
4429         mono_acfg_lock (acfg);
4430         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4431         mono_acfg_unlock (acfg);
4432
4433         /*
4434          * Check for absolute addresses.
4435          */
4436         skip = FALSE;
4437         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4438                 switch (patch_info->type) {
4439                 case MONO_PATCH_INFO_ABS:
4440                         /* unable to handle this */
4441                         skip = TRUE;    
4442                         break;
4443                 default:
4444                         break;
4445                 }
4446         }
4447
4448         if (skip) {
4449                 if (acfg->aot_opts.print_skipped_methods)
4450                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4451                 InterlockedIncrement (&acfg->stats.abscount);
4452                 mono_destroy_compile (cfg);
4453                 return;
4454         }
4455
4456         /* Lock for the rest of the code */
4457         mono_acfg_lock (acfg);
4458
4459         /*
4460          * Check for methods/klasses we can't encode.
4461          */
4462         skip = FALSE;
4463         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4464                 if (!can_encode_patch (acfg, patch_info))
4465                         skip = TRUE;
4466         }
4467
4468         if (skip) {
4469                 if (acfg->aot_opts.print_skipped_methods)
4470                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4471                 acfg->stats.ocount++;
4472                 mono_destroy_compile (cfg);
4473                 mono_acfg_unlock (acfg);
4474                 return;
4475         }
4476
4477         /* Adds generic instances referenced by this method */
4478         /* 
4479          * The depth is used to avoid infinite loops when generic virtual recursion is 
4480          * encountered.
4481          */
4482         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4483         if (depth < 32) {
4484                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4485                         switch (patch_info->type) {
4486                         case MONO_PATCH_INFO_METHOD: {
4487                                 MonoMethod *m = patch_info->data.method;
4488                                 if (m->is_inflated) {
4489                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
4490                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
4491                                                 !method_has_type_vars (m)) {
4492                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4493                                                         if (acfg->aot_opts.full_aot)
4494                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4495                                                 } else {
4496                                                         add_extra_method_with_depth (acfg, m, depth + 1);
4497                                                 }
4498                                         }
4499                                         add_generic_class_with_depth (acfg, m->klass, depth + 5);
4500                                 }
4501                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4502                                         add_extra_method_with_depth (acfg, m, depth + 1);
4503                                 break;
4504                         }
4505                         case MONO_PATCH_INFO_VTABLE: {
4506                                 MonoClass *klass = patch_info->data.klass;
4507
4508                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4509                                         add_generic_class_with_depth (acfg, klass, depth + 5);
4510                                 break;
4511                         }
4512                         default:
4513                                 break;
4514                         }
4515                 }
4516         }
4517
4518         /* Determine whenever the method has GOT slots */
4519         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4520                 switch (patch_info->type) {
4521                 case MONO_PATCH_INFO_GOT_OFFSET:
4522                 case MONO_PATCH_INFO_NONE:
4523                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4524                         break;
4525                 case MONO_PATCH_INFO_IMAGE:
4526                         /* The assembly is stored in GOT slot 0 */
4527                         if (patch_info->data.image != acfg->image)
4528                                 cfg->has_got_slots = TRUE;
4529                         break;
4530                 default:
4531                         if (!is_plt_patch (patch_info))
4532                                 cfg->has_got_slots = TRUE;
4533                         break;
4534                 }
4535         }
4536
4537         if (!cfg->has_got_slots)
4538                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4539
4540         /* 
4541          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4542          */
4543         /* Make a copy of the patch info which is in the mempool */
4544         {
4545                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4546
4547                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4548                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4549
4550                         if (!patches)
4551                                 patches = new_patch_info;
4552                         else
4553                                 patches_end->next = new_patch_info;
4554                         patches_end = new_patch_info;
4555                 }
4556                 cfg->patch_info = patches;
4557         }
4558         /* Make a copy of the unwind info */
4559         {
4560                 GSList *l, *unwind_ops;
4561                 MonoUnwindOp *op;
4562
4563                 unwind_ops = NULL;
4564                 for (l = cfg->unwind_ops; l; l = l->next) {
4565                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4566                         memcpy (op, l->data, sizeof (MonoUnwindOp));
4567                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4568                 }
4569                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4570         }
4571         /* Make a copy of the argument/local info */
4572         {
4573                 MonoInst **args, **locals;
4574                 MonoMethodSignature *sig;
4575                 MonoMethodHeader *header;
4576                 int i;
4577                 
4578                 sig = mono_method_signature (method);
4579                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4580                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4581                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4582                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4583                 }
4584                 cfg->args = args;
4585
4586                 header = mono_method_get_header (method);
4587                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4588                 for (i = 0; i < header->num_locals; ++i) {
4589                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4590                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4591                 }
4592                 cfg->locals = locals;
4593         }
4594
4595         /* Free some fields used by cfg to conserve memory */
4596         mono_mempool_destroy (cfg->mempool);
4597         cfg->mempool = NULL;
4598         g_free (cfg->varinfo);
4599         cfg->varinfo = NULL;
4600         g_free (cfg->vars);
4601         cfg->vars = NULL;
4602         if (cfg->rs) {
4603                 mono_regstate_free (cfg->rs);
4604                 cfg->rs = NULL;
4605         }
4606
4607         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
4608
4609         while (index >= acfg->cfgs_size) {
4610                 MonoCompile **new_cfgs;
4611                 int new_size;
4612
4613                 new_size = acfg->cfgs_size * 2;
4614                 new_cfgs = g_new0 (MonoCompile*, new_size);
4615                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4616                 g_free (acfg->cfgs);
4617                 acfg->cfgs = new_cfgs;
4618                 acfg->cfgs_size = new_size;
4619         }
4620         acfg->cfgs [index] = cfg;
4621
4622         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4623
4624         /*
4625         if (cfg->orig_method->wrapper_type)
4626                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4627         */
4628
4629         mono_acfg_unlock (acfg);
4630
4631         InterlockedIncrement (&acfg->stats.ccount);
4632 }
4633  
4634 static void
4635 compile_thread_main (gpointer *user_data)
4636 {
4637         MonoDomain *domain = user_data [0];
4638         MonoAotCompile *acfg = user_data [1];
4639         GPtrArray *methods = user_data [2];
4640         int i;
4641
4642         mono_thread_attach (domain);
4643
4644         for (i = 0; i < methods->len; ++i)
4645                 compile_method (acfg, g_ptr_array_index (methods, i));
4646 }
4647
4648 static void
4649 load_profile_files (MonoAotCompile *acfg)
4650 {
4651         FILE *infile;
4652         char *tmp;
4653         int file_index, res, method_index, i;
4654         char ver [256];
4655         guint32 token;
4656         GList *unordered;
4657
4658         file_index = 0;
4659         while (TRUE) {
4660                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4661
4662                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4663                         g_free (tmp);
4664                         break;
4665                 }
4666
4667                 infile = fopen (tmp, "r");
4668                 g_assert (infile);
4669
4670                 printf ("Using profile data file '%s'\n", tmp);
4671                 g_free (tmp);
4672
4673                 file_index ++;
4674
4675                 res = fscanf (infile, "%32s\n", ver);
4676                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4677                         printf ("Profile file has wrong version or invalid.\n");
4678                         fclose (infile);
4679                         continue;
4680                 }
4681
4682                 while (TRUE) {
4683                         char name [1024];
4684                         MonoMethodDesc *desc;
4685                         MonoMethod *method;
4686
4687                         if (fgets (name, 1023, infile) == NULL)
4688                                 break;
4689
4690                         /* Kill the newline */
4691                         if (strlen (name) > 0)
4692                                 name [strlen (name) - 1] = '\0';
4693
4694                         desc = mono_method_desc_new (name, TRUE);
4695
4696                         method = mono_method_desc_search_in_image (desc, acfg->image);
4697
4698                         if (method && mono_method_get_token (method)) {
4699                                 token = mono_method_get_token (method);
4700                                 method_index = mono_metadata_token_index (token) - 1;
4701
4702                                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4703                                         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4704                                 }
4705                         } else {
4706                                 //printf ("No method found matching '%s'.\n", name);
4707                         }
4708                 }
4709                 fclose (infile);
4710         }
4711
4712         /* Add missing methods */
4713         unordered = NULL;
4714         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4715                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4716                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4717         }
4718         unordered = g_list_reverse (unordered);
4719         if (acfg->method_order)
4720                 g_list_last (acfg->method_order)->next = unordered;
4721         else
4722                 acfg->method_order = unordered;
4723 }
4724  
4725 /* Used by the LLVM backend */
4726 guint32
4727 mono_aot_get_got_offset (MonoJumpInfo *ji)
4728 {
4729         return get_got_offset (llvm_acfg, ji);
4730 }
4731
4732 char*
4733 mono_aot_get_method_name (MonoCompile *cfg)
4734 {
4735         guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4736
4737         return g_strdup_printf ("m_%x", method_index);
4738 }
4739
4740 char*
4741 mono_aot_get_method_debug_name (MonoCompile *cfg)
4742 {
4743         return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4744 }
4745
4746 char*
4747 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4748 {
4749         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4750         MonoPltEntry *plt_entry;
4751
4752         ji->type = type;
4753         ji->data.target = data;
4754
4755         if (!can_encode_patch (llvm_acfg, ji))
4756                 return NULL;
4757
4758         plt_entry = get_plt_entry (llvm_acfg, ji);
4759
4760         return g_strdup_printf (plt_entry->symbol);
4761 }
4762
4763 MonoJumpInfo*
4764 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4765 {
4766         MonoJumpInfo *res;
4767
4768         mono_acfg_lock (llvm_acfg);
4769         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4770         mono_acfg_unlock (llvm_acfg);
4771
4772         return res;
4773 }
4774
4775 #ifdef ENABLE_LLVM
4776
4777 /*
4778  * emit_llvm_file:
4779  *
4780  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4781  * tools.
4782  */
4783 static void
4784 emit_llvm_file (MonoAotCompile *acfg)
4785 {
4786         char *command, *opts;
4787         int i;
4788         MonoJumpInfo *patch_info;
4789         const char *llc_extra_args;
4790
4791         /*
4792          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4793          * to it.
4794          */
4795
4796         /* Compute the final size of the got */
4797         for (i = 0; i < acfg->nmethods; ++i) {
4798                 if (acfg->cfgs [i]) {
4799                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4800                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4801                                         if (!is_plt_patch (patch_info))
4802                                                 get_got_offset (acfg, patch_info);
4803                                         else
4804                                                 get_plt_entry (acfg, patch_info);
4805                                 }
4806                         }
4807                 }
4808         }
4809
4810         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4811
4812         if (acfg->aot_opts.full_aot) {
4813                 int ntype;
4814
4815                 /* 
4816                  * Need to add the got entries used by the trampolines.
4817                  * This is only a conservative approximation.
4818                  */
4819                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4820                         /* For the generic + rgctx trampolines */
4821                         acfg->final_got_size += 200;
4822                         /* For the specific trampolines */
4823                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4824                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4825                 }
4826         }
4827
4828
4829         mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4830
4831         /*
4832          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4833          * a lot of time, and doesn't seem to save much space.
4834          * The following optimizations cannot be enabled:
4835          * - 'tailcallelim'
4836          * - 'jump-threading' changes our blockaddress references to int constants.
4837          * The opt list below was produced by taking the output of:
4838          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4839          * then removing tailcallelim + the global opts, and adding a second gvn.
4840          */
4841         opts = g_strdup ("-instcombine -simplifycfg");
4842         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");
4843 #if 1
4844         command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4845         printf ("Executing opt: %s\n", command);
4846         if (system (command) != 0) {
4847                 exit (1);
4848         }
4849 #endif
4850         g_free (opts);
4851
4852 #if !LLVM_CHECK_VERSION(2, 8)
4853         /* LLVM 2.8 removed the -f flag ??? */
4854         llc_extra_args = "-f";
4855 #else
4856         llc_extra_args = "";
4857 #endif
4858         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);
4859
4860         printf ("Executing llc: %s\n", command);
4861
4862         if (system (command) != 0) {
4863                 exit (1);
4864         }
4865 }
4866 #endif
4867
4868 static void
4869 emit_code (MonoAotCompile *acfg)
4870 {
4871         int i;
4872         char symbol [256];
4873         char end_symbol [256];
4874         GList *l;
4875
4876 #if defined(TARGET_POWERPC64)
4877         sprintf (symbol, ".Lgot_addr");
4878         emit_section_change (acfg, ".text", 0);
4879         emit_alignment (acfg, 8);
4880         emit_label (acfg, symbol);
4881         emit_pointer (acfg, acfg->got_symbol);
4882 #endif
4883
4884         /* 
4885          * This global symbol is used to compute the address of each method using the
4886          * code_offsets array. It is also used to compute the memory ranges occupied by
4887          * AOT code, so it must be equal to the address of the first emitted method.
4888          */
4889         sprintf (symbol, "methods");
4890         emit_section_change (acfg, ".text", 0);
4891         emit_global (acfg, symbol, TRUE);
4892         emit_alignment (acfg, 8);
4893         if (acfg->llvm) {
4894                 for (i = 0; i < acfg->nmethods; ++i) {
4895                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4896                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4897                                 break;
4898                         }
4899                 }
4900                 if (i == acfg->nmethods)
4901                         /* No LLVM compiled methods */
4902                         emit_label (acfg, symbol);
4903         } else {
4904                 emit_label (acfg, symbol);
4905         }
4906
4907         /* 
4908          * Emit some padding so the local symbol for the first method doesn't have the
4909          * same address as 'methods'.
4910          */
4911         emit_zero_bytes (acfg, 16);
4912
4913         for (l = acfg->method_order; l != NULL; l = l->next) {
4914                 MonoCompile *cfg;
4915                 MonoMethod *method;
4916
4917                 i = GPOINTER_TO_UINT (l->data);
4918
4919                 cfg = acfg->cfgs [i];
4920
4921                 if (!cfg)
4922                         continue;
4923
4924                 method = cfg->orig_method;
4925
4926                 /* Emit unbox trampoline */
4927                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4928                         char call_target [256];
4929
4930                         if (!method->wrapper_type && !method->is_inflated) {
4931                                 g_assert (method->token);
4932                                 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4933                         } else {
4934                                 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4935                         }
4936
4937                         emit_section_change (acfg, ".text", 0);
4938 #ifdef __native_client_codegen__
4939                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4940 #endif
4941                         emit_global (acfg, symbol, TRUE);
4942                         emit_label (acfg, symbol);
4943
4944                         sprintf (call_target, "%s", cfg->asm_symbol);
4945
4946                         arch_emit_unbox_trampoline (acfg, cfg->orig_method, call_target);
4947                 }
4948
4949                 if (cfg->compile_llvm)
4950                         acfg->stats.llvm_count ++;
4951                 else
4952                         emit_method_code (acfg, cfg);
4953         }
4954
4955         sprintf (symbol, "methods_end");
4956         emit_section_change (acfg, ".text", 0);
4957         emit_global (acfg, symbol, FALSE);
4958         emit_alignment (acfg, 8);
4959         emit_label (acfg, symbol);
4960
4961         sprintf (symbol, "code_offsets");
4962         emit_section_change (acfg, RODATA_SECT, 1);
4963         emit_global (acfg, symbol, FALSE);
4964         emit_alignment (acfg, 8);
4965         emit_label (acfg, symbol);
4966
4967         acfg->stats.offsets_size += acfg->nmethods * 4;
4968
4969         sprintf (end_symbol, "methods");
4970         for (i = 0; i < acfg->nmethods; ++i) {
4971                 if (acfg->cfgs [i]) {
4972                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4973                 } else {
4974                         emit_int32 (acfg, 0xffffffff);
4975                 }
4976         }
4977         emit_line (acfg);
4978 }
4979
4980 static void
4981 emit_info (MonoAotCompile *acfg)
4982 {
4983         int i;
4984         char symbol [256];
4985         GList *l;
4986         gint32 *offsets;
4987
4988         offsets = g_new0 (gint32, acfg->nmethods);
4989
4990         for (l = acfg->method_order; l != NULL; l = l->next) {
4991                 i = GPOINTER_TO_UINT (l->data);
4992
4993                 if (acfg->cfgs [i]) {
4994                         emit_method_info (acfg, acfg->cfgs [i]);
4995                         offsets [i] = acfg->cfgs [i]->method_info_offset;
4996                 } else {
4997                         offsets [i] = 0;
4998                 }
4999         }
5000
5001         sprintf (symbol, "method_info_offsets");
5002         emit_section_change (acfg, RODATA_SECT, 1);
5003         emit_global (acfg, symbol, FALSE);
5004         emit_alignment (acfg, 8);
5005         emit_label (acfg, symbol);
5006
5007         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5008
5009         g_free (offsets);
5010 }
5011
5012 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5013
5014 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5015 #define mix(a,b,c) { \
5016         a -= c;  a ^= rot(c, 4);  c += b; \
5017         b -= a;  b ^= rot(a, 6);  a += c; \
5018         c -= b;  c ^= rot(b, 8);  b += a; \
5019         a -= c;  a ^= rot(c,16);  c += b; \
5020         b -= a;  b ^= rot(a,19);  a += c; \
5021         c -= b;  c ^= rot(b, 4);  b += a; \
5022 }
5023 #define final(a,b,c) { \
5024         c ^= b; c -= rot(b,14); \
5025         a ^= c; a -= rot(c,11); \
5026         b ^= a; b -= rot(a,25); \
5027         c ^= b; c -= rot(b,16); \
5028         a ^= c; a -= rot(c,4);  \
5029         b ^= a; b -= rot(a,14); \
5030         c ^= b; c -= rot(b,24); \
5031 }
5032
5033 static guint
5034 mono_aot_type_hash (MonoType *t1)
5035 {
5036         guint hash = t1->type;
5037
5038         hash |= t1->byref << 6; /* do not collide with t1->type values */
5039         switch (t1->type) {
5040         case MONO_TYPE_VALUETYPE:
5041         case MONO_TYPE_CLASS:
5042         case MONO_TYPE_SZARRAY:
5043                 /* check if the distribution is good enough */
5044                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5045         case MONO_TYPE_PTR:
5046                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5047         case MONO_TYPE_ARRAY:
5048                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5049         case MONO_TYPE_GENERICINST:
5050                 return ((hash << 5) - hash) ^ 0;
5051         }
5052         return hash;
5053 }
5054
5055 /*
5056  * mono_aot_method_hash:
5057  *
5058  *   Return a hash code for methods which only depends on metadata.
5059  */
5060 guint32
5061 mono_aot_method_hash (MonoMethod *method)
5062 {
5063         MonoMethodSignature *sig;
5064         MonoClass *klass;
5065         int i, hindex;
5066         int hashes_count;
5067         guint32 *hashes_start, *hashes;
5068         guint32 a, b, c;
5069         MonoGenericInst *ginst = NULL;
5070
5071         /* Similar to the hash in mono_method_get_imt_slot () */
5072
5073         sig = mono_method_signature (method);
5074
5075         if (method->is_inflated)
5076                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5077
5078         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5079         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5080         hashes = hashes_start;
5081
5082         /* Some wrappers are assigned to random classes */
5083         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5084                 klass = method->klass;
5085         else
5086                 klass = mono_defaults.object_class;
5087
5088         if (!method->wrapper_type) {
5089                 char *full_name = mono_type_full_name (&klass->byval_arg);
5090
5091                 hashes [0] = mono_metadata_str_hash (full_name);
5092                 hashes [1] = 0;
5093                 g_free (full_name);
5094         } else {
5095                 hashes [0] = mono_metadata_str_hash (klass->name);
5096                 hashes [1] = mono_metadata_str_hash (klass->name_space);
5097         }
5098         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5099                 /* The method name includes a stringified pointer */
5100                 hashes [2] = 0;
5101         else
5102                 hashes [2] = mono_metadata_str_hash (method->name);
5103         hashes [3] = method->wrapper_type;
5104         hashes [4] = mono_aot_type_hash (sig->ret);
5105         hindex = 5;
5106         for (i = 0; i < sig->param_count; i++) {
5107                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5108         }
5109         if (ginst) {
5110                 for (i = 0; i < ginst->type_argc; ++i)
5111                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5112         }               
5113         g_assert (hindex == hashes_count);
5114
5115         /* Setup internal state */
5116         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5117
5118         /* Handle most of the hashes */
5119         while (hashes_count > 3) {
5120                 a += hashes [0];
5121                 b += hashes [1];
5122                 c += hashes [2];
5123                 mix (a,b,c);
5124                 hashes_count -= 3;
5125                 hashes += 3;
5126         }
5127
5128         /* Handle the last 3 hashes (all the case statements fall through) */
5129         switch (hashes_count) { 
5130         case 3 : c += hashes [2];
5131         case 2 : b += hashes [1];
5132         case 1 : a += hashes [0];
5133                 final (a,b,c);
5134         case 0: /* nothing left to add */
5135                 break;
5136         }
5137         
5138         free (hashes_start);
5139         
5140         return c;
5141 }
5142 #undef rot
5143 #undef mix
5144 #undef final
5145
5146 /*
5147  * mono_aot_wrapper_name:
5148  *
5149  *   Return a string which uniqely identifies the given wrapper method.
5150  */
5151 char*
5152 mono_aot_wrapper_name (MonoMethod *method)
5153 {
5154         char *name, *tmpsig, *klass_desc;
5155
5156         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5157
5158         switch (method->wrapper_type) {
5159         case MONO_WRAPPER_RUNTIME_INVOKE:
5160                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5161                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5162                 else
5163                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5164                 break;
5165         default:
5166                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5167                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5168                 g_free (klass_desc);
5169                 break;
5170         }
5171
5172         g_free (tmpsig);
5173
5174         return name;
5175 }
5176
5177 /*
5178  * mono_aot_get_array_helper_from_wrapper;
5179  *
5180  * Get the helper method in Array called by an array wrapper method.
5181  */
5182 MonoMethod*
5183 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5184 {
5185         MonoMethod *m;
5186         const char *prefix;
5187         MonoGenericContext ctx;
5188         MonoType *args [16];
5189         char *mname, *iname, *s, *s2, *helper_name = NULL;
5190
5191         prefix = "System.Collections.Generic";
5192         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5193         s2 = strstr (s, "`1.");
5194         g_assert (s2);
5195         s2 [0] = '\0';
5196         iname = s;
5197         mname = s2 + 3;
5198
5199         //printf ("X: %s %s\n", iname, mname);
5200
5201         if (!strcmp (iname, "IList"))
5202                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5203         else
5204                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5205         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5206         g_assert (m);
5207         g_free (helper_name);
5208         g_free (s);
5209
5210         if (m->is_generic) {
5211                 memset (&ctx, 0, sizeof (ctx));
5212                 args [0] = &method->klass->element_class->byval_arg;
5213                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5214                 m = mono_class_inflate_generic_method (m, &ctx);
5215         }
5216
5217         return m;
5218 }
5219
5220 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5221
5222 typedef struct HashEntry {
5223     guint32 key, value, index;
5224         struct HashEntry *next;
5225 } HashEntry;
5226
5227 /*
5228  * emit_extra_methods:
5229  *
5230  * Emit methods which are not in the METHOD table, like wrappers.
5231  */
5232 static void
5233 emit_extra_methods (MonoAotCompile *acfg)
5234 {
5235         int i, table_size, buf_size;
5236         char symbol [256];
5237         guint8 *p, *buf;
5238         guint32 *info_offsets;
5239         guint32 hash;
5240         GPtrArray *table;
5241         HashEntry *entry, *new_entry;
5242         int nmethods, max_chain_length;
5243         int *chain_lengths;
5244
5245         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5246
5247         /* Emit method info */
5248         nmethods = 0;
5249         for (i = 0; i < acfg->extra_methods->len; ++i) {
5250                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5251                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5252                 char *name;
5253
5254                 if (!cfg)
5255                         continue;
5256
5257                 buf_size = 10240;
5258                 p = buf = g_malloc (buf_size);
5259
5260                 nmethods ++;
5261
5262                 method = cfg->method_to_register;
5263
5264                 name = NULL;
5265                 if (method->wrapper_type) {
5266                         /* 
5267                          * We encode some wrappers using their name, since encoding them
5268                          * directly would be difficult. This also avoids creating the wrapper
5269                          * methods at runtime, since they are not needed anyway.
5270                          */
5271                         switch (method->wrapper_type) {
5272                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5273                         case MONO_WRAPPER_SYNCHRONIZED:
5274                                 /* encode_method_ref () can handle these */
5275                                 break;
5276                         case MONO_WRAPPER_RUNTIME_INVOKE:
5277                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5278                                         /* Direct wrapper, encode normally */
5279                                         break;
5280                                 /* Fall through */
5281                         default:
5282                                 name = mono_aot_wrapper_name (method);
5283                                 break;
5284                         }
5285                 }
5286
5287                 if (name) {
5288                         encode_value (1, p, &p);
5289                         encode_value (method->wrapper_type, p, &p);
5290                         strcpy ((char*)p, name);
5291                         p += strlen (name ) + 1;
5292                         g_free (name);
5293                 } else {
5294                         encode_value (0, p, &p);
5295                         encode_method_ref (acfg, method, p, &p);
5296                 }
5297
5298                 g_assert ((p - buf) < buf_size);
5299
5300                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5301                 g_free (buf);
5302         }
5303
5304         /*
5305          * Construct a chained hash table for mapping indexes in extra_method_info to
5306          * method indexes.
5307          */
5308         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5309         table = g_ptr_array_sized_new (table_size);
5310         for (i = 0; i < table_size; ++i)
5311                 g_ptr_array_add (table, NULL);
5312         chain_lengths = g_new0 (int, table_size);
5313         max_chain_length = 0;
5314         for (i = 0; i < acfg->extra_methods->len; ++i) {
5315                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5316                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5317                 guint32 key, value;
5318
5319                 if (!cfg)
5320                         continue;
5321
5322                 key = info_offsets [i];
5323                 value = get_method_index (acfg, method);
5324
5325                 hash = mono_aot_method_hash (method) % table_size;
5326
5327                 chain_lengths [hash] ++;
5328                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5329
5330                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5331                 new_entry->key = key;
5332                 new_entry->value = value;
5333
5334                 entry = g_ptr_array_index (table, hash);
5335                 if (entry == NULL) {
5336                         new_entry->index = hash;
5337                         g_ptr_array_index (table, hash) = new_entry;
5338                 } else {
5339                         while (entry->next)
5340                                 entry = entry->next;
5341                         
5342                         entry->next = new_entry;
5343                         new_entry->index = table->len;
5344                         g_ptr_array_add (table, new_entry);
5345                 }
5346         }
5347
5348         //printf ("MAX: %d\n", max_chain_length);
5349
5350         /* Emit the table */
5351         sprintf (symbol, "extra_method_table");
5352         emit_section_change (acfg, RODATA_SECT, 0);
5353         emit_global (acfg, symbol, FALSE);
5354         emit_alignment (acfg, 8);
5355         emit_label (acfg, symbol);
5356
5357         emit_int32 (acfg, table_size);
5358         for (i = 0; i < table->len; ++i) {
5359                 HashEntry *entry = g_ptr_array_index (table, i);
5360
5361                 if (entry == NULL) {
5362                         emit_int32 (acfg, 0);
5363                         emit_int32 (acfg, 0);
5364                         emit_int32 (acfg, 0);
5365                 } else {
5366                         //g_assert (entry->key > 0);
5367                         emit_int32 (acfg, entry->key);
5368                         emit_int32 (acfg, entry->value);
5369                         if (entry->next)
5370                                 emit_int32 (acfg, entry->next->index);
5371                         else
5372                                 emit_int32 (acfg, 0);
5373                 }
5374         }
5375
5376         /* 
5377          * Emit a table reverse mapping method indexes to their index in extra_method_info.
5378          * This is used by mono_aot_find_jit_info ().
5379          */
5380         sprintf (symbol, "extra_method_info_offsets");
5381         emit_section_change (acfg, RODATA_SECT, 0);
5382         emit_global (acfg, symbol, FALSE);
5383         emit_alignment (acfg, 8);
5384         emit_label (acfg, symbol);
5385
5386         emit_int32 (acfg, acfg->extra_methods->len);
5387         for (i = 0; i < acfg->extra_methods->len; ++i) {
5388                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5389
5390                 emit_int32 (acfg, get_method_index (acfg, method));
5391                 emit_int32 (acfg, info_offsets [i]);
5392         }
5393 }       
5394
5395 static void
5396 emit_exception_info (MonoAotCompile *acfg)
5397 {
5398         int i;
5399         char symbol [256];
5400         gint32 *offsets;
5401
5402         offsets = g_new0 (gint32, acfg->nmethods);
5403         for (i = 0; i < acfg->nmethods; ++i) {
5404                 if (acfg->cfgs [i]) {
5405                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
5406                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
5407                 } else {
5408                         offsets [i] = 0;
5409                 }
5410         }
5411
5412         sprintf (symbol, "ex_info_offsets");
5413         emit_section_change (acfg, RODATA_SECT, 1);
5414         emit_global (acfg, symbol, FALSE);
5415         emit_alignment (acfg, 8);
5416         emit_label (acfg, symbol);
5417
5418         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5419         g_free (offsets);
5420 }
5421
5422 static void
5423 emit_unwind_info (MonoAotCompile *acfg)
5424 {
5425         int i;
5426         char symbol [128];
5427
5428         /* 
5429          * The unwind info contains a lot of duplicates so we emit each unique
5430          * entry once, and only store the offset from the start of the table in the
5431          * exception info.
5432          */
5433
5434         sprintf (symbol, "unwind_info");
5435         emit_section_change (acfg, RODATA_SECT, 1);
5436         emit_alignment (acfg, 8);
5437         emit_label (acfg, symbol);
5438         emit_global (acfg, symbol, FALSE);
5439
5440         for (i = 0; i < acfg->unwind_ops->len; ++i) {
5441                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5442                 guint8 *unwind_info;
5443                 guint32 unwind_info_len;
5444                 guint8 buf [16];
5445                 guint8 *p;
5446
5447                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5448
5449                 p = buf;
5450                 encode_value (unwind_info_len, p, &p);
5451                 emit_bytes (acfg, buf, p - buf);
5452                 emit_bytes (acfg, unwind_info, unwind_info_len);
5453
5454                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5455         }
5456 }
5457
5458 static void
5459 emit_class_info (MonoAotCompile *acfg)
5460 {
5461         int i;
5462         char symbol [256];
5463         gint32 *offsets;
5464
5465         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5466         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5467                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5468
5469         sprintf (symbol, "class_info_offsets");
5470         emit_section_change (acfg, RODATA_SECT, 1);
5471         emit_global (acfg, symbol, FALSE);
5472         emit_alignment (acfg, 8);
5473         emit_label (acfg, symbol);
5474
5475         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5476         g_free (offsets);
5477 }
5478
5479 typedef struct ClassNameTableEntry {
5480         guint32 token, index;
5481         struct ClassNameTableEntry *next;
5482 } ClassNameTableEntry;
5483
5484 static void
5485 emit_class_name_table (MonoAotCompile *acfg)
5486 {
5487         int i, table_size;
5488         guint32 token, hash;
5489         MonoClass *klass;
5490         GPtrArray *table;
5491         char *full_name;
5492         char symbol [256];
5493         ClassNameTableEntry *entry, *new_entry;
5494
5495         /*
5496          * Construct a chained hash table for mapping class names to typedef tokens.
5497          */
5498         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5499         table = g_ptr_array_sized_new (table_size);
5500         for (i = 0; i < table_size; ++i)
5501                 g_ptr_array_add (table, NULL);
5502         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5503                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5504                 klass = mono_class_get (acfg->image, token);
5505                 if (!klass)
5506                         continue;
5507                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5508                 hash = mono_metadata_str_hash (full_name) % table_size;
5509                 g_free (full_name);
5510
5511                 /* FIXME: Allocate from the mempool */
5512                 new_entry = g_new0 (ClassNameTableEntry, 1);
5513                 new_entry->token = token;
5514
5515                 entry = g_ptr_array_index (table, hash);
5516                 if (entry == NULL) {
5517                         new_entry->index = hash;
5518                         g_ptr_array_index (table, hash) = new_entry;
5519                 } else {
5520                         while (entry->next)
5521                                 entry = entry->next;
5522                         
5523                         entry->next = new_entry;
5524                         new_entry->index = table->len;
5525                         g_ptr_array_add (table, new_entry);
5526                 }
5527         }
5528
5529         /* Emit the table */
5530         sprintf (symbol, "class_name_table");
5531         emit_section_change (acfg, RODATA_SECT, 0);
5532         emit_global (acfg, symbol, FALSE);
5533         emit_alignment (acfg, 8);
5534         emit_label (acfg, symbol);
5535
5536         /* FIXME: Optimize memory usage */
5537         g_assert (table_size < 65000);
5538         emit_int16 (acfg, table_size);
5539         g_assert (table->len < 65000);
5540         for (i = 0; i < table->len; ++i) {
5541                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5542
5543                 if (entry == NULL) {
5544                         emit_int16 (acfg, 0);
5545                         emit_int16 (acfg, 0);
5546                 } else {
5547                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
5548                         if (entry->next)
5549                                 emit_int16 (acfg, entry->next->index);
5550                         else
5551                                 emit_int16 (acfg, 0);
5552                 }
5553         }
5554 }
5555
5556 static void
5557 emit_image_table (MonoAotCompile *acfg)
5558 {
5559         int i;
5560         char symbol [256];
5561
5562         /*
5563          * The image table is small but referenced in a lot of places.
5564          * So we emit it at once, and reference its elements by an index.
5565          */
5566
5567         sprintf (symbol, "mono_image_table");
5568         emit_section_change (acfg, RODATA_SECT, 1);
5569         emit_global (acfg, symbol, FALSE);
5570         emit_alignment (acfg, 8);
5571         emit_label (acfg, symbol);
5572
5573         emit_int32 (acfg, acfg->image_table->len);
5574         for (i = 0; i < acfg->image_table->len; i++) {
5575                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5576                 MonoAssemblyName *aname = &image->assembly->aname;
5577
5578                 /* FIXME: Support multi-module assemblies */
5579                 g_assert (image->assembly->image == image);
5580
5581                 emit_string (acfg, image->assembly_name);
5582                 emit_string (acfg, image->guid);
5583                 emit_string (acfg, aname->culture ? aname->culture : "");
5584                 emit_string (acfg, (const char*)aname->public_key_token);
5585
5586                 emit_alignment (acfg, 8);
5587                 emit_int32 (acfg, aname->flags);
5588                 emit_int32 (acfg, aname->major);
5589                 emit_int32 (acfg, aname->minor);
5590                 emit_int32 (acfg, aname->build);
5591                 emit_int32 (acfg, aname->revision);
5592         }
5593 }
5594
5595 static void
5596 emit_got_info (MonoAotCompile *acfg)
5597 {
5598         char symbol [256];
5599         int i, first_plt_got_patch, buf_size;
5600         guint8 *p, *buf;
5601         guint32 *got_info_offsets;
5602
5603         /* Add the patches needed by the PLT to the GOT */
5604         acfg->plt_got_offset_base = acfg->got_offset;
5605         first_plt_got_patch = acfg->got_patches->len;
5606         for (i = 1; i < acfg->plt_offset; ++i) {
5607                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5608
5609                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5610         }
5611
5612         acfg->got_offset += acfg->plt_offset;
5613
5614         /**
5615          * FIXME: 
5616          * - optimize offsets table.
5617          * - reduce number of exported symbols.
5618          * - emit info for a klass only once.
5619          * - determine when a method uses a GOT slot which is guaranteed to be already 
5620          *   initialized.
5621          * - clean up and document the code.
5622          * - use String.Empty in class libs.
5623          */
5624
5625         /* Encode info required to decode shared GOT entries */
5626         buf_size = acfg->got_patches->len * 128;
5627         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5628         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5629         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5630         /* Unused */
5631         if (acfg->plt_offset)
5632                 acfg->plt_got_info_offsets [0] = 0;
5633         for (i = 0; i < acfg->got_patches->len; ++i) {
5634                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5635
5636                 p = buf;
5637
5638                 encode_value (ji->type, p, &p);
5639                 encode_patch (acfg, ji, p, &p);
5640
5641                 g_assert (p - buf <= buf_size);
5642                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5643
5644                 if (i >= first_plt_got_patch)
5645                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5646                 acfg->stats.got_info_size += p - buf;
5647         }
5648
5649         /* Emit got_info_offsets table */
5650         sprintf (symbol, "got_info_offsets");
5651         emit_section_change (acfg, RODATA_SECT, 1);
5652         emit_global (acfg, symbol, FALSE);
5653         emit_alignment (acfg, 8);
5654         emit_label (acfg, symbol);
5655
5656         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5657         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5658 }
5659
5660 static void
5661 emit_got (MonoAotCompile *acfg)
5662 {
5663         char symbol [256];
5664
5665         if (!acfg->llvm) {
5666                 /* Don't make GOT global so accesses to it don't need relocations */
5667                 sprintf (symbol, "%s", acfg->got_symbol);
5668                 emit_section_change (acfg, ".bss", 0);
5669                 emit_alignment (acfg, 8);
5670                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5671                 emit_label (acfg, symbol);
5672                 if (acfg->got_offset > 0)
5673                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5674
5675                 sprintf (symbol, "got_end");
5676                 emit_label (acfg, symbol);
5677         }
5678
5679         sprintf (symbol, "mono_aot_got_addr");
5680         emit_section_change (acfg, ".data", 0);
5681         emit_global (acfg, symbol, FALSE);
5682         emit_alignment (acfg, 8);
5683         emit_label (acfg, symbol);
5684         emit_pointer (acfg, acfg->got_symbol);
5685 }
5686
5687 typedef struct GlobalsTableEntry {
5688         guint32 value, index;
5689         struct GlobalsTableEntry *next;
5690 } GlobalsTableEntry;
5691
5692 static void
5693 emit_globals_table (MonoAotCompile *acfg)
5694 {
5695         int i, table_size;
5696         guint32 hash;
5697         GPtrArray *table;
5698         char symbol [256];
5699         GlobalsTableEntry *entry, *new_entry;
5700
5701         /*
5702          * Construct a chained hash table for mapping global names to their index in
5703          * the globals table.
5704          */
5705         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5706         table = g_ptr_array_sized_new (table_size);
5707         for (i = 0; i < table_size; ++i)
5708                 g_ptr_array_add (table, NULL);
5709         for (i = 0; i < acfg->globals->len; ++i) {
5710                 char *name = g_ptr_array_index (acfg->globals, i);
5711
5712                 hash = mono_metadata_str_hash (name) % table_size;
5713
5714                 /* FIXME: Allocate from the mempool */
5715                 new_entry = g_new0 (GlobalsTableEntry, 1);
5716                 new_entry->value = i;
5717
5718                 entry = g_ptr_array_index (table, hash);
5719                 if (entry == NULL) {
5720                         new_entry->index = hash;
5721                         g_ptr_array_index (table, hash) = new_entry;
5722                 } else {
5723                         while (entry->next)
5724                                 entry = entry->next;
5725                         
5726                         entry->next = new_entry;
5727                         new_entry->index = table->len;
5728                         g_ptr_array_add (table, new_entry);
5729                 }
5730         }
5731
5732         /* Emit the table */
5733         sprintf (symbol, ".Lglobals_hash");
5734         emit_section_change (acfg, RODATA_SECT, 0);
5735         emit_alignment (acfg, 8);
5736         emit_label (acfg, symbol);
5737
5738         /* FIXME: Optimize memory usage */
5739         g_assert (table_size < 65000);
5740         emit_int16 (acfg, table_size);
5741         for (i = 0; i < table->len; ++i) {
5742                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5743
5744                 if (entry == NULL) {
5745                         emit_int16 (acfg, 0);
5746                         emit_int16 (acfg, 0);
5747                 } else {
5748                         emit_int16 (acfg, entry->value + 1);
5749                         if (entry->next)
5750                                 emit_int16 (acfg, entry->next->index);
5751                         else
5752                                 emit_int16 (acfg, 0);
5753                 }
5754         }
5755
5756         /* Emit the names */
5757         for (i = 0; i < acfg->globals->len; ++i) {
5758                 char *name = g_ptr_array_index (acfg->globals, i);
5759
5760                 sprintf (symbol, "name_%d", i);
5761                 emit_section_change (acfg, RODATA_SECT, 1);
5762                 emit_label (acfg, symbol);
5763                 emit_string (acfg, name);
5764         }
5765
5766         /* Emit the globals table */
5767         sprintf (symbol, ".Lglobals");
5768         emit_section_change (acfg, ".data", 0);
5769         /* This is not a global, since it is accessed by the init function */
5770         emit_alignment (acfg, 8);
5771         emit_label (acfg, symbol);
5772
5773         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5774         emit_pointer (acfg, symbol);
5775
5776         for (i = 0; i < acfg->globals->len; ++i) {
5777                 char *name = g_ptr_array_index (acfg->globals, i);
5778
5779                 sprintf (symbol, "name_%d", i);
5780                 emit_pointer (acfg, symbol);
5781
5782                 sprintf (symbol, "%s", name);
5783                 emit_pointer (acfg, symbol);
5784         }
5785         /* Null terminate the table */
5786         emit_int32 (acfg, 0);
5787         emit_int32 (acfg, 0);
5788 }
5789
5790 static void
5791 emit_globals (MonoAotCompile *acfg)
5792 {
5793         char *build_info;
5794
5795         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5796
5797         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5798
5799         if (acfg->aot_opts.bind_to_runtime_version) {
5800                 build_info = mono_get_runtime_build_info ();
5801                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5802                 g_free (build_info);
5803         } else {
5804                 emit_string_symbol (acfg, "mono_runtime_version", "");
5805         }
5806
5807         /* 
5808          * When static linking, we emit a global which will point to the symbol table.
5809          */
5810         if (acfg->aot_opts.static_link) {
5811                 char symbol [256];
5812                 char *p;
5813
5814                 /* Emit a string holding the assembly name */
5815                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5816
5817                 emit_globals_table (acfg);
5818
5819                 /* 
5820                  * Emit a global symbol which can be passed by an embedding app to
5821                  * mono_aot_register_module ().
5822                  */
5823 #if defined(__MACH__) && !defined(__native_client_codegen__)
5824                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5825 #else
5826                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5827 #endif
5828
5829                 /* Get rid of characters which cannot occur in symbols */
5830                 p = symbol;
5831                 for (p = symbol; *p; ++p) {
5832                         if (!(isalnum (*p) || *p == '_'))
5833                                 *p = '_';
5834                 }
5835                 acfg->static_linking_symbol = g_strdup (symbol);
5836                 emit_global_inner (acfg, symbol, FALSE);
5837                 emit_alignment (acfg, 8);
5838                 emit_label (acfg, symbol);
5839                 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5840                 emit_pointer (acfg, symbol);
5841         }
5842 }
5843
5844 static void
5845 emit_autoreg (MonoAotCompile *acfg)
5846 {
5847         char *symbol;
5848
5849         /*
5850          * Emit a function into the .ctor section which will be called by the ELF
5851          * loader to register this module with the runtime.
5852          */
5853         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5854                 return;
5855
5856         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5857
5858         arch_emit_autoreg (acfg, symbol);
5859
5860         g_free (symbol);
5861 }       
5862
5863 static void
5864 emit_mem_end (MonoAotCompile *acfg)
5865 {
5866         char symbol [128];
5867
5868         sprintf (symbol, "mem_end");
5869         emit_section_change (acfg, ".text", 1);
5870         emit_global (acfg, symbol, FALSE);
5871         emit_alignment (acfg, 8);
5872         emit_label (acfg, symbol);
5873 }
5874
5875 /*
5876  * Emit a structure containing all the information not stored elsewhere.
5877  */
5878 static void
5879 emit_file_info (MonoAotCompile *acfg)
5880 {
5881         char symbol [128];
5882         int i;
5883         int gc_name_offset;
5884         const char *gc_name;
5885
5886         /*
5887          * The managed allocators are GC specific, so can't use an AOT image created by one GC
5888          * in another.
5889          */
5890         gc_name = mono_gc_get_gc_name ();
5891         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
5892
5893         sprintf (symbol, "mono_aot_file_info");
5894         emit_section_change (acfg, ".data", 0);
5895         emit_alignment (acfg, 8);
5896         emit_label (acfg, symbol);
5897         emit_global (acfg, symbol, FALSE);
5898
5899         /* The data emitted here must match MonoAotFileInfo. */
5900         emit_int32 (acfg, acfg->plt_got_offset_base);
5901         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5902         emit_int32 (acfg, acfg->plt_offset);
5903         emit_int32 (acfg, acfg->nmethods);
5904         emit_int32 (acfg, acfg->flags);
5905         emit_int32 (acfg, acfg->opts);
5906         emit_int32 (acfg, gc_name_offset);
5907
5908         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5909                 emit_int32 (acfg, acfg->num_trampolines [i]);
5910         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5911                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5912         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5913                 emit_int32 (acfg, acfg->trampoline_size [i]);
5914 }
5915
5916 static void
5917 emit_blob (MonoAotCompile *acfg)
5918 {
5919         char symbol [128];
5920
5921         sprintf (symbol, "blob");
5922         emit_section_change (acfg, RODATA_SECT, 1);
5923         emit_global (acfg, symbol, FALSE);
5924         emit_alignment (acfg, 8);
5925         emit_label (acfg, symbol);
5926
5927         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5928 }
5929
5930 static void
5931 emit_dwarf_info (MonoAotCompile *acfg)
5932 {
5933 #ifdef EMIT_DWARF_INFO
5934         int i;
5935         char symbol [128], symbol2 [128];
5936
5937         /* DIEs for methods */
5938         for (i = 0; i < acfg->nmethods; ++i) {
5939                 MonoCompile *cfg = acfg->cfgs [i];
5940
5941                 if (!cfg)
5942                         continue;
5943
5944                 // FIXME: LLVM doesn't define .Lme_...
5945                 if (cfg->compile_llvm)
5946                         continue;
5947
5948                 sprintf (symbol, "%s", cfg->asm_symbol);
5949                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5950
5951                 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 ()));
5952         }
5953 #endif
5954 }
5955
5956 static void
5957 collect_methods (MonoAotCompile *acfg)
5958 {
5959         int i;
5960         MonoImage *image = acfg->image;
5961
5962         /* Collect methods */
5963         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5964                 MonoMethod *method;
5965                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5966
5967                 method = mono_get_method (acfg->image, token, NULL);
5968
5969                 if (!method) {
5970                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5971                         exit (1);
5972                 }
5973                         
5974                 /* Load all methods eagerly to skip the slower lazy loading code */
5975                 mono_class_setup_methods (method->klass);
5976
5977                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5978                         /* Compile the wrapper instead */
5979                         /* We do this here instead of add_wrappers () because it is easy to do it here */
5980                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5981                         method = wrapper;
5982                 }
5983
5984                 /* FIXME: Some mscorlib methods don't have debug info */
5985                 /*
5986                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5987                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5988                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5989                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5990                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5991                                 if (!mono_debug_lookup_method (method)) {
5992                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5993                                         exit (1);
5994                                 }
5995                         }
5996                 }
5997                 */
5998
5999                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6000                 add_method_with_index (acfg, method, i, FALSE);
6001                 acfg->method_index ++;
6002         }
6003
6004         add_generic_instances (acfg);
6005
6006         if (acfg->aot_opts.full_aot)
6007                 add_wrappers (acfg);
6008 }
6009
6010 static void
6011 compile_methods (MonoAotCompile *acfg)
6012 {
6013         int i, methods_len;
6014
6015         if (acfg->aot_opts.nthreads > 0) {
6016                 GPtrArray *frag;
6017                 int len, j;
6018                 GPtrArray *threads;
6019                 HANDLE handle;
6020                 gpointer *user_data;
6021                 MonoMethod **methods;
6022
6023                 methods_len = acfg->methods->len;
6024
6025                 len = acfg->methods->len / acfg->aot_opts.nthreads;
6026                 g_assert (len > 0);
6027                 /* 
6028                  * Partition the list of methods into fragments, and hand it to threads to
6029                  * process.
6030                  */
6031                 threads = g_ptr_array_new ();
6032                 /* Make a copy since acfg->methods is modified by compile_method () */
6033                 methods = g_new0 (MonoMethod*, methods_len);
6034                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6035                 for (i = 0; i < methods_len; ++i)
6036                         methods [i] = g_ptr_array_index (acfg->methods, i);
6037                 i = 0;
6038                 while (i < methods_len) {
6039                         frag = g_ptr_array_new ();
6040                         for (j = 0; j < len; ++j) {
6041                                 if (i < methods_len) {
6042                                         g_ptr_array_add (frag, methods [i]);
6043                                         i ++;
6044                                 }
6045                         }
6046
6047                         user_data = g_new0 (gpointer, 3);
6048                         user_data [0] = mono_domain_get ();
6049                         user_data [1] = acfg;
6050                         user_data [2] = frag;
6051                         
6052                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6053                         g_ptr_array_add (threads, handle);
6054                 }
6055                 g_free (methods);
6056
6057                 for (i = 0; i < threads->len; ++i) {
6058                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6059                 }
6060         } else {
6061                 methods_len = 0;
6062         }
6063
6064         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6065         for (i = methods_len; i < acfg->methods->len; ++i) {
6066                 /* This can new methods to acfg->methods */
6067                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6068         }
6069 }
6070
6071 static int
6072 compile_asm (MonoAotCompile *acfg)
6073 {
6074         char *command, *objfile;
6075         char *outfile_name, *tmp_outfile_name;
6076         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6077
6078 #if defined(TARGET_AMD64)
6079 #define AS_OPTIONS "--64"
6080 #elif defined(TARGET_POWERPC64)
6081 #define AS_OPTIONS "-a64 -mppc64"
6082 #define LD_OPTIONS "-m elf64ppc"
6083 #elif defined(sparc) && SIZEOF_VOID_P == 8
6084 #define AS_OPTIONS "-xarch=v9"
6085 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6086 #define AS_OPTIONS "-arch i386 -W"
6087 #else
6088 #define AS_OPTIONS ""
6089 #endif
6090
6091 #ifdef __native_client_codegen__
6092 #define AS_NAME "nacl-as"
6093 #else
6094 #define AS_NAME "as"
6095 #endif
6096
6097 #ifndef LD_OPTIONS
6098 #define LD_OPTIONS ""
6099 #endif
6100
6101 #ifdef ENABLE_LLVM
6102 #define EH_LD_OPTIONS "--eh-frame-hdr"
6103 #else
6104 #define EH_LD_OPTIONS ""
6105 #endif
6106
6107         if (acfg->aot_opts.asm_only) {
6108                 printf ("Output file: '%s'.\n", acfg->tmpfname);
6109                 if (acfg->aot_opts.static_link)
6110                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6111                 return 0;
6112         }
6113
6114         if (acfg->aot_opts.static_link) {
6115                 if (acfg->aot_opts.outfile)
6116                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6117                 else
6118                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
6119         } else {
6120                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6121         }
6122         command = g_strdup_printf ("%s%s %s %s -o %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->tmpfname, objfile);
6123         printf ("Executing the native assembler: %s\n", command);
6124         if (system (command) != 0) {
6125                 g_free (command);
6126                 g_free (objfile);
6127                 return 1;
6128         }
6129
6130         g_free (command);
6131
6132         if (acfg->aot_opts.static_link) {
6133                 printf ("Output file: '%s'.\n", objfile);
6134                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6135                 g_free (objfile);
6136                 return 0;
6137         }
6138
6139         if (acfg->aot_opts.outfile)
6140                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6141         else
6142                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6143
6144         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6145
6146 #if defined(sparc)
6147         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6148 #elif defined(__ppc__) && defined(__MACH__)
6149         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6150 #elif defined(HOST_WIN32)
6151         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6152 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6153         command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6154 #else
6155         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6156 #endif
6157         printf ("Executing the native linker: %s\n", command);
6158         if (system (command) != 0) {
6159                 g_free (tmp_outfile_name);
6160                 g_free (outfile_name);
6161                 g_free (command);
6162                 g_free (objfile);
6163                 return 1;
6164         }
6165
6166         g_free (command);
6167         unlink (objfile);
6168         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6169         printf ("Stripping the binary: %s\n", com);
6170         system (com);
6171         g_free (com);*/
6172
6173 #if defined(TARGET_ARM) && !defined(__MACH__)
6174         /* 
6175          * gas generates 'mapping symbols' each time code and data is mixed, which 
6176          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6177          */
6178         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6179         printf ("Stripping the binary: %s\n", command);
6180         if (system (command) != 0) {
6181                 g_free (tmp_outfile_name);
6182                 g_free (outfile_name);
6183                 g_free (command);
6184                 g_free (objfile);
6185                 return 1;
6186         }
6187 #endif
6188
6189         rename (tmp_outfile_name, outfile_name);
6190
6191         g_free (tmp_outfile_name);
6192         g_free (outfile_name);
6193         g_free (objfile);
6194
6195         if (acfg->aot_opts.save_temps)
6196                 printf ("Retained input file.\n");
6197         else
6198                 unlink (acfg->tmpfname);
6199
6200         return 0;
6201 }
6202
6203 static MonoAotCompile*
6204 acfg_create (MonoAssembly *ass, guint32 opts)
6205 {
6206         MonoImage *image = ass->image;
6207         MonoAotCompile *acfg;
6208         int i;
6209
6210         acfg = g_new0 (MonoAotCompile, 1);
6211         acfg->methods = g_ptr_array_new ();
6212         acfg->method_indexes = g_hash_table_new (NULL, NULL);
6213         acfg->method_depth = g_hash_table_new (NULL, NULL);
6214         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6215         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6216         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6217         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6218         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6219                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6220         acfg->got_patches = g_ptr_array_new ();
6221         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6222         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6223         acfg->image_hash = g_hash_table_new (NULL, NULL);
6224         acfg->image_table = g_ptr_array_new ();
6225         acfg->globals = g_ptr_array_new ();
6226         acfg->image = image;
6227         acfg->opts = opts;
6228         acfg->mempool = mono_mempool_new ();
6229         acfg->extra_methods = g_ptr_array_new ();
6230         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6231         acfg->unwind_ops = g_ptr_array_new ();
6232         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6233         InitializeCriticalSection (&acfg->mutex);
6234
6235         return acfg;
6236 }
6237
6238 static void
6239 acfg_free (MonoAotCompile *acfg)
6240 {
6241         int i;
6242
6243         img_writer_destroy (acfg->w);
6244         for (i = 0; i < acfg->nmethods; ++i)
6245                 if (acfg->cfgs [i])
6246                         g_free (acfg->cfgs [i]);
6247         g_free (acfg->cfgs);
6248         g_free (acfg->static_linking_symbol);
6249         g_free (acfg->got_symbol);
6250         g_free (acfg->plt_symbol);
6251         g_ptr_array_free (acfg->methods, TRUE);
6252         g_ptr_array_free (acfg->got_patches, TRUE);
6253         g_ptr_array_free (acfg->image_table, TRUE);
6254         g_ptr_array_free (acfg->globals, TRUE);
6255         g_ptr_array_free (acfg->unwind_ops, TRUE);
6256         g_hash_table_destroy (acfg->method_indexes);
6257         g_hash_table_destroy (acfg->method_depth);
6258         g_hash_table_destroy (acfg->plt_offset_to_entry);
6259         g_hash_table_destroy (acfg->patch_to_plt_entry);
6260         g_hash_table_destroy (acfg->patch_to_got_offset);
6261         g_hash_table_destroy (acfg->method_to_cfg);
6262         g_hash_table_destroy (acfg->token_info_hash);
6263         g_hash_table_destroy (acfg->image_hash);
6264         g_hash_table_destroy (acfg->unwind_info_offsets);
6265         g_hash_table_destroy (acfg->method_label_hash);
6266         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6267                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6268         g_free (acfg->patch_to_got_offset_by_type);
6269         mono_mempool_destroy (acfg->mempool);
6270         g_free (acfg);
6271 }
6272
6273 int
6274 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6275 {
6276         MonoImage *image = ass->image;
6277         int i, res;
6278         MonoAotCompile *acfg;
6279         char *outfile_name, *tmp_outfile_name, *p;
6280         TV_DECLARE (atv);
6281         TV_DECLARE (btv);
6282
6283         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6284
6285         acfg = acfg_create (ass, opts);
6286
6287         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6288         acfg->aot_opts.write_symbols = TRUE;
6289         acfg->aot_opts.ntrampolines = 1024;
6290         acfg->aot_opts.nrgctx_trampolines = 1024;
6291         acfg->aot_opts.nimt_trampolines = 128;
6292
6293         mono_aot_parse_options (aot_options, &acfg->aot_opts);
6294
6295         if (acfg->aot_opts.static_link)
6296                 acfg->aot_opts.autoreg = TRUE;
6297
6298         //acfg->aot_opts.print_skipped_methods = TRUE;
6299
6300 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6301         if (acfg->aot_opts.full_aot) {
6302                 printf ("--aot=full is not supported on this platform.\n");
6303                 return 1;
6304         }
6305 #endif
6306
6307         if (acfg->aot_opts.static_link)
6308                 acfg->aot_opts.asm_writer = TRUE;
6309
6310         if (acfg->aot_opts.soft_debug) {
6311                 MonoDebugOptions *opt = mini_get_debug_options ();
6312
6313                 opt->mdb_optimizations = TRUE;
6314                 opt->gen_seq_points = TRUE;
6315
6316                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6317                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6318                         return 1;
6319                 }
6320                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6321         }
6322
6323         if (mono_use_llvm) {
6324                 acfg->llvm = TRUE;
6325                 acfg->aot_opts.asm_writer = TRUE;
6326                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6327         }
6328
6329         if (acfg->aot_opts.full_aot)
6330                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6331
6332         load_profile_files (acfg);
6333
6334         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6335 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6336         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6337 #endif
6338         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6339
6340         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6341         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6342
6343         /* Get rid of characters which cannot occur in symbols */
6344         for (p = acfg->got_symbol_base; *p; ++p) {
6345                 if (!(isalnum (*p) || *p == '_'))
6346                         *p = '_';
6347         }
6348         for (p = acfg->plt_symbol; *p; ++p) {
6349                 if (!(isalnum (*p) || *p == '_'))
6350                         *p = '_';
6351         }
6352
6353         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6354
6355         /*
6356          * The prefix LLVM likes to put in front of symbol names on darwin.
6357          * The mach-os specs require this for globals, but LLVM puts them in front of all
6358          * symbols. We need to handle this, since we need to refer to LLVM generated
6359          * symbols.
6360          */
6361         acfg->llvm_label_prefix = "";
6362         if (acfg->llvm)
6363                 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6364
6365         acfg->method_index = 1;
6366
6367         collect_methods (acfg);
6368
6369         acfg->cfgs_size = acfg->methods->len + 32;
6370         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6371
6372         /* PLT offset 0 is reserved for the PLT trampoline */
6373         acfg->plt_offset = 1;
6374
6375 #ifdef ENABLE_LLVM
6376         if (acfg->llvm) {
6377                 llvm_acfg = acfg;
6378                 mono_llvm_create_aot_module (acfg->got_symbol_base);
6379         }
6380 #endif
6381
6382         /* GOT offset 0 is reserved for the address of the current assembly */
6383         {
6384                 MonoJumpInfo *ji;
6385
6386                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6387                 ji->type = MONO_PATCH_INFO_IMAGE;
6388                 ji->data.image = acfg->image;
6389
6390                 get_got_offset (acfg, ji);
6391
6392                 /* Slot 1 is reserved for the mscorlib got addr */
6393                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6394                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6395                 get_got_offset (acfg, ji);
6396
6397                 /* This is very common */
6398                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6399                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6400                 get_got_offset (acfg, ji);
6401         }
6402
6403         TV_GETTIME (atv);
6404
6405         compile_methods (acfg);
6406
6407         TV_GETTIME (btv);
6408
6409         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6410
6411         TV_GETTIME (atv);
6412
6413 #ifdef ENABLE_LLVM
6414         if (acfg->llvm) {
6415                 if (acfg->aot_opts.asm_only) {
6416                         if (acfg->aot_opts.outfile)
6417                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6418                         else
6419                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6420                 } else {
6421                         acfg->tmpfname = g_strdup ("temp.s");
6422                 }
6423
6424                 emit_llvm_file (acfg);
6425         }
6426 #endif
6427
6428         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6429                 if (acfg->aot_opts.outfile)
6430                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6431                 else
6432                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6433
6434                 /* 
6435                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
6436                  * it might be in another file system so the rename () won't work.
6437                  */
6438                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6439
6440                 acfg->fp = fopen (tmp_outfile_name, "w");
6441                 if (!acfg->fp) {
6442                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6443                         return 1;
6444                 }
6445
6446                 acfg->w = img_writer_create (acfg->fp, TRUE);
6447                 acfg->use_bin_writer = TRUE;
6448         } else {
6449                 if (acfg->llvm) {
6450                         /* Append to the .s file created by llvm */
6451                         /* FIXME: Use multiple files instead */
6452                         acfg->fp = fopen (acfg->tmpfname, "a+");
6453                 } else {
6454                         if (acfg->aot_opts.asm_only) {
6455                                 if (acfg->aot_opts.outfile)
6456                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6457                                 else
6458                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6459                                 acfg->fp = fopen (acfg->tmpfname, "w+");
6460                         } else {
6461                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6462                                 acfg->fp = fdopen (i, "w+");
6463                         }
6464                         g_assert (acfg->fp);
6465                 }
6466                 acfg->w = img_writer_create (acfg->fp, FALSE);
6467                 
6468                 tmp_outfile_name = NULL;
6469                 outfile_name = NULL;
6470         }
6471
6472         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6473
6474         /* Compute symbols for methods */
6475         for (i = 0; i < acfg->nmethods; ++i) {
6476                 if (acfg->cfgs [i]) {
6477                         MonoCompile *cfg = acfg->cfgs [i];
6478                         int method_index = get_method_index (acfg, cfg->orig_method);
6479
6480                         cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6481                 }
6482         }
6483
6484         if (!acfg->aot_opts.nodebug)
6485                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6486
6487         img_writer_emit_start (acfg->w);
6488
6489         if (acfg->dwarf)
6490                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6491
6492         emit_code (acfg);
6493
6494         emit_info (acfg);
6495
6496         emit_extra_methods (acfg);
6497
6498         emit_trampolines (acfg);
6499
6500         emit_class_name_table (acfg);
6501
6502         emit_got_info (acfg);
6503
6504         emit_exception_info (acfg);
6505
6506         emit_unwind_info (acfg);
6507
6508         emit_class_info (acfg);
6509
6510         emit_plt (acfg);
6511
6512         emit_image_table (acfg);
6513
6514         emit_got (acfg);
6515
6516         emit_file_info (acfg);
6517
6518         emit_blob (acfg);
6519
6520         emit_globals (acfg);
6521
6522         emit_autoreg (acfg);
6523
6524         if (acfg->dwarf) {
6525                 emit_dwarf_info (acfg);
6526                 mono_dwarf_writer_close (acfg->dwarf);
6527         }
6528
6529         emit_mem_end (acfg);
6530
6531         TV_GETTIME (btv);
6532
6533         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6534
6535         if (acfg->llvm)
6536                 g_assert (acfg->got_offset <= acfg->final_got_size);
6537
6538         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);
6539
6540         TV_GETTIME (atv);
6541         res = img_writer_emit_writeout (acfg->w);
6542         if (res != 0) {
6543                 acfg_free (acfg);
6544                 return res;
6545         }
6546         if (acfg->use_bin_writer) {
6547                 int err = rename (tmp_outfile_name, outfile_name);
6548
6549                 if (err) {
6550                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6551                         return 1;
6552                 }
6553         } else {
6554                 res = compile_asm (acfg);
6555                 if (res != 0) {
6556                         acfg_free (acfg);
6557                         return res;
6558                 }
6559         }
6560         TV_GETTIME (btv);
6561         acfg->stats.link_time = TV_ELAPSED (atv, btv);
6562
6563         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);
6564         if (acfg->stats.genericcount)
6565                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6566         if (acfg->stats.abscount)
6567                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6568         if (acfg->stats.lmfcount)
6569                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6570         if (acfg->stats.ocount)
6571                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6572         if (acfg->llvm)
6573                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6574         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);
6575         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6576
6577         if (acfg->aot_opts.stats) {
6578                 int i;
6579
6580                 printf ("GOT slot distribution:\n");
6581                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6582                         if (acfg->stats.got_slot_types [i])
6583                                 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6584         }
6585
6586         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);
6587
6588         acfg_free (acfg);
6589         
6590         return 0;
6591 }
6592
6593 #else
6594
6595 /* AOT disabled */
6596
6597 int
6598 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6599 {
6600         return 0;
6601 }
6602
6603 #endif