revert r133848 which broke monobuild
[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  * - reduce the length of the wrapper names.
13  * - aot IMT tables, so we don't have two kinds of aot code.
14  * - optimize the trampolines, generate more code in the arch files.
15  * - make things more consistent with how elf works, for example, use ELF 
16  *   relocations.
17  * Remaining generics sharing work:
18  * - optimize the size of the data which is encoded.
19  * - optimize the runtime loading of data:
20  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
21  *     which loads the debugging+exception handling info for the method. This is a 
22  *     huge waste of time and code, since the rgctx structure is currently empty.
23  *   - every shared method has a MonoGenericJitInfo structure which is only really
24  *     used for handling catch clauses with open types, not a very common use case.
25  */
26
27 #include "config.h"
28 #include <sys/types.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef HAVE_STDINT_H
33 #include <stdint.h>
34 #endif
35 #include <fcntl.h>
36 #include <ctype.h>
37 #include <string.h>
38 #ifndef PLATFORM_WIN32
39 #include <sys/time.h>
40 #else
41 #include <winsock2.h>
42 #include <windows.h>
43 #endif
44
45 #include <errno.h>
46 #include <sys/stat.h>
47
48 #include <mono/metadata/tabledefs.h>
49 #include <mono/metadata/class.h>
50 #include <mono/metadata/object.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/assembly.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/marshal.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/mempool-internals.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/utils/mono-logger.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
65
66 #include "mini.h"
67 #include "image-writer.h"
68 #include "dwarfwriter.h"
69
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71
72 #define TV_DECLARE(name) gint64 name
73 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
74 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75
76 #ifdef PLATFORM_WIN32
77 #define SHARED_EXT ".dll"
78 #elif defined(__ppc__) && defined(__MACH__)
79 #define SHARED_EXT ".dylib"
80 #else
81 #define SHARED_EXT ".so"
82 #endif
83
84 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
85 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
86 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
87
88 typedef struct MonoAotOptions {
89         char *outfile;
90         gboolean save_temps;
91         gboolean write_symbols;
92         gboolean metadata_only;
93         gboolean bind_to_runtime_version;
94         gboolean full_aot;
95         gboolean no_dlsym;
96         gboolean static_link;
97         gboolean asm_only;
98         gboolean asm_writer;
99         gboolean nodebug;
100         int nthreads;
101         int ntrampolines;
102         gboolean print_skipped_methods;
103 } MonoAotOptions;
104
105 typedef struct MonoAotStats {
106         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
107         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
108         int methods_without_got_slots, direct_calls, all_calls;
109         int got_slots;
110         int got_slot_types [MONO_PATCH_INFO_NONE];
111         int jit_time, gen_time, link_time;
112 } MonoAotStats;
113
114 typedef struct MonoAotCompile {
115         MonoImage *image;
116         GPtrArray *methods;
117         GHashTable *method_indexes;
118         MonoCompile **cfgs;
119         int cfgs_size;
120         GHashTable *patch_to_plt_offset;
121         GHashTable *plt_offset_to_patch;
122         GHashTable *patch_to_shared_got_offset;
123         GPtrArray *shared_patches;
124         GHashTable *image_hash;
125         GHashTable *method_to_cfg;
126         GHashTable *token_info_hash;
127         GPtrArray *extra_methods;
128         GPtrArray *image_table;
129         GPtrArray *globals;
130         GList *method_order;
131         guint32 *plt_got_info_offsets;
132         guint32 got_offset, plt_offset, plt_got_offset_base;
133         /* Number of GOT entries reserved for trampolines */
134         guint32 num_trampoline_got_entries;
135         guint32 num_specific_trampolines;
136         guint32 specific_trampoline_size;
137         guint32 specific_trampoline_got_offset_base;
138         /* Same for static rgctx trampolines */
139         guint32 num_static_rgctx_trampolines;
140         guint32 static_rgctx_trampoline_size;
141         guint32 static_rgctx_trampoline_got_offset_base;
142         MonoAotOptions aot_opts;
143         guint32 nmethods;
144         guint32 opts;
145         MonoMemPool *mempool;
146         MonoAotStats stats;
147         int method_index;
148         char *static_linking_symbol;
149         CRITICAL_SECTION mutex;
150         gboolean use_bin_writer;
151         MonoImageWriter *w;
152         MonoDwarfWriter *dwarf;
153         FILE *fp;
154         char *tmpfname;
155         GSList *cie_program;
156         GHashTable *unwind_info_offsets;
157         GPtrArray *unwind_ops;
158         guint32 unwind_info_offset;
159 } MonoAotCompile;
160
161 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
162 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
163
164 #ifdef HAVE_ARRAY_ELEM_INIT
165 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
166 #define MSGSTRFIELD1(line) str##line
167 static const struct msgstr_t {
168 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
169 #include "patch-info.h"
170 #undef PATCH_INFO
171 } opstr = {
172 #define PATCH_INFO(a,b) b,
173 #include "patch-info.h"
174 #undef PATCH_INFO
175 };
176 static const gint16 opidx [] = {
177 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
178 #include "patch-info.h"
179 #undef PATCH_INFO
180 };
181
182 static G_GNUC_UNUSED const char*
183 get_patch_name (int info)
184 {
185         return (const char*)&opstr + opidx [info];
186 }
187
188 #else
189 #define PATCH_INFO(a,b) b,
190 static const char* const
191 patch_types [MONO_PATCH_INFO_NUM + 1] = {
192 #include "patch-info.h"
193         NULL
194 };
195
196 static const char*
197 get_patch_name (int info)
198 {
199         return patch_types [info];
200 }
201
202 #endif
203
204 /* Wrappers around the image writer functions */
205
206 static inline void
207 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
208 {
209         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
210 }
211
212 static inline void
213 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
214 {
215         img_writer_emit_push_section (acfg->w, section_name, subsection);
216 }
217
218 static inline void
219 emit_pop_section (MonoAotCompile *acfg)
220 {
221         img_writer_emit_pop_section (acfg->w);
222 }
223
224 static inline void
225 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
226
227         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
228 }
229
230 static inline void
231 emit_label (MonoAotCompile *acfg, const char *name) 
232
233         img_writer_emit_label (acfg->w, name); 
234 }
235
236 static inline void
237 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
238
239         img_writer_emit_bytes (acfg->w, buf, size); 
240 }
241
242 static inline void
243 emit_string (MonoAotCompile *acfg, const char *value) 
244
245         img_writer_emit_string (acfg->w, value); 
246 }
247
248 static inline void
249 emit_line (MonoAotCompile *acfg) 
250
251         img_writer_emit_line (acfg->w); 
252 }
253
254 static inline void
255 emit_alignment (MonoAotCompile *acfg, int size) 
256
257         img_writer_emit_alignment (acfg->w, size); 
258 }
259
260 static inline void
261 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
262
263         img_writer_emit_pointer_unaligned (acfg->w, target); 
264 }
265
266 static inline void
267 emit_pointer (MonoAotCompile *acfg, const char *target) 
268
269         img_writer_emit_pointer (acfg->w, target); 
270 }
271
272 static inline void
273 emit_int16 (MonoAotCompile *acfg, int value) 
274
275         img_writer_emit_int16 (acfg->w, value); 
276 }
277
278 static inline void
279 emit_int32 (MonoAotCompile *acfg, int value) 
280
281         img_writer_emit_int32 (acfg->w, value); 
282 }
283
284 static inline void
285 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
286
287         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
288 }
289
290 static inline void
291 emit_zero_bytes (MonoAotCompile *acfg, int num) 
292
293         img_writer_emit_zero_bytes (acfg->w, num); 
294 }
295
296 static inline void
297 emit_byte (MonoAotCompile *acfg, guint8 val) 
298
299         img_writer_emit_byte (acfg->w, val); 
300 }
301
302 static G_GNUC_UNUSED void
303 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
304 {
305         img_writer_emit_global (acfg->w, name, func);
306 }
307
308 static void
309 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
310 {
311         if (acfg->aot_opts.no_dlsym) {
312                 g_ptr_array_add (acfg->globals, g_strdup (name));
313         } else {
314                 img_writer_emit_global (acfg->w, name, func);
315         }
316 }
317
318 static void
319 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
320 {
321         img_writer_emit_section_change (acfg->w, ".text", 1);
322         emit_global (acfg, name, FALSE);
323         img_writer_emit_label (acfg->w, name);
324         img_writer_emit_string (acfg->w, value);
325 }
326
327 static G_GNUC_UNUSED void
328 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
329 {
330         do {
331                 guint8 b = value & 0x7f;
332                 value >>= 7;
333                 if (value != 0) /* more bytes to come */
334                         b |= 0x80;
335                 emit_byte (acfg, b);
336         } while (value);
337 }
338
339 static G_GNUC_UNUSED void
340 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
341 {
342         gboolean more = 1;
343         gboolean negative = (value < 0);
344         guint32 size = 64;
345         guint8 byte;
346
347         while (more) {
348                 byte = value & 0x7f;
349                 value >>= 7;
350                 /* the following is unnecessary if the
351                  * implementation of >>= uses an arithmetic rather
352                  * than logical shift for a signed left operand
353                  */
354                 if (negative)
355                         /* sign extend */
356                         value |= - ((gint64)1 <<(size - 7));
357                 /* sign bit of byte is second high order bit (0x40) */
358                 if ((value == 0 && !(byte & 0x40)) ||
359                         (value == -1 && (byte & 0x40)))
360                         more = 0;
361                 else
362                         byte |= 0x80;
363                 emit_byte (acfg, byte);
364         }
365 }
366
367 static G_GNUC_UNUSED void
368 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
369 {
370         guint8 *p = buf;
371
372         do {
373                 guint8 b = value & 0x7f;
374                 value >>= 7;
375                 if (value != 0) /* more bytes to come */
376                         b |= 0x80;
377                 *p ++ = b;
378         } while (value);
379
380         *endbuf = p;
381 }
382
383 static G_GNUC_UNUSED void
384 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
385 {
386         gboolean more = 1;
387         gboolean negative = (value < 0);
388         guint32 size = 32;
389         guint8 byte;
390         guint8 *p = buf;
391
392         while (more) {
393                 byte = value & 0x7f;
394                 value >>= 7;
395                 /* the following is unnecessary if the
396                  * implementation of >>= uses an arithmetic rather
397                  * than logical shift for a signed left operand
398                  */
399                 if (negative)
400                         /* sign extend */
401                         value |= - (1 <<(size - 7));
402                 /* sign bit of byte is second high order bit (0x40) */
403                 if ((value == 0 && !(byte & 0x40)) ||
404                         (value == -1 && (byte & 0x40)))
405                         more = 0;
406                 else
407                         byte |= 0x80;
408                 *p ++= byte;
409         }
410
411         *endbuf = p;
412 }
413
414 /* ARCHITECTURE SPECIFIC CODE */
415
416 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
417 #define EMIT_DWARF_INFO 1
418 #endif
419
420 /*
421  * arch_emit_direct_call:
422  *
423  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
424  * calling code.
425  */
426 static void
427 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
428 {
429 #if defined(TARGET_X86) || defined(TARGET_AMD64)
430         /* Need to make sure this is exactly 5 bytes long */
431         emit_byte (acfg, '\xe8');
432         emit_symbol_diff (acfg, target, ".", -4);
433         *call_size = 5;
434 #elif defined(TARGET_ARM)
435         if (acfg->use_bin_writer) {
436                 guint8 buf [4];
437                 guint8 *code;
438
439                 code = buf;
440                 ARM_BL (code, 0);
441
442                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
443                 emit_bytes (acfg, buf, 4);
444         } else {
445                 img_writer_emit_unset_mode (acfg->w);
446                 fprintf (acfg->fp, "bl %s\n", target);
447         }
448         *call_size = 4;
449 #else
450         g_assert_not_reached ();
451 #endif
452 }
453
454 #ifdef MONO_ARCH_AOT_SUPPORTED
455
456 /*
457  * arch_emit_got_access:
458  *
459  *   The memory pointed to by CODE should hold native code for loading a GOT
460  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
461  * CODE_SIZE is set to the number of bytes emitted.
462  */
463 static void
464 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
465 {
466         /* Emit beginning of instruction */
467         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
468
469         /* Emit the offset */
470 #ifdef TARGET_AMD64
471         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
472 #elif defined(TARGET_X86)
473         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
474 #elif defined(TARGET_ARM)
475         emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
476 #else
477         g_assert_not_reached ();
478 #endif
479
480         *code_size = mono_arch_get_patch_offset (code) + 4;
481 }
482
483 #endif
484
485 /*
486  * arch_emit_plt_entry:
487  *
488  *   Emit code for the PLT entry with index INDEX.
489  */
490 static void
491 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
492 {
493 #if defined(TARGET_X86)
494                 if (index == 0) {
495                         /* It is filled up during loading by the AOT loader. */
496                         emit_zero_bytes (acfg, 16);
497                 } else {
498                         /* Need to make sure this is 9 bytes long */
499                         emit_byte (acfg, '\xe9');
500                         emit_symbol_diff (acfg, "plt", ".", -4);
501                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
502                 }
503 #elif defined(TARGET_AMD64)
504                 /*
505                  * We can't emit jumps because they are 32 bits only so they can't be patched.
506                  * So we make indirect calls through GOT entries which are patched by the AOT 
507                  * loader to point to .Lpd entries. 
508                  * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
509                  */
510                 /* jmpq *<offset>(%rip) */
511                 emit_byte (acfg, '\xff');
512                 emit_byte (acfg, '\x25');
513                 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
514                 /* Used by mono_aot_get_plt_info_offset */
515                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
516 #elif defined(TARGET_ARM)
517                 guint8 buf [256];
518                 guint8 *code;
519
520                 /* FIXME:
521                  * - optimize OP_AOTCONST implementation
522                  * - optimize the PLT entries
523                  * - optimize SWITCH AOT implementation
524                  * - implement IMT support
525                  */
526                 code = buf;
527                 if (acfg->use_bin_writer) {
528                         /* We only emit 1 relocation since we implement it ourselves anyway */
529                         img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
530                         /* FIXME: A 2 instruction encoding is sufficient in most cases */
531                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
532                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
533                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
534                         emit_bytes (acfg, buf, code - buf);
535                         /* FIXME: Get rid of this */
536                         emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
537                         /* Used by mono_aot_get_plt_info_offset */
538                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
539                 } else {
540                         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
541                         ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
542                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
543                         emit_bytes (acfg, buf, code - buf);
544                         emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
545                         /* Used by mono_aot_get_plt_info_offset */
546                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
547                 }
548 #else
549                 g_assert_not_reached ();
550 #endif
551 }
552
553 /*
554  * arch_emit_specific_trampoline:
555  *
556  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
557  * two GOT slots which contain the generic trampoline address and the trampoline
558  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
559  */
560 static void
561 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
562 {
563         /*
564          * The trampolines created here are variations of the specific 
565          * trampolines created in mono_arch_create_specific_trampoline (). The 
566          * differences are:
567          * - the generic trampoline address is taken from a got slot.
568          * - the offset of the got slot where the trampoline argument is stored
569          *   is embedded in the instruction stream, and the generic trampoline
570          *   can load the argument by loading the offset, adding it to the
571          *   address of the trampoline to get the address of the got slot, and
572          *   loading the argument from there.
573          * - all the trampolines should be of the same length.
574          */
575 #if defined(TARGET_AMD64)
576         /* This should be exactly 16 bytes long */
577         *tramp_size = 16;
578         /* call *<offset>(%rip) */
579         emit_byte (acfg, '\x41');
580         emit_byte (acfg, '\xff');
581         emit_byte (acfg, '\x15');
582         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
583         /* This should be relative to the start of the trampoline */
584         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
585         emit_zero_bytes (acfg, 5);
586 #elif defined(TARGET_ARM)
587         guint8 buf [128];
588         guint8 *code;
589
590         /* This should be exactly 28 bytes long */
591         *tramp_size = 28;
592         code = buf;
593         ARM_PUSH (code, 0x5fff);
594         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
595         /* Load the value from the GOT */
596         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
597         /* Branch to it */
598         ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
599         ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
600
601         g_assert (code - buf == 20);
602
603         /* Emit it */
604         emit_bytes (acfg, buf, code - buf);
605         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
606         emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
607 #else
608         g_assert_not_reached ();
609 #endif
610 }
611
612 /*
613  * arch_emit_unbox_trampoline:
614  *
615  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
616  * CALL_TARGET is the symbol pointing to the native code of METHOD.
617  */
618 static void
619 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
620 {
621 #if defined(TARGET_AMD64)
622         guint8 buf [32];
623         guint8 *code;
624         int this_reg;
625
626         this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
627         code = buf;
628         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
629
630         emit_bytes (acfg, buf, code - buf);
631         /* jump <method> */
632         emit_byte (acfg, '\xe9');
633         emit_symbol_diff (acfg, call_target, ".", -4);
634 #elif defined(TARGET_ARM)
635         guint8 buf [128];
636         guint8 *code;
637         int this_pos = 0;
638
639         code = buf;
640
641         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
642                 this_pos = 1;
643
644         ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
645
646         emit_bytes (acfg, buf, code - buf);
647         /* jump to method */
648         if (acfg->use_bin_writer) {
649                 guint8 buf [4];
650                 guint8 *code;
651
652                 code = buf;
653                 ARM_B (code, 0);
654
655                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
656                 emit_bytes (acfg, buf, 4);
657         } else {
658                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
659         }
660 #else
661         g_assert_not_reached ();
662 #endif
663 }
664
665 /*
666  * arch_emit_static_rgctx_trampoline:
667  *
668  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
669  * two GOT slots which contain the rgctx argument, and the method to jump to.
670  * TRAMP_SIZE is set to the size of the emitted trampoline.
671  * These kinds of trampolines cannot be enumerated statically, since there could
672  * be one trampoline per method instantiation, so we emit the same code for all
673  * trampolines, and parameterize them using two GOT slots.
674  */
675 static void
676 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
677 {
678 #if defined(TARGET_AMD64)
679         /* This should be exactly 13 bytes long */
680         *tramp_size = 13;
681
682         /* mov <OFFSET>(%rip), %r10 */
683         emit_byte (acfg, '\x4d');
684         emit_byte (acfg, '\x8b');
685         emit_byte (acfg, '\x15');
686         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
687
688         /* jmp *<offset>(%rip) */
689         emit_byte (acfg, '\xff');
690         emit_byte (acfg, '\x25');
691         emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4);
692 #elif defined(TARGET_ARM)
693         guint8 buf [128];
694         guint8 *code;
695
696         /* This should be exactly 24 bytes long */
697         *tramp_size = 24;
698         code = buf;
699         /* Load rgctx value */
700         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
701         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
702         /* Load branch addr + branch */
703         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
704         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
705
706         g_assert (code - buf == 16);
707
708         /* Emit it */
709         emit_bytes (acfg, buf, code - buf);
710         emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
711         emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
712 #else
713         g_assert_not_reached ();
714 #endif
715 }       
716
717 /*
718  * arch_get_cie_program:
719  *
720  *   Get the unwind bytecode for the DWARF CIE.
721  */
722 static GSList*
723 arch_get_cie_program (void)
724 {
725 #ifdef TARGET_AMD64
726         GSList *l = NULL;
727
728         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
729         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
730
731         return l;
732 #else
733         return NULL;
734 #endif
735 }
736
737 /* END OF ARCH SPECIFIC CODE */
738
739 static guint32
740 mono_get_field_token (MonoClassField *field) 
741 {
742         MonoClass *klass = field->parent;
743         int i;
744
745         for (i = 0; i < klass->field.count; ++i) {
746                 if (field == &klass->fields [i])
747                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
748         }
749
750         g_assert_not_reached ();
751         return 0;
752 }
753
754 static inline void
755 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
756 {
757         guint8 *p = buf;
758
759         //printf ("ENCODE: %d 0x%x.\n", value, value);
760
761         /* 
762          * Same encoding as the one used in the metadata, extended to handle values
763          * greater than 0x1fffffff.
764          */
765         if ((value >= 0) && (value <= 127))
766                 *p++ = value;
767         else if ((value >= 0) && (value <= 16383)) {
768                 p [0] = 0x80 | (value >> 8);
769                 p [1] = value & 0xff;
770                 p += 2;
771         } else if ((value >= 0) && (value <= 0x1fffffff)) {
772                 p [0] = (value >> 24) | 0xc0;
773                 p [1] = (value >> 16) & 0xff;
774                 p [2] = (value >> 8) & 0xff;
775                 p [3] = value & 0xff;
776                 p += 4;
777         }
778         else {
779                 p [0] = 0xff;
780                 p [1] = (value >> 24) & 0xff;
781                 p [2] = (value >> 16) & 0xff;
782                 p [3] = (value >> 8) & 0xff;
783                 p [4] = value & 0xff;
784                 p += 5;
785         }
786         if (endbuf)
787                 *endbuf = p;
788 }
789
790 static guint32
791 get_image_index (MonoAotCompile *cfg, MonoImage *image)
792 {
793         guint32 index;
794
795         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
796         if (index)
797                 return index - 1;
798         else {
799                 index = g_hash_table_size (cfg->image_hash);
800                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
801                 g_ptr_array_add (cfg->image_table, image);
802                 return index;
803         }
804 }
805
806 static guint32
807 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
808 {
809         int i;
810         MonoClass *k = NULL;
811
812         /* FIXME: Search referenced images as well */
813         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
814                 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
815                 if (k == klass)
816                         break;
817         }
818
819         if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
820                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
821         else
822                 return 0;
823 }
824
825 static void
826 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
827
828 /*
829  * encode_klass_ref:
830  *
831  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
832  * standard metadata encoding.
833  */
834 static void
835 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
836 {
837         guint8 *p = buf;
838
839         if (klass->generic_class) {
840                 guint32 token;
841                 g_assert (klass->type_token);
842
843                 /* Find a typespec for a class if possible */
844                 token = find_typespec_for_class (acfg, klass);
845                 if (token) {
846                         encode_value (token, p, &p);
847                         encode_value (get_image_index (acfg, acfg->image), p, &p);
848                 } else {
849                         MonoClass *gclass = klass->generic_class->container_class;
850                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
851                         int i;
852
853                         /* Encode it ourselves */
854                         /* Marker */
855                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
856                         encode_value (MONO_TYPE_GENERICINST, p, &p);
857                         encode_klass_ref (acfg, gclass, p, &p);
858                         encode_value (inst->type_argc, p, &p);
859                         for (i = 0; i < inst->type_argc; ++i)
860                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
861                 }
862         } else if (klass->type_token) {
863                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
864                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
865                 encode_value (get_image_index (acfg, klass->image), p, &p);
866         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
867                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
868                 g_assert (container);
869
870                 /* Marker */
871                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
872                 encode_value (klass->byval_arg.type, p, &p);
873
874                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
875                 
876                 encode_value (container->is_method, p, &p);
877                 if (container->is_method)
878                         encode_method_ref (acfg, container->owner.method, p, &p);
879                 else
880                         encode_klass_ref (acfg, container->owner.klass, p, &p);
881         } else {
882                 /* Array class */
883                 g_assert (klass->rank > 0);
884                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
885                 encode_value (get_image_index (acfg, klass->image), p, &p);
886                 encode_value (klass->rank, p, &p);
887                 encode_klass_ref (acfg, klass->element_class, p, &p);
888         }
889         *endbuf = p;
890 }
891
892 static void
893 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
894 {
895         guint32 token = mono_get_field_token (field);
896         guint8 *p = buf;
897
898         encode_klass_ref (cfg, field->parent, p, &p);
899         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
900         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
901         *endbuf = p;
902 }
903
904 static void
905 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
906 {
907         guint8 *p = buf;
908         int i;
909         MonoGenericInst *inst;
910
911         /* Encode the context */
912         inst = context->class_inst;
913         encode_value (inst ? 1 : 0, p, &p);
914         if (inst) {
915                 encode_value (inst->type_argc, p, &p);
916                 for (i = 0; i < inst->type_argc; ++i)
917                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
918         }
919         inst = context->method_inst;
920         encode_value (inst ? 1 : 0, p, &p);
921         if (inst) {
922                 encode_value (inst->type_argc, p, &p);
923                 for (i = 0; i < inst->type_argc; ++i)
924                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
925         }
926
927         *endbuf = p;
928 }
929
930 #define MAX_IMAGE_INDEX 250
931
932 static void
933 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
934 {
935         guint32 image_index = get_image_index (acfg, method->klass->image);
936         guint32 token = method->token;
937         MonoJumpInfoToken *ji;
938         guint8 *p = buf;
939         char *name;
940
941         /*
942          * The encoding for most methods is as follows:
943          * - image index encoded as a leb128
944          * - token index encoded as a leb128
945          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
946          * types of method encodings.
947          */
948
949         g_assert (image_index < MONO_AOT_METHODREF_MIN);
950
951         /* Mark methods which can't use aot trampolines because they need the further 
952          * processing in mono_magic_trampoline () which requires a MonoMethod*.
953          */
954         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
955                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
956                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
957
958         /* 
959          * Some wrapper methods are shared using their signature, encode their 
960          * stringified signature instead.
961          * FIXME: Optimize disk usage
962          */
963         name = NULL;
964         if (method->wrapper_type) {
965                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
966                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
967                         name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
968                         g_free (tmpsig);
969                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
970                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
971                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
972                         g_free (tmpsig);
973                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
974                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
975                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
976                         g_free (tmpsig);
977                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
978                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
979                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
980                         g_free (tmpsig);
981                 }
982         }
983
984         if (name) {
985                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
986                 strcpy ((char*)p, name);
987                 p += strlen (name) + 1;
988                 g_free (name);
989         } else if (method->wrapper_type) {
990                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
991
992                 encode_value (method->wrapper_type, p, &p);
993
994                 switch (method->wrapper_type) {
995                 case MONO_WRAPPER_REMOTING_INVOKE:
996                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
997                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
998                         MonoMethod *m;
999
1000                         m = mono_marshal_method_from_wrapper (method);
1001                         g_assert (m);
1002                         encode_method_ref (acfg, m, p, &p);
1003                         break;
1004                 }
1005                 case MONO_WRAPPER_PROXY_ISINST:
1006                 case MONO_WRAPPER_LDFLD:
1007                 case MONO_WRAPPER_LDFLDA:
1008                 case MONO_WRAPPER_STFLD:
1009                 case MONO_WRAPPER_ISINST: {
1010                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1011                         encode_klass_ref (acfg, proxy_class, p, &p);
1012                         break;
1013                 }
1014                 case MONO_WRAPPER_LDFLD_REMOTE:
1015                 case MONO_WRAPPER_STFLD_REMOTE:
1016                         break;
1017                 case MONO_WRAPPER_ALLOC: {
1018                         int alloc_type = mono_gc_get_managed_allocator_type (method);
1019                         g_assert (alloc_type != -1);
1020                         encode_value (alloc_type, p, &p);
1021                         break;
1022                 }
1023                 case MONO_WRAPPER_STELEMREF:
1024                         break;
1025                 case MONO_WRAPPER_UNKNOWN:
1026                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1027                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1028                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1029                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1030                         else
1031                                 g_assert_not_reached ();
1032                         break;
1033                 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
1034                 case MONO_WRAPPER_SYNCHRONIZED:
1035                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
1036                         MonoMethod *m;
1037
1038                         m = mono_marshal_method_from_wrapper (method);
1039                         g_assert (m);
1040                         g_assert (m != method);
1041                         encode_method_ref (acfg, m, p, &p);
1042                         break;
1043                 }
1044                 default:
1045                         g_assert_not_reached ();
1046                 }
1047         } else if (mono_method_signature (method)->is_inflated) {
1048                 /* 
1049                  * This is a generic method, find the original token which referenced it and
1050                  * encode that.
1051                  * Obtain the token from information recorded by the JIT.
1052                  */
1053                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1054                 if (ji) {
1055                         image_index = get_image_index (acfg, ji->image);
1056                         g_assert (image_index < MAX_IMAGE_INDEX);
1057                         token = ji->token;
1058
1059                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1060                         encode_value (image_index, p, &p);
1061                         encode_value (token, p, &p);
1062                 } else {
1063                         MonoMethod *declaring;
1064                         MonoGenericContext *context = mono_method_get_context (method);
1065
1066                         g_assert (method->is_inflated);
1067                         declaring = ((MonoMethodInflated*)method)->declaring;
1068
1069                         /*
1070                          * This might be a non-generic method of a generic instance, which 
1071                          * doesn't have a token since the reference is generated by the JIT 
1072                          * like Nullable:Box/Unbox, or by generic sharing.
1073                          */
1074
1075                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1076                         /* Encode the klass */
1077                         encode_klass_ref (acfg, method->klass, p, &p);
1078                         /* Encode the method */
1079                         image_index = get_image_index (acfg, method->klass->image);
1080                         g_assert (image_index < MAX_IMAGE_INDEX);
1081                         g_assert (declaring->token);
1082                         token = declaring->token;
1083                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1084                         encode_value (image_index, p, &p);
1085                         encode_value (token, p, &p);
1086                         encode_generic_context (acfg, context, p, &p);
1087                 }
1088         } else if (token == 0) {
1089                 /* This might be a method of a constructed type like int[,].Set */
1090                 /* Obtain the token from information recorded by the JIT */
1091                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1092                 if (ji) {
1093                         image_index = get_image_index (acfg, ji->image);
1094                         g_assert (image_index < MAX_IMAGE_INDEX);
1095                         token = ji->token;
1096
1097                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1098                         encode_value (image_index, p, &p);
1099                         encode_value (token, p, &p);
1100                 } else {
1101                         /* Array methods */
1102                         g_assert (method->klass->rank);
1103
1104                         /* Encode directly */
1105                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1106                         encode_klass_ref (acfg, method->klass, p, &p);
1107                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1108                                 encode_value (0, p, &p);
1109                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1110                                 encode_value (1, p, &p);
1111                         else if (!strcmp (method->name, "Get"))
1112                                 encode_value (2, p, &p);
1113                         else if (!strcmp (method->name, "Address"))
1114                                 encode_value (3, p, &p);
1115                         else if (!strcmp (method->name, "Set"))
1116                                 encode_value (4, p, &p);
1117                         else
1118                                 g_assert_not_reached ();
1119                 }
1120         } else {
1121                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1122                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1123         }
1124         *endbuf = p;
1125 }
1126
1127 static gint
1128 compare_patches (gconstpointer a, gconstpointer b)
1129 {
1130         int i, j;
1131
1132         i = (*(MonoJumpInfo**)a)->ip.i;
1133         j = (*(MonoJumpInfo**)b)->ip.i;
1134
1135         if (i < j)
1136                 return -1;
1137         else
1138                 if (i > j)
1139                         return 1;
1140         else
1141                 return 0;
1142 }
1143
1144 /*
1145  * is_plt_patch:
1146  *
1147  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1148  * PLT entry.
1149  */
1150 static inline gboolean
1151 is_plt_patch (MonoJumpInfo *patch_info)
1152 {
1153         switch (patch_info->type) {
1154         case MONO_PATCH_INFO_METHOD:
1155         case MONO_PATCH_INFO_INTERNAL_METHOD:
1156         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1157         case MONO_PATCH_INFO_ICALL_ADDR:
1158         case MONO_PATCH_INFO_CLASS_INIT:
1159         case MONO_PATCH_INFO_RGCTX_FETCH:
1160         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1161         case MONO_PATCH_INFO_MONITOR_ENTER:
1162         case MONO_PATCH_INFO_MONITOR_EXIT:
1163                 return TRUE;
1164         default:
1165                 return FALSE;
1166         }
1167 }
1168
1169 /*
1170  * is_shared_got_patch:
1171  *
1172  *   Return whenever PATCH_INFO refers to a patch which needs a shared GOT
1173  * entry.
1174  */
1175 static inline gboolean
1176 is_shared_got_patch (MonoJumpInfo *patch_info)
1177 {
1178         switch (patch_info->type) {
1179         case MONO_PATCH_INFO_VTABLE:
1180         case MONO_PATCH_INFO_CLASS:
1181         case MONO_PATCH_INFO_IID:
1182         case MONO_PATCH_INFO_ADJUSTED_IID:
1183         case MONO_PATCH_INFO_FIELD:
1184         case MONO_PATCH_INFO_SFLDA:
1185         case MONO_PATCH_INFO_DECLSEC:
1186         case MONO_PATCH_INFO_LDTOKEN:
1187         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1188         case MONO_PATCH_INFO_RVA:
1189         case MONO_PATCH_INFO_METHODCONST:
1190         case MONO_PATCH_INFO_IMAGE:
1191                 return TRUE;
1192         default:
1193                 return FALSE;
1194         }
1195 }
1196
1197 gboolean
1198 mono_aot_is_shared_got_patch (MonoJumpInfo *patch_info)
1199 {
1200         return is_shared_got_patch (patch_info);
1201 }
1202
1203 static int
1204 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1205 {
1206         int res = -1;
1207
1208         if (is_plt_patch (patch_info)) {
1209                 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1210
1211                 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1212                         /* 
1213                          * Allocate a separate PLT slot for each such patch, since some plt
1214                          * entries will refer to the method itself, and some will refer to
1215                          * wrapper.
1216                          */
1217                         idx = 0;
1218                 }
1219
1220                 if (idx) {
1221                         res = idx;
1222                 } else {
1223                         MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1224
1225                         res = acfg->plt_offset;
1226                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1227                         g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1228                         acfg->plt_offset ++;
1229                 }
1230         }
1231
1232         return res;
1233 }
1234
1235 /**
1236  * get_got_offset:
1237  *
1238  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1239  * JI could be found if it exists, otherwise allocates a new one.
1240  */
1241 static guint32
1242 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1243 {
1244         guint32 got_offset;
1245
1246         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1247         if (got_offset)
1248                 return got_offset - 1;
1249
1250         got_offset = acfg->got_offset;
1251         acfg->got_offset ++;
1252
1253         acfg->stats.got_slots ++;
1254         acfg->stats.got_slot_types [ji->type] ++;
1255
1256         return got_offset;
1257 }
1258
1259 static guint32
1260 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1261 {
1262         MonoJumpInfo *copy;
1263         guint32 got_offset;
1264
1265         if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1266                 got_offset = get_got_offset (acfg, ji);
1267                 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1268                 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1269                 g_ptr_array_add (acfg->shared_patches, copy);
1270         }
1271
1272         return get_got_offset (acfg, ji);
1273 }
1274
1275 /* Add a method to the list of methods which need to be emitted */
1276 static void
1277 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1278 {
1279         g_assert (method);
1280         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1281                 g_ptr_array_add (acfg->methods, method);
1282                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1283                 acfg->nmethods = acfg->methods->len + 1;
1284         }
1285 }
1286
1287 static guint32
1288 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1289 {
1290         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1291         
1292         g_assert (index);
1293
1294         return index - 1;
1295 }
1296
1297 static int
1298 add_method (MonoAotCompile *acfg, MonoMethod *method)
1299 {
1300         int index;
1301
1302         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1303         if (index)
1304                 return index - 1;
1305
1306         index = acfg->method_index;
1307         add_method_with_index (acfg, method, index);
1308
1309         /* FIXME: Fix quadratic behavior */
1310         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1311
1312         acfg->method_index ++;
1313
1314         return index;
1315 }
1316
1317 static void
1318 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1319 {
1320         int index;
1321
1322         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1323         if (index)
1324                 return;
1325         add_method (acfg, method);
1326         g_ptr_array_add (acfg->extra_methods, method);
1327 }
1328
1329 static void
1330 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1331 {
1332         MonoAotCompile *acfg = user_data;
1333         MonoJitICallInfo *callinfo = value;
1334         MonoMethod *wrapper;
1335         char *name;
1336
1337         if (!callinfo->sig)
1338                 return;
1339
1340         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1341         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1342         g_free (name);
1343
1344         add_method (acfg, wrapper);
1345 }
1346
1347 static MonoMethod*
1348 get_runtime_invoke_sig (MonoMethodSignature *sig)
1349 {
1350         MonoMethodBuilder *mb;
1351         MonoMethod *m;
1352
1353         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1354         m = mono_mb_create_method (mb, sig, 16);
1355         return mono_marshal_get_runtime_invoke (m, FALSE);
1356 }
1357
1358 static void
1359 add_wrappers (MonoAotCompile *acfg)
1360 {
1361         MonoMethod *method, *m;
1362         int i, j, nallocators;
1363         MonoMethodSignature *sig, *csig;
1364         guint32 token;
1365
1366         /* 
1367          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1368          * so there is only one wrapper of a given type, or inlining their contents into their
1369          * callers.
1370          */
1371
1372         /* 
1373          * FIXME: This depends on the fact that different wrappers have different 
1374          * names.
1375          */
1376
1377         /* FIXME: Collect these automatically */
1378
1379         /* Runtime invoke wrappers */
1380
1381         /* void runtime-invoke () [.cctor] */
1382         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1383         csig->ret = &mono_defaults.void_class->byval_arg;
1384         add_method (acfg, get_runtime_invoke_sig (csig));
1385
1386         /* void runtime-invoke () [Finalize] */
1387         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1388         csig->hasthis = 1;
1389         csig->ret = &mono_defaults.void_class->byval_arg;
1390         add_method (acfg, get_runtime_invoke_sig (csig));
1391
1392         /* void runtime-invoke (string) [exception ctor] */
1393         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1394         csig->hasthis = 1;
1395         csig->ret = &mono_defaults.void_class->byval_arg;
1396         csig->params [0] = &mono_defaults.string_class->byval_arg;
1397         add_method (acfg, get_runtime_invoke_sig (csig));
1398
1399         /* void runtime-invoke (string, string) [exception ctor] */
1400         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1401         csig->hasthis = 1;
1402         csig->ret = &mono_defaults.void_class->byval_arg;
1403         csig->params [0] = &mono_defaults.string_class->byval_arg;
1404         csig->params [1] = &mono_defaults.string_class->byval_arg;
1405         add_method (acfg, get_runtime_invoke_sig (csig));
1406
1407         /* string runtime-invoke () [Exception.ToString ()] */
1408         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1409         csig->hasthis = 1;
1410         csig->ret = &mono_defaults.string_class->byval_arg;
1411         add_method (acfg, get_runtime_invoke_sig (csig));
1412
1413         /* void runtime-invoke (string, Exception) [exception ctor] */
1414         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1415         csig->hasthis = 1;
1416         csig->ret = &mono_defaults.void_class->byval_arg;
1417         csig->params [0] = &mono_defaults.string_class->byval_arg;
1418         csig->params [1] = &mono_defaults.exception_class->byval_arg;
1419         add_method (acfg, get_runtime_invoke_sig (csig));
1420
1421         /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1422         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1423         csig->hasthis = 1;
1424         csig->ret = &(mono_class_from_name (
1425                                                                                 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1426         csig->params [0] = &mono_defaults.string_class->byval_arg;
1427         csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1428         add_method (acfg, get_runtime_invoke_sig (csig));
1429
1430         /* runtime-invoke used by finalizers */
1431         add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1432
1433         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1434                 MonoMethod *method;
1435                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1436                 gboolean skip = FALSE;
1437
1438                 method = mono_get_method (acfg->image, token, NULL);
1439
1440                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1441                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1442                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1443                         skip = TRUE;
1444
1445                 if (method->is_generic || method->klass->generic_container)
1446                         skip = TRUE;
1447
1448                 /* Skip methods which can not be handled by get_runtime_invoke () */
1449                 sig = mono_method_signature (method);
1450                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1451                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1452                         skip = TRUE;
1453
1454                 for (j = 0; j < sig->param_count; j++) {
1455                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1456                                 skip = TRUE;
1457                 }
1458
1459                 if (!skip)
1460                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1461         }
1462
1463         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1464                 MonoMethodDesc *desc;
1465                 MonoMethod *orig_method;
1466
1467                 /* JIT icall wrappers */
1468                 /* FIXME: locking */
1469                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1470
1471                 /* Managed Allocators */
1472                 nallocators = mono_gc_get_managed_allocator_types ();
1473                 for (i = 0; i < nallocators; ++i) {
1474                         m = mono_gc_get_managed_allocator_by_type (i);
1475                         if (m)
1476                                 add_method (acfg, m);
1477                 }
1478
1479                 /* stelemref */
1480                 add_method (acfg, mono_marshal_get_stelemref ());
1481
1482                 /* Monitor Enter/Exit */
1483                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1484                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1485                 g_assert (orig_method);
1486                 mono_method_desc_free (desc);
1487                 method = mono_monitor_get_fast_path (orig_method);
1488                 if (method)
1489                         add_method (acfg, method);
1490
1491                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1492                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1493                 g_assert (orig_method);
1494                 mono_method_desc_free (desc);
1495                 method = mono_monitor_get_fast_path (orig_method);
1496                 if (method)
1497                         add_method (acfg, method);
1498         }
1499
1500         /* remoting-invoke wrappers */
1501         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1502                 MonoMethodSignature *sig;
1503                 
1504                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1505                 method = mono_get_method (acfg->image, token, NULL);
1506
1507                 sig = mono_method_signature (method);
1508
1509                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1510                         m = mono_marshal_get_remoting_invoke_with_check (method);
1511
1512                         add_method (acfg, m);
1513                 }
1514         }
1515
1516         /* delegate-invoke wrappers */
1517         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1518                 MonoClass *klass;
1519                 
1520                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1521                 klass = mono_class_get (acfg->image, token);
1522
1523                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1524                         method = mono_get_delegate_invoke (klass);
1525
1526                         m = mono_marshal_get_delegate_invoke (method, NULL);
1527
1528                         add_method (acfg, m);
1529
1530                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1531                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1532
1533                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1534                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1535                 }
1536         }
1537
1538         /* Synchronized wrappers */
1539         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1540                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1541                 method = mono_get_method (acfg->image, token, NULL);
1542
1543                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1544                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1545         }
1546
1547         /* pinvoke wrappers */
1548         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1549                 MonoMethod *method;
1550                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1551
1552                 method = mono_get_method (acfg->image, token, NULL);
1553
1554                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1555                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1556                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1557                 }
1558         }
1559 }
1560
1561 static gboolean
1562 has_type_vars (MonoClass *klass)
1563 {
1564         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1565                 return TRUE;
1566         if (klass->rank)
1567                 return has_type_vars (klass->element_class);
1568         if (klass->generic_class) {
1569                 MonoGenericContext *context = &klass->generic_class->context;
1570                 if (context->class_inst) {
1571                         int i;
1572
1573                         for (i = 0; i < context->class_inst->type_argc; ++i)
1574                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1575                                         return TRUE;
1576                 }
1577         }
1578         return FALSE;
1579 }
1580
1581 static gboolean
1582 method_has_type_vars (MonoMethod *method)
1583 {
1584         if (has_type_vars (method->klass))
1585                 return TRUE;
1586
1587         if (method->is_inflated) {
1588                 MonoGenericContext *context = mono_method_get_context (method);
1589                 if (context->method_inst) {
1590                         int i;
1591
1592                         for (i = 0; i < context->method_inst->type_argc; ++i)
1593                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1594                                         return TRUE;
1595                 }
1596         }
1597         return FALSE;
1598 }
1599
1600 /*
1601  * add_generic_class:
1602  *
1603  *   Add all methods of a generic class.
1604  */
1605 static void
1606 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1607 {
1608         MonoMethod *method;
1609         gpointer iter;
1610
1611         mono_class_init (klass);
1612
1613         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1614                 return;
1615
1616         if (has_type_vars (klass))
1617                 return;
1618
1619         if (!klass->generic_class && !klass->rank)
1620                 return;
1621
1622         /* 
1623          * Add rgctx wrappers for cctors since those are called by the runtime, so 
1624          * there is no methodspec for them. This is needed even for shared classes,
1625          * since rgctx wrappers belong to inflated methods.
1626          */
1627         method = mono_class_get_cctor (klass);
1628         if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
1629                 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1630
1631         iter = NULL;
1632         while ((method = mono_class_get_methods (klass, &iter))) {
1633                 if (mono_method_is_generic_sharable_impl (method, FALSE))
1634                         /* Already added */
1635                         continue;
1636
1637                 if (method->is_generic)
1638                         /* FIXME: */
1639                         continue;
1640
1641                 /*
1642                  * FIXME: Instances which are referenced by these methods are not added,
1643                  * for example Array.Resize<int> for List<int>.Add ().
1644                  */
1645                 add_extra_method (acfg, method);
1646         }
1647
1648         /* 
1649          * For ICollection<T>, where T is a vtype, add instances of the helper methods
1650          * in Array, since a T[] could be cast to ICollection<T>.
1651          */
1652         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
1653                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
1654                 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
1655                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
1656                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
1657                 gpointer iter;
1658                 char *name_prefix;
1659
1660                 if (!strcmp (klass->name, "IEnumerator`1"))
1661                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
1662                 else
1663                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
1664
1665                 /* Add the T[]/InternalEnumerator class */
1666                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
1667                         MonoClass *nclass;
1668
1669                         iter = NULL;
1670                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
1671                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
1672                                         break;
1673                         }
1674                         g_assert (nclass);
1675                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
1676                         add_generic_class (acfg, nclass);
1677                 }
1678
1679                 iter = NULL;
1680                 while ((method = mono_class_get_methods (array_class, &iter))) {
1681                         if (strstr (method->name, name_prefix))
1682                                 add_extra_method (acfg, method);
1683                 }
1684
1685                 g_free (name_prefix);
1686         }
1687 }
1688
1689 /*
1690  * add_generic_instances:
1691  *
1692  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
1693  */
1694 static void
1695 add_generic_instances (MonoAotCompile *acfg)
1696 {
1697         int i;
1698         guint32 token;
1699         MonoMethod *method;
1700         MonoMethodHeader *header;
1701         MonoMethodSignature *sig;
1702         MonoGenericContext *context;
1703
1704         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1705                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1706                 method = mono_get_method (acfg->image, token, NULL);
1707
1708                 context = mono_method_get_context (method);
1709                 if (context && ((context->class_inst && context->class_inst->is_open) ||
1710                                                 (context->method_inst && context->method_inst->is_open)))
1711                         continue;
1712
1713                 if (method->klass->image != acfg->image)
1714                         continue;
1715
1716                 if (mono_method_is_generic_sharable_impl (method, FALSE))
1717                         /* Already added */
1718                         continue;
1719
1720                 add_extra_method (acfg, method);
1721         }
1722
1723         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1724                 MonoClass *klass;
1725
1726                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1727
1728                 klass = mono_class_get (acfg->image, token);
1729                 if (!klass)
1730                         continue;
1731
1732                 add_generic_class (acfg, klass);
1733         }
1734
1735         /* Add types of args/locals */
1736         for (i = 0; i < acfg->methods->len; ++i) {
1737                 int j;
1738
1739                 method = g_ptr_array_index (acfg->methods, i);
1740
1741                 sig = mono_method_signature (method);
1742
1743                 if (sig) {
1744                         for (j = 0; j < sig->param_count; ++j)
1745                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
1746                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
1747                 }
1748
1749                 header = mono_method_get_header (method);
1750
1751                 if (header) {
1752                         for (j = 0; j < header->num_locals; ++j)
1753                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
1754                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
1755                 }
1756         }
1757 }
1758
1759 /*
1760  * emit_and_reloc_code:
1761  *
1762  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1763  * is true, calls are made through the GOT too. This is used for emitting trampolines
1764  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1765  * since trampolines are needed to make PTL work.
1766  */
1767 static void
1768 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1769 {
1770         int i, pindex, start_index, method_index;
1771         GPtrArray *patches;
1772         MonoJumpInfo *patch_info;
1773         MonoMethodHeader *header;
1774         gboolean skip, direct_call;
1775         guint32 got_slot;
1776         char direct_call_target [128];
1777
1778         if (method) {
1779                 header = mono_method_get_header (method);
1780
1781                 method_index = get_method_index (acfg, method);
1782         }
1783
1784         /* Collect and sort relocations */
1785         patches = g_ptr_array_new ();
1786         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1787                 g_ptr_array_add (patches, patch_info);
1788         g_ptr_array_sort (patches, compare_patches);
1789
1790         start_index = 0;
1791         for (i = 0; i < code_len; i++) {
1792                 patch_info = NULL;
1793                 for (pindex = start_index; pindex < patches->len; ++pindex) {
1794                         patch_info = g_ptr_array_index (patches, pindex);
1795                         if (patch_info->ip.i >= i)
1796                                 break;
1797                 }
1798
1799 #ifdef MONO_ARCH_AOT_SUPPORTED
1800                 skip = FALSE;
1801                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1802                         start_index = pindex;
1803
1804                         switch (patch_info->type) {
1805                         case MONO_PATCH_INFO_NONE:
1806                                 break;
1807                         case MONO_PATCH_INFO_GOT_OFFSET: {
1808                                 guint32 offset = mono_arch_get_patch_offset (code + i);
1809                                 emit_bytes (acfg, code + i, offset);
1810                                 emit_symbol_diff (acfg, "got", ".", offset);
1811
1812                                 i += offset + 4 - 1;
1813                                 skip = TRUE;
1814                                 break;
1815                         }
1816                         default: {
1817                                 /*
1818                                  * If this patch is a call, try emitting a direct call instead of
1819                                  * through a PLT entry. This is possible if the called method is in
1820                                  * the same assembly and requires no initialization.
1821                                  */
1822                                 direct_call = FALSE;
1823                                 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1824                                         MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1825                                         if (callee_cfg) {
1826                                                 gboolean direct_callable = TRUE;
1827
1828                                                 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1829                                                         direct_callable = FALSE;
1830                                                 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1831                                                         // FIXME: Maybe call the wrapper directly ?
1832                                                         direct_callable = FALSE;
1833                                                 if (direct_callable) {
1834                                                         //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1835                                                         direct_call = TRUE;
1836                                                         sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1837                                                         patch_info->type = MONO_PATCH_INFO_NONE;
1838                                                         acfg->stats.direct_calls ++;
1839                                                 }
1840                                         }
1841
1842                                         acfg->stats.all_calls ++;
1843                                 }
1844
1845                                 if (!got_only && !direct_call) {
1846                                         int plt_offset = get_plt_offset (acfg, patch_info);
1847                                         if (plt_offset != -1) {
1848                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1849                                                 direct_call = TRUE;
1850                                                 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1851                 
1852                                                 /* Nullify the patch */
1853                                                 patch_info->type = MONO_PATCH_INFO_NONE;
1854                                         }
1855                                 }
1856
1857                                 if (direct_call) {
1858                                         int call_size;
1859
1860                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
1861                                         i += call_size - 1;
1862                                 } else {
1863                                         int code_size;
1864
1865                                         got_slot = get_got_offset (acfg, patch_info);
1866
1867                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1868                                         i += code_size - 1;
1869                                 }
1870                                 skip = TRUE;
1871                         }
1872                         }
1873                 }
1874 #endif /* MONO_ARCH_AOT_SUPPORTED */
1875
1876                 if (!skip) {
1877                         /* Find next patch */
1878                         patch_info = NULL;
1879                         for (pindex = start_index; pindex < patches->len; ++pindex) {
1880                                 patch_info = g_ptr_array_index (patches, pindex);
1881                                 if (patch_info->ip.i >= i)
1882                                         break;
1883                         }
1884
1885                         /* Try to emit multiple bytes at once */
1886                         if (pindex < patches->len && patch_info->ip.i > i) {
1887                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
1888                                 i = patch_info->ip.i - 1;
1889                         } else {
1890                                 emit_bytes (acfg, code + i, 1);
1891                         }
1892                 }
1893         }
1894 }
1895
1896 static void
1897 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1898 {
1899         MonoMethod *method;
1900         int method_index;
1901         guint8 *code;
1902         char symbol [128];
1903         int func_alignment = 16;
1904         MonoMethodHeader *header;
1905
1906         method = cfg->orig_method;
1907         code = cfg->native_code;
1908         header = mono_method_get_header (method);
1909
1910         method_index = get_method_index (acfg, method);
1911
1912         /* Make the labels local */
1913         sprintf (symbol, ".Lm_%x", method_index);
1914
1915         emit_alignment (acfg, func_alignment);
1916         emit_label (acfg, symbol);
1917
1918         if (acfg->aot_opts.write_symbols && !acfg->aot_opts.nodebug && acfg->use_bin_writer) {
1919                 char *full_name;
1920                 /* Emit a local symbol into the symbol table */
1921                 full_name = mono_method_full_name (method, TRUE);
1922                 sprintf (symbol, ".Lme_%x", method_index);
1923                 emit_local_symbol (acfg, full_name, symbol, TRUE);
1924                 emit_label (acfg, full_name);
1925                 g_free (full_name);
1926         }
1927
1928         if (cfg->verbose_level > 0)
1929                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
1930
1931         acfg->stats.code_size += cfg->code_len;
1932
1933         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
1934
1935         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
1936
1937         emit_line (acfg);
1938
1939         sprintf (symbol, ".Lme_%x", method_index);
1940         emit_label (acfg, symbol);
1941 }
1942
1943 /**
1944  * encode_patch:
1945  *
1946  *  Encode PATCH_INFO into its disk representation.
1947  */
1948 static void
1949 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
1950 {
1951         guint8 *p = buf;
1952
1953         switch (patch_info->type) {
1954         case MONO_PATCH_INFO_NONE:
1955                 break;
1956         case MONO_PATCH_INFO_IMAGE:
1957                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
1958                 break;
1959         case MONO_PATCH_INFO_METHOD_REL:
1960                 encode_value ((gint)patch_info->data.offset, p, &p);
1961                 break;
1962         case MONO_PATCH_INFO_SWITCH: {
1963                 gpointer *table = (gpointer *)patch_info->data.table->table;
1964                 int k;
1965
1966                 encode_value (patch_info->data.table->table_size, p, &p);
1967                 for (k = 0; k < patch_info->data.table->table_size; k++)
1968                         encode_value ((int)(gssize)table [k], p, &p);
1969                 break;
1970         }
1971         case MONO_PATCH_INFO_METHODCONST:
1972         case MONO_PATCH_INFO_METHOD:
1973         case MONO_PATCH_INFO_METHOD_JUMP:
1974         case MONO_PATCH_INFO_ICALL_ADDR:
1975         case MONO_PATCH_INFO_METHOD_RGCTX:
1976                 encode_method_ref (acfg, patch_info->data.method, p, &p);
1977                 break;
1978         case MONO_PATCH_INFO_INTERNAL_METHOD:
1979         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1980                 guint32 len = strlen (patch_info->data.name);
1981
1982                 encode_value (len, p, &p);
1983
1984                 memcpy (p, patch_info->data.name, len);
1985                 p += len;
1986                 *p++ = '\0';
1987                 break;
1988         }
1989         case MONO_PATCH_INFO_LDSTR: {
1990                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
1991                 guint32 token = patch_info->data.token->token;
1992                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
1993                 encode_value (image_index, p, &p);
1994                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
1995                 break;
1996         }
1997         case MONO_PATCH_INFO_RVA:
1998         case MONO_PATCH_INFO_DECLSEC:
1999         case MONO_PATCH_INFO_LDTOKEN:
2000         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2001                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2002                 encode_value (patch_info->data.token->token, p, &p);
2003                 encode_value (patch_info->data.token->has_context, p, &p);
2004                 if (patch_info->data.token->has_context)
2005                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2006                 break;
2007         case MONO_PATCH_INFO_EXC_NAME: {
2008                 MonoClass *ex_class;
2009
2010                 ex_class =
2011                         mono_class_from_name (mono_defaults.exception_class->image,
2012                                                                   "System", patch_info->data.target);
2013                 g_assert (ex_class);
2014                 encode_klass_ref (acfg, ex_class, p, &p);
2015                 break;
2016         }
2017         case MONO_PATCH_INFO_R4:
2018                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2019                 break;
2020         case MONO_PATCH_INFO_R8:
2021                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2022                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2023                 break;
2024         case MONO_PATCH_INFO_VTABLE:
2025         case MONO_PATCH_INFO_CLASS:
2026         case MONO_PATCH_INFO_IID:
2027         case MONO_PATCH_INFO_ADJUSTED_IID:
2028                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2029                 break;
2030         case MONO_PATCH_INFO_CLASS_INIT:
2031         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2032                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2033                 break;
2034         case MONO_PATCH_INFO_FIELD:
2035         case MONO_PATCH_INFO_SFLDA:
2036                 encode_field_info (acfg, patch_info->data.field, p, &p);
2037                 break;
2038         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2039                 break;
2040         case MONO_PATCH_INFO_RGCTX_FETCH: {
2041                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2042
2043                 encode_method_ref (acfg, entry->method, p, &p);
2044                 encode_value (entry->in_mrgctx, p, &p);
2045                 encode_value (entry->info_type, p, &p);
2046                 encode_value (entry->data->type, p, &p);
2047                 encode_patch (acfg, entry->data, p, &p);
2048                 break;
2049         }
2050         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2051         case MONO_PATCH_INFO_MONITOR_ENTER:
2052         case MONO_PATCH_INFO_MONITOR_EXIT:
2053                 break;
2054         default:
2055                 g_warning ("unable to handle jump info %d", patch_info->type);
2056                 g_assert_not_reached ();
2057         }
2058
2059         *endbuf = p;
2060 }
2061
2062 static void
2063 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2064 {
2065         guint8 *p = buf;
2066         guint32 pindex;
2067         MonoJumpInfo *patch_info;
2068
2069         encode_value (n_patches, p, &p);
2070
2071         if (n_patches)
2072                 encode_value (first_got_offset, p, &p);
2073
2074         for (pindex = 0; pindex < patches->len; ++pindex) {
2075                 patch_info = g_ptr_array_index (patches, pindex);
2076
2077                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2078                         /* Nothing to do */
2079                         continue;
2080
2081                 encode_value (patch_info->type, p, &p);
2082                 if (is_shared_got_patch (patch_info)) {
2083                         guint32 offset = get_got_offset (acfg, patch_info);
2084                         encode_value (offset, p, &p);
2085                 } else {
2086                         encode_patch (acfg, patch_info, p, &p);
2087                 }
2088         }
2089
2090         *endbuf = p;
2091 }
2092
2093 static void
2094 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2095 {
2096         MonoMethod *method;
2097         GList *l;
2098         int pindex, buf_size, n_patches;
2099         guint8 *code;
2100         char symbol [128];
2101         GPtrArray *patches;
2102         MonoJumpInfo *patch_info;
2103         MonoMethodHeader *header;
2104         guint32 method_index;
2105         guint8 *p, *buf;
2106         guint32 first_got_offset;
2107
2108         method = cfg->orig_method;
2109         code = cfg->native_code;
2110         header = mono_method_get_header (method);
2111
2112         method_index = get_method_index (acfg, method);
2113
2114         /* Make the labels local */
2115         sprintf (symbol, ".Lm_%x_p", method_index);
2116
2117         /* Sort relocations */
2118         patches = g_ptr_array_new ();
2119         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2120                 g_ptr_array_add (patches, patch_info);
2121         g_ptr_array_sort (patches, compare_patches);
2122
2123         first_got_offset = acfg->cfgs [method_index]->got_offset;
2124
2125         /**********************/
2126         /* Encode method info */
2127         /**********************/
2128
2129         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2130         p = buf = g_malloc (buf_size);
2131
2132         if (mono_class_get_cctor (method->klass))
2133                 encode_klass_ref (acfg, method->klass, p, &p);
2134         else
2135                 /* Not needed when loading the method */
2136                 encode_value (0, p, &p);
2137
2138         /* String table */
2139         if (cfg->opt & MONO_OPT_SHARED) {
2140                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2141                 for (l = cfg->ldstr_list; l; l = l->next) {
2142                         encode_value ((long)l->data, p, &p);
2143                 }
2144         }
2145         else
2146                 /* Used only in shared mode */
2147                 g_assert (!cfg->ldstr_list);
2148
2149         n_patches = 0;
2150         for (pindex = 0; pindex < patches->len; ++pindex) {
2151                 patch_info = g_ptr_array_index (patches, pindex);
2152                 
2153                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2154                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2155                         patch_info->type = MONO_PATCH_INFO_NONE;
2156                         /* Nothing to do */
2157                         continue;
2158                 }
2159
2160                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2161                         /* Stored in a GOT slot initialized at module load time */
2162                         patch_info->type = MONO_PATCH_INFO_NONE;
2163                         continue;
2164                 }
2165
2166                 if (is_plt_patch (patch_info)) {
2167                         /* Calls are made through the PLT */
2168                         patch_info->type = MONO_PATCH_INFO_NONE;
2169                         continue;
2170                 }
2171
2172                 n_patches ++;
2173         }
2174
2175         if (n_patches)
2176                 g_assert (cfg->has_got_slots);
2177
2178         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2179
2180         acfg->stats.info_size += p - buf;
2181
2182         /* Emit method info */
2183
2184         emit_label (acfg, symbol);
2185
2186         g_assert (p - buf < buf_size);
2187         emit_bytes (acfg, buf, p - buf);
2188         g_free (buf);
2189 }
2190
2191 static guint32
2192 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2193 {
2194         guint32 cache_index;
2195         guint32 offset;
2196
2197         /* Reuse the unwind module to canonize and store unwind info entries */
2198         cache_index = mono_cache_unwind_info (encoded, encoded_len);
2199
2200         /* Use +/- 1 to distinguish 0s from missing entries */
2201         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2202         if (offset)
2203                 return offset - 1;
2204         else {
2205                 guint8 buf [16];
2206                 guint8 *p;
2207
2208                 /* 
2209                  * It would be easier to use assembler symbols, but the caller needs an
2210                  * offset now.
2211                  */
2212                 offset = acfg->unwind_info_offset;
2213                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2214                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2215
2216                 p = buf;
2217                 encode_value (encoded_len, p, &p);
2218
2219                 acfg->unwind_info_offset += encoded_len + (p - buf);
2220                 return offset;
2221         }
2222 }
2223
2224 static void
2225 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2226 {
2227         MonoMethod *method;
2228         int k, buf_size, method_index;
2229         guint32 debug_info_size;
2230         guint8 *code;
2231         char symbol [128];
2232         MonoMethodHeader *header;
2233         guint8 *p, *buf, *debug_info;
2234         MonoJitInfo *jinfo = cfg->jit_info;
2235         guint32 flags;
2236         gboolean use_unwind_ops = FALSE;
2237
2238         method = cfg->orig_method;
2239         code = cfg->native_code;
2240         header = mono_method_get_header (method);
2241
2242         method_index = get_method_index (acfg, method);
2243
2244         /* Make the labels local */
2245         sprintf (symbol, ".Le_%x_p", method_index);
2246
2247         if (!acfg->aot_opts.nodebug) {
2248                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2249         } else {
2250                 debug_info = NULL;
2251                 debug_info_size = 0;
2252         }
2253
2254         buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2255         p = buf = g_malloc (buf_size);
2256
2257 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2258         use_unwind_ops = cfg->unwind_ops != NULL;
2259 #endif
2260
2261         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2262
2263         encode_value (jinfo->code_size, p, &p);
2264         encode_value (flags, p, &p);
2265
2266         if (use_unwind_ops) {
2267                 guint32 encoded_len;
2268                 guint8 *encoded;
2269
2270                 /* 
2271                  * This is a duplicate of the data in the .debug_frame section, but that
2272                  * section cannot be accessed using the dl interface.
2273                  */
2274                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2275                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2276                 g_free (encoded);
2277         } else {
2278                 encode_value (jinfo->used_regs, p, &p);
2279         }
2280
2281         /* Exception table */
2282         if (header->num_clauses) {
2283                 for (k = 0; k < header->num_clauses; ++k) {
2284                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2285
2286                         encode_value (ei->exvar_offset, p, &p);
2287
2288                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2289                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2290
2291                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2292                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2293                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2294                 }
2295         }
2296
2297         if (jinfo->has_generic_jit_info) {
2298                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2299
2300                 encode_value (gi->has_this ? 1 : 0, p, &p);
2301                 encode_value (gi->this_reg, p, &p);
2302                 encode_value (gi->this_offset, p, &p);
2303
2304                 /* 
2305                  * Need to encode jinfo->method too, since it is not equal to 'method'
2306                  * when using generic sharing.
2307                  */
2308                 encode_method_ref (acfg, jinfo->method, p, &p);
2309         }
2310
2311         g_assert (debug_info_size < buf_size);
2312
2313         encode_value (debug_info_size, p, &p);
2314         if (debug_info_size) {
2315                 memcpy (p, debug_info, debug_info_size);
2316                 p += debug_info_size;
2317                 g_free (debug_info);
2318         }
2319
2320         acfg->stats.ex_info_size += p - buf;
2321
2322         /* Emit info */
2323
2324         emit_label (acfg, symbol);
2325
2326         g_assert (p - buf < buf_size);
2327         emit_bytes (acfg, buf, p - buf);
2328         g_free (buf);
2329 }
2330
2331 static void
2332 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2333 {
2334         MonoClass *klass = mono_class_get (acfg->image, token);
2335         guint8 *p, *buf;
2336         int i, buf_size;
2337         char symbol [128];
2338         gboolean no_special_static, cant_encode;
2339         gpointer iter = NULL;
2340
2341         buf_size = 10240 + (klass->vtable_size * 16);
2342         p = buf = g_malloc (buf_size);
2343
2344         g_assert (klass);
2345
2346         mono_class_init (klass);
2347
2348         mono_class_get_nested_types (klass, &iter);
2349         g_assert (klass->nested_classes_inited);
2350
2351         mono_class_setup_vtable (klass);
2352
2353         /* 
2354          * Emit all the information which is required for creating vtables so
2355          * the runtime does not need to create the MonoMethod structures which
2356          * take up a lot of space.
2357          */
2358
2359         no_special_static = !mono_class_has_special_static_fields (klass);
2360
2361         /* Check whenever we have enough info to encode the vtable */
2362         cant_encode = FALSE;
2363         for (i = 0; i < klass->vtable_size; ++i) {
2364                 MonoMethod *cm = klass->vtable [i];
2365
2366                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2367                         cant_encode = TRUE;
2368         }
2369
2370         if (klass->generic_container || cant_encode) {
2371                 encode_value (-1, p, &p);
2372         } else {
2373                 encode_value (klass->vtable_size, p, &p);
2374                 encode_value ((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);
2375                 if (klass->has_cctor)
2376                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2377                 if (klass->has_finalize)
2378                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2379  
2380                 encode_value (klass->instance_size, p, &p);
2381                 encode_value (mono_class_data_size (klass), p, &p);
2382                 encode_value (klass->packing_size, p, &p);
2383                 encode_value (klass->min_align, p, &p);
2384
2385                 for (i = 0; i < klass->vtable_size; ++i) {
2386                         MonoMethod *cm = klass->vtable [i];
2387
2388                         if (cm)
2389                                 encode_method_ref (acfg, cm, p, &p);
2390                         else
2391                                 encode_value (0, p, &p);
2392                 }
2393         }
2394
2395         acfg->stats.class_info_size += p - buf;
2396
2397         /* Emit the info */
2398         sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2399         emit_label (acfg, symbol);
2400
2401         g_assert (p - buf < buf_size);
2402         emit_bytes (acfg, buf, p - buf);
2403         g_free (buf);
2404 }
2405
2406 /*
2407  * Calls made from AOTed code are routed through a table of jumps similar to the
2408  * ELF PLT (Program Linkage Table). The differences are the following:
2409  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2410  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2411  *   jumps. This means the jumps need to be patched when the address of the callee is
2412  *   known. Initially the PLT entries jump to code which transfers control to the
2413  *   AOT runtime through the first PLT entry.
2414  */
2415 static void
2416 emit_plt (MonoAotCompile *acfg)
2417 {
2418         char symbol [128];
2419         int i;
2420
2421         emit_line (acfg);
2422         sprintf (symbol, "plt");
2423
2424         emit_section_change (acfg, ".text", 0);
2425         emit_global (acfg, symbol, TRUE);
2426 #ifdef TARGET_X86
2427         /* This section will be made read-write by the AOT loader */
2428         emit_alignment (acfg, mono_pagesize ());
2429 #else
2430         emit_alignment (acfg, 16);
2431 #endif
2432         emit_label (acfg, symbol);
2433
2434         for (i = 0; i < acfg->plt_offset; ++i) {
2435                 char label [128];
2436
2437                 sprintf (label, ".Lp_%d", i);
2438                 emit_label (acfg, label);
2439
2440                 /* 
2441                  * The first plt entry is used to transfer code to the AOT loader. 
2442                  */
2443                 arch_emit_plt_entry (acfg, i);
2444         }
2445
2446         sprintf (symbol, "plt_end");
2447         emit_global (acfg, symbol, TRUE);
2448         emit_label (acfg, symbol);
2449 }
2450
2451 static G_GNUC_UNUSED void
2452 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
2453                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2454 {
2455         char symbol [256];
2456         guint32 buf_size;
2457         MonoJumpInfo *patch_info;
2458         guint8 *buf, *p;
2459         GPtrArray *patches;
2460
2461         /* Emit code */
2462
2463         sprintf (symbol, "%s", name);
2464
2465         emit_section_change (acfg, ".text", 0);
2466         emit_global (acfg, symbol, TRUE);
2467         emit_alignment (acfg, 16);
2468         emit_label (acfg, symbol);
2469
2470         sprintf (symbol, ".Lnamed_%s", name);
2471         emit_label (acfg, symbol);
2472
2473         /* 
2474          * The code should access everything through the GOT, so we pass
2475          * TRUE here.
2476          */
2477         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2478
2479         /* Emit info */
2480
2481         /* Sort relocations */
2482         patches = g_ptr_array_new ();
2483         for (patch_info = ji; patch_info; patch_info = patch_info->next)
2484                 g_ptr_array_add (patches, patch_info);
2485         g_ptr_array_sort (patches, compare_patches);
2486
2487         buf_size = patches->len * 128 + 128;
2488         buf = g_malloc (buf_size);
2489         p = buf;
2490
2491         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2492         g_assert (p - buf < buf_size);
2493
2494         sprintf (symbol, "%s_p", name);
2495
2496         emit_section_change (acfg, ".text", 0);
2497         emit_global (acfg, symbol, FALSE);
2498         emit_label (acfg, symbol);
2499                 
2500         emit_bytes (acfg, buf, p - buf);
2501
2502         /* Emit debug info */
2503         if (unwind_ops) {
2504                 char symbol2 [256];
2505
2506                 sprintf (symbol, "%s", name);
2507                 sprintf (symbol2, ".Lnamed_%s", name);
2508
2509                 if (acfg->dwarf)
2510                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2511         }
2512 }
2513
2514 /*
2515  * When running in aot-only mode, we can't create trampolines at runtime, so we create 
2516  * a few, and save them in the AOT file. Normal trampolines embed their argument as a 
2517  * literal inside the trampoline code, we can't do that here, so instead we embed an offset
2518  * which needs to be added to the trampoline address to get the address of the GOT slot
2519  * which contains the argument value.
2520  * The generated trampolines jump to the generic trampolines using another GOT slot, which
2521  * will be setup by the AOT loader to point to the generic trampoline code of the given 
2522  * type.
2523  */
2524 static void
2525 emit_trampolines (MonoAotCompile *acfg)
2526 {
2527         char symbol [256];
2528         int i, tramp_got_offset;
2529 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2530         int tramp_type;
2531         guint32 code_size;
2532         MonoJumpInfo *ji;
2533         guint8 *code;
2534         GSList *unwind_ops;
2535 #endif
2536
2537         if (!acfg->aot_opts.full_aot)
2538                 return;
2539         
2540         g_assert (acfg->image->assembly);
2541
2542         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2543         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2544 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2545                 /*
2546                  * Emit the generic trampolines.
2547                  *
2548                  * We could save some code by treating the generic trampolines as a wrapper
2549                  * method, but that approach has its own complexities, so we choose the simpler
2550                  * method.
2551                  */
2552                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2553                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2554
2555                         /* Emit trampoline code */
2556
2557                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
2558
2559                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2560                 }
2561
2562                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2563                 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2564 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2565                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2566                 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2567                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2568                 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2569 #endif
2570
2571                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2572                 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2573
2574                 /* Emit the exception related code pieces */
2575                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2576                 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2577                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2578                 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2579                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2580                 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2581                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2582                 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2583                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2584                 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2585                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2586                 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2587
2588 #if defined(TARGET_AMD64)
2589                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2590                 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2591 #endif
2592
2593 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2594                 for (i = 0; i < 128; ++i) {
2595                         int offset;
2596
2597                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2598                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2599                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2600                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2601
2602                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2603                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2604                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2605                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2606                 }
2607 #endif
2608
2609 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2610                 {
2611                         GSList *l;
2612
2613                         /* delegate_invoke_impl trampolines */
2614                         l = mono_arch_get_delegate_invoke_impls ();
2615                         while (l) {
2616                                 MonoAotTrampInfo *info = l->data;
2617
2618                                 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
2619                                 l = l->next;
2620                         }
2621                 }
2622 #endif
2623
2624 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
2625
2626                 /*
2627                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2628                  * each class).
2629                  */
2630
2631                 /* Reserve some entries at the end of the GOT for our use */
2632                 acfg->num_trampoline_got_entries = (acfg->num_specific_trampolines * 2) + (acfg->num_static_rgctx_trampolines * 2);
2633
2634                 sprintf (symbol, "specific_trampolines");
2635
2636                 emit_section_change (acfg, ".text", 0);
2637                 emit_global (acfg, symbol, TRUE);
2638                 emit_alignment (acfg, 16);
2639                 emit_label (acfg, symbol);
2640
2641                 tramp_got_offset = acfg->got_offset;
2642
2643                 acfg->specific_trampoline_got_offset_base = tramp_got_offset;
2644
2645                 for (i = 0; i < acfg->num_specific_trampolines; ++i) {
2646                         int tramp_size = 0;
2647
2648                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
2649                         if (!acfg->specific_trampoline_size) {
2650                                 g_assert (tramp_size);
2651                                 acfg->specific_trampoline_size = tramp_size;
2652                         }
2653
2654                         tramp_got_offset += 2;
2655                 }
2656
2657                 sprintf (symbol, "static_rgctx_trampolines");
2658
2659                 emit_section_change (acfg, ".text", 0);
2660                 emit_global (acfg, symbol, TRUE);
2661                 emit_alignment (acfg, 16);
2662                 emit_label (acfg, symbol);
2663
2664                 acfg->static_rgctx_trampoline_got_offset_base = tramp_got_offset;
2665
2666                 for (i = 0; i < acfg->num_static_rgctx_trampolines; ++i) {
2667                         int tramp_size = 0;
2668
2669                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
2670                         if (!acfg->static_rgctx_trampoline_size) {
2671                                 g_assert (tramp_size);
2672                                 acfg->static_rgctx_trampoline_size = tramp_size;
2673                         }
2674
2675                         tramp_got_offset += 2;
2676                 }
2677         }
2678
2679         /* Unbox trampolines */
2680         for (i = 0; i < acfg->methods->len; ++i) {
2681                 MonoMethod *method = g_ptr_array_index (acfg->methods, i);
2682                 MonoCompile *cfg;
2683                 char call_target [256];
2684
2685                 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2686                 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2687                         continue;
2688
2689                 if (!method->wrapper_type && !method->is_inflated) {
2690                         g_assert (method->token);
2691                         sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2692                 } else {
2693                         sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2694                 }
2695
2696                 emit_section_change (acfg, ".text", 0);
2697                 emit_global (acfg, symbol, TRUE);
2698                 emit_label (acfg, symbol);
2699
2700                 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2701
2702                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2703         }
2704
2705         acfg->got_offset += acfg->num_trampoline_got_entries;
2706 }
2707
2708 static gboolean
2709 str_begins_with (const char *str1, const char *str2)
2710 {
2711         int len = strlen (str2);
2712         return strncmp (str1, str2, len) == 0;
2713 }
2714
2715 static void
2716 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2717 {
2718         gchar **args, **ptr;
2719
2720         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2721         for (ptr = args; ptr && *ptr; ptr ++) {
2722                 const char *arg = *ptr;
2723
2724                 if (str_begins_with (arg, "outfile=")) {
2725                         opts->outfile = g_strdup (arg + strlen ("outfile="));
2726                 } else if (str_begins_with (arg, "save-temps")) {
2727                         opts->save_temps = TRUE;
2728                 } else if (str_begins_with (arg, "keep-temps")) {
2729                         opts->save_temps = TRUE;
2730                 } else if (str_begins_with (arg, "write-symbols")) {
2731                         opts->write_symbols = TRUE;
2732                 } else if (str_begins_with (arg, "metadata-only")) {
2733                         opts->metadata_only = TRUE;
2734                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2735                         opts->bind_to_runtime_version = TRUE;
2736                 } else if (str_begins_with (arg, "full")) {
2737                         opts->full_aot = TRUE;
2738                 } else if (str_begins_with (arg, "threads=")) {
2739                         opts->nthreads = atoi (arg + strlen ("threads="));
2740                 } else if (str_begins_with (arg, "static")) {
2741                         opts->static_link = TRUE;
2742                         opts->no_dlsym = TRUE;
2743                 } else if (str_begins_with (arg, "asmonly")) {
2744                         opts->asm_only = TRUE;
2745                 } else if (str_begins_with (arg, "asmwriter")) {
2746                         opts->asm_writer = TRUE;
2747                 } else if (str_begins_with (arg, "nodebug")) {
2748                         opts->nodebug = TRUE;
2749                 } else if (str_begins_with (arg, "ntrampolines=")) {
2750                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
2751                 } else {
2752                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2753                         exit (1);
2754                 }
2755         }
2756
2757         g_strfreev (args);
2758 }
2759
2760 static void
2761 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2762 {
2763         MonoMethod *method = (MonoMethod*)key;
2764         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2765         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2766         MonoAotCompile *acfg = user_data;
2767
2768         new_ji->image = ji->image;
2769         new_ji->token = ji->token;
2770         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2771 }
2772
2773 static gboolean
2774 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2775 {
2776         if (klass->type_token)
2777                 return TRUE;
2778         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2779                 return TRUE;
2780         if (klass->rank)
2781                 return can_encode_class (acfg, klass->element_class);
2782         return FALSE;
2783 }
2784
2785 static gboolean
2786 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2787 {
2788         switch (patch_info->type) {
2789         case MONO_PATCH_INFO_METHOD:
2790         case MONO_PATCH_INFO_METHODCONST: {
2791                 MonoMethod *method = patch_info->data.method;
2792
2793                 if (method->wrapper_type) {
2794                         switch (method->wrapper_type) {
2795                         case MONO_WRAPPER_NONE:
2796                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2797                         case MONO_WRAPPER_XDOMAIN_INVOKE:
2798                         case MONO_WRAPPER_STFLD:
2799                         case MONO_WRAPPER_LDFLD:
2800                         case MONO_WRAPPER_LDFLDA:
2801                         case MONO_WRAPPER_LDFLD_REMOTE:
2802                         case MONO_WRAPPER_STFLD_REMOTE:
2803                         case MONO_WRAPPER_STELEMREF:
2804                         case MONO_WRAPPER_ISINST:
2805                         case MONO_WRAPPER_PROXY_ISINST:
2806                         case MONO_WRAPPER_ALLOC:
2807                         case MONO_WRAPPER_REMOTING_INVOKE:
2808                         case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
2809                         case MONO_WRAPPER_UNKNOWN:
2810                                 break;
2811                         default:
2812                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2813                                 return FALSE;
2814                         }
2815                 } else {
2816                         if (!method->token) {
2817                                 /* The method is part of a constructed type like Int[,].Set (). */
2818                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2819                                         if (method->klass->rank)
2820                                                 return TRUE;
2821                                         return FALSE;
2822                                 }
2823                         }
2824                 }
2825                 break;
2826         }
2827         case MONO_PATCH_INFO_VTABLE:
2828         case MONO_PATCH_INFO_CLASS_INIT:
2829         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2830         case MONO_PATCH_INFO_CLASS:
2831         case MONO_PATCH_INFO_IID:
2832         case MONO_PATCH_INFO_ADJUSTED_IID:
2833                 if (!can_encode_class (acfg, patch_info->data.klass)) {
2834                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
2835                         return FALSE;
2836                 }
2837                 break;
2838         case MONO_PATCH_INFO_RGCTX_FETCH: {
2839                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2840
2841                 if (!can_encode_patch (acfg, entry->data))
2842                         return FALSE;
2843                 break;
2844         }
2845         default:
2846                 break;
2847         }
2848
2849         return TRUE;
2850 }
2851
2852 static void
2853 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
2854
2855 /*
2856  * compile_method:
2857  *
2858  *   AOT compile a given method.
2859  * This function might be called by multiple threads, so it must be thread-safe.
2860  */
2861 static void
2862 compile_method (MonoAotCompile *acfg, MonoMethod *method)
2863 {
2864         MonoCompile *cfg;
2865         MonoJumpInfo *patch_info;
2866         gboolean skip;
2867         int index;
2868         MonoMethod *wrapped;
2869
2870         if (acfg->aot_opts.metadata_only)
2871                 return;
2872
2873         mono_acfg_lock (acfg);
2874         index = get_method_index (acfg, method);
2875         mono_acfg_unlock (acfg);
2876
2877         /* fixme: maybe we can also precompile wrapper methods */
2878         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2879                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2880                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
2881                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
2882                 return;
2883         }
2884
2885         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2886                 return;
2887
2888         wrapped = mono_marshal_method_from_wrapper (method);
2889         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
2890                 // FIXME: The wrapper should be generic too, but it is not
2891                 return;
2892
2893         InterlockedIncrement (&acfg->stats.mcount);
2894
2895 #if 0
2896         if (method->is_generic || method->klass->generic_container) {
2897                 InterlockedIncrement (&acfg->stats.genericcount);
2898                 return;
2899         }
2900 #endif
2901
2902         //acfg->aot_opts.print_skipped_methods = TRUE;
2903
2904         if (acfg->aot_opts.full_aot)
2905                 mono_use_imt = FALSE;
2906
2907         /*
2908          * Since these methods are the only ones which are compiled with
2909          * AOT support, and they are not used by runtime startup/shutdown code,
2910          * the runtime will not see AOT methods during AOT compilation,so it
2911          * does not need to support them by creating a fake GOT etc.
2912          */
2913         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
2914         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
2915                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2916                 InterlockedIncrement (&acfg->stats.genericcount);
2917                 return;
2918         }
2919         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
2920                 /* Let the exception happen at runtime */
2921                 return;
2922         }
2923
2924         if (cfg->disable_aot) {
2925                 if (acfg->aot_opts.print_skipped_methods)
2926                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
2927                 InterlockedIncrement (&acfg->stats.ocount);
2928                 mono_destroy_compile (cfg);
2929                 return;
2930         }
2931
2932         /* Nullify patches which need no aot processing */
2933         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2934                 switch (patch_info->type) {
2935                 case MONO_PATCH_INFO_LABEL:
2936                 case MONO_PATCH_INFO_BB:
2937                         patch_info->type = MONO_PATCH_INFO_NONE;
2938                         break;
2939                 default:
2940                         break;
2941                 }
2942         }
2943
2944         /* Collect method->token associations from the cfg */
2945         mono_acfg_lock (acfg);
2946         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
2947         mono_acfg_unlock (acfg);
2948
2949         /*
2950          * Check for absolute addresses.
2951          */
2952         skip = FALSE;
2953         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2954                 switch (patch_info->type) {
2955                 case MONO_PATCH_INFO_ABS:
2956                         /* unable to handle this */
2957                         skip = TRUE;    
2958                         break;
2959                 default:
2960                         break;
2961                 }
2962         }
2963
2964         if (skip) {
2965                 if (acfg->aot_opts.print_skipped_methods)
2966                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
2967                 InterlockedIncrement (&acfg->stats.abscount);
2968                 mono_destroy_compile (cfg);
2969                 return;
2970         }
2971
2972         /* Lock for the rest of the code */
2973         mono_acfg_lock (acfg);
2974
2975         /*
2976          * Check for methods/klasses we can't encode.
2977          */
2978         skip = FALSE;
2979         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2980                 if (!can_encode_patch (acfg, patch_info))
2981                         skip = TRUE;
2982         }
2983
2984         if (skip) {
2985                 if (acfg->aot_opts.print_skipped_methods)
2986                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
2987                 acfg->stats.ocount++;
2988                 mono_destroy_compile (cfg);
2989                 mono_acfg_unlock (acfg);
2990                 return;
2991         }
2992
2993         /* Adds generic instances referenced by this method */
2994         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2995                 switch (patch_info->type) {
2996                 case MONO_PATCH_INFO_METHOD: {
2997                         MonoMethod *m = patch_info->data.method;
2998                         if (m->is_inflated) {
2999                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3000                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
3001                                         !method_has_type_vars (m)) {
3002                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3003                                                 if (acfg->aot_opts.full_aot)
3004                                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3005                                         } else {
3006                                                 add_extra_method (acfg, m);
3007                                         }
3008                                 }
3009                                 add_generic_class (acfg, m->klass);
3010                         }
3011                         break;
3012                 }
3013                 default:
3014                         break;
3015                 }
3016         }
3017
3018         /* Determine whenever the method has GOT slots */
3019         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3020                 switch (patch_info->type) {
3021                 case MONO_PATCH_INFO_GOT_OFFSET:
3022                 case MONO_PATCH_INFO_NONE:
3023                         break;
3024                 case MONO_PATCH_INFO_IMAGE:
3025                         /* The assembly is stored in GOT slot 0 */
3026                         if (patch_info->data.image != acfg->image)
3027                                 cfg->has_got_slots = TRUE;
3028                         break;
3029                 default:
3030                         if (!is_plt_patch (patch_info))
3031                                 cfg->has_got_slots = TRUE;
3032                         break;
3033                 }
3034         }
3035
3036         if (!cfg->has_got_slots)
3037                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3038
3039         /* Make a copy of the patch info which is in the mempool */
3040         {
3041                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3042
3043                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3044                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3045
3046                         if (!patches)
3047                                 patches = new_patch_info;
3048                         else
3049                                 patches_end->next = new_patch_info;
3050                         patches_end = new_patch_info;
3051                 }
3052                 cfg->patch_info = patches;
3053         }
3054         /* Make a copy of the unwind info */
3055         {
3056                 GSList *l, *unwind_ops;
3057                 MonoUnwindOp *op;
3058
3059                 unwind_ops = NULL;
3060                 for (l = cfg->unwind_ops; l; l = l->next) {
3061                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3062                         memcpy (op, l->data, sizeof (MonoUnwindOp));
3063                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3064                 }
3065                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3066         }
3067         /* Make a copy of the argument/local info */
3068         {
3069                 MonoInst **args, **locals;
3070                 MonoMethodSignature *sig;
3071                 MonoMethodHeader *header;
3072                 int i;
3073                 
3074                 sig = mono_method_signature (method);
3075                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3076                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3077                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3078                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3079                 }
3080                 cfg->args = args;
3081
3082                 header = mono_method_get_header (method);
3083                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3084                 for (i = 0; i < header->num_locals; ++i) {
3085                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3086                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3087                 }
3088                 cfg->locals = locals;
3089         }
3090
3091         /* Free some fields used by cfg to conserve memory */
3092         mono_mempool_destroy (cfg->mempool);
3093         cfg->mempool = NULL;
3094         g_free (cfg->varinfo);
3095         cfg->varinfo = NULL;
3096         g_free (cfg->vars);
3097         cfg->vars = NULL;
3098         if (cfg->rs) {
3099                 mono_regstate_free (cfg->rs);
3100                 cfg->rs = NULL;
3101         }
3102
3103         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3104
3105         while (index >= acfg->cfgs_size) {
3106                 MonoCompile **new_cfgs;
3107                 int new_size;
3108
3109                 new_size = acfg->cfgs_size * 2;
3110                 new_cfgs = g_new0 (MonoCompile*, new_size);
3111                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3112                 g_free (acfg->cfgs);
3113                 acfg->cfgs = new_cfgs;
3114                 acfg->cfgs_size = new_size;
3115         }
3116         acfg->cfgs [index] = cfg;
3117
3118         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3119
3120         if (cfg->orig_method->wrapper_type)
3121                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3122
3123         mono_acfg_unlock (acfg);
3124
3125         InterlockedIncrement (&acfg->stats.ccount);
3126 }
3127  
3128 static void
3129 compile_thread_main (gpointer *user_data)
3130 {
3131         MonoDomain *domain = user_data [0];
3132         MonoAotCompile *acfg = user_data [1];
3133         GPtrArray *methods = user_data [2];
3134         int i;
3135
3136         mono_thread_attach (domain);
3137
3138         for (i = 0; i < methods->len; ++i)
3139                 compile_method (acfg, g_ptr_array_index (methods, i));
3140 }
3141
3142 static void
3143 load_profile_files (MonoAotCompile *acfg)
3144 {
3145         FILE *infile;
3146         char *tmp;
3147         int file_index, res, method_index, i;
3148         char ver [256];
3149         guint32 token;
3150         GList *unordered;
3151
3152         file_index = 0;
3153         while (TRUE) {
3154                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
3155
3156                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3157                         g_free (tmp);
3158                         break;
3159                 }
3160
3161                 infile = fopen (tmp, "r");
3162                 g_assert (infile);
3163
3164                 printf ("Using profile data file '%s'\n", tmp);
3165                 g_free (tmp);
3166
3167                 file_index ++;
3168
3169                 res = fscanf (infile, "%32s\n", ver);
3170                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3171                         printf ("Profile file has wrong version or invalid.\n");
3172                         fclose (infile);
3173                         continue;
3174                 }
3175
3176                 while (TRUE) {
3177                         res = fscanf (infile, "%d\n", &token);
3178                         if (res < 1)
3179                                 break;
3180
3181                         method_index = mono_metadata_token_index (token) - 1;
3182
3183                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3184                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3185                 }
3186                 fclose (infile);
3187         }
3188
3189         /* Add missing methods */
3190         unordered = NULL;
3191         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3192                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3193                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3194         }
3195         unordered = g_list_reverse (unordered);
3196         if (acfg->method_order)
3197                 g_list_last (acfg->method_order)->next = unordered;
3198         else
3199                 acfg->method_order = unordered;
3200 }
3201
3202 /**
3203  * alloc_got_slots:
3204  *
3205  *  Collect all patches which have shared GOT entries and alloc entries for them. The
3206  * rest will get entries allocated during emit_code ().
3207  */
3208 static void
3209 alloc_got_slots (MonoAotCompile *acfg)
3210 {
3211         int i;
3212         GList *l;
3213         MonoJumpInfo *ji;
3214
3215         /* Slot 0 is reserved for the address of the current assembly */
3216         ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3217         ji->type = MONO_PATCH_INFO_IMAGE;
3218         ji->data.image = acfg->image;
3219
3220         get_shared_got_offset (acfg, ji);
3221
3222         for (l = acfg->method_order; l != NULL; l = l->next) {
3223                 i = GPOINTER_TO_UINT (l->data);
3224
3225                 if (acfg->cfgs [i]) {
3226                         MonoCompile *cfg = acfg->cfgs [i];
3227
3228                         for (ji = cfg->patch_info; ji; ji = ji->next) {
3229                                 if (is_shared_got_patch (ji))
3230                                         get_shared_got_offset (acfg, ji);
3231                         }
3232                 }
3233         }
3234 }
3235
3236 static void
3237 emit_code (MonoAotCompile *acfg)
3238 {
3239         int i;
3240         char symbol [256];
3241         GList *l;
3242
3243         sprintf (symbol, "methods");
3244         emit_section_change (acfg, ".text", 0);
3245         emit_global (acfg, symbol, TRUE);
3246         emit_alignment (acfg, 8);
3247         emit_label (acfg, symbol);
3248
3249         /* 
3250          * Emit some padding so the local symbol for the first method doesn't have the
3251          * same address as 'methods'.
3252          */
3253         emit_zero_bytes (acfg, 16);
3254
3255         for (l = acfg->method_order; l != NULL; l = l->next) {
3256                 i = GPOINTER_TO_UINT (l->data);
3257
3258                 if (acfg->cfgs [i])
3259                         emit_method_code (acfg, acfg->cfgs [i]);
3260         }
3261
3262         sprintf (symbol, "methods_end");
3263         emit_section_change (acfg, ".text", 0);
3264         emit_global (acfg, symbol, FALSE);
3265         emit_alignment (acfg, 8);
3266         emit_label (acfg, symbol);
3267
3268         sprintf (symbol, "method_offsets");
3269         emit_section_change (acfg, ".text", 1);
3270         emit_global (acfg, symbol, FALSE);
3271         emit_alignment (acfg, 8);
3272         emit_label (acfg, symbol);
3273
3274         for (i = 0; i < acfg->nmethods; ++i) {
3275                 if (acfg->cfgs [i]) {
3276                         sprintf (symbol, ".Lm_%x", i);
3277                         emit_symbol_diff (acfg, symbol, "methods", 0);
3278                 } else {
3279                         emit_int32 (acfg, 0xffffffff);
3280                 }
3281         }
3282         emit_line (acfg);
3283 }
3284
3285 static void
3286 emit_info (MonoAotCompile *acfg)
3287 {
3288         int i;
3289         char symbol [256];
3290         GList *l;
3291
3292         /* Emit method info */
3293         sprintf (symbol, "method_info");
3294         emit_section_change (acfg, ".text", 1);
3295         emit_global (acfg, symbol, FALSE);
3296         emit_alignment (acfg, 8);
3297         emit_label (acfg, symbol);
3298
3299         /* To reduce size of generated assembly code */
3300         sprintf (symbol, "mi");
3301         emit_label (acfg, symbol);
3302
3303         for (l = acfg->method_order; l != NULL; l = l->next) {
3304                 i = GPOINTER_TO_UINT (l->data);
3305
3306                 if (acfg->cfgs [i])
3307                         emit_method_info (acfg, acfg->cfgs [i]);
3308         }
3309
3310         sprintf (symbol, "method_info_offsets");
3311         emit_section_change (acfg, ".text", 1);
3312         emit_global (acfg, symbol, FALSE);
3313         emit_alignment (acfg, 8);
3314         emit_label (acfg, symbol);
3315
3316         for (i = 0; i < acfg->nmethods; ++i) {
3317                 if (acfg->cfgs [i]) {
3318                         sprintf (symbol, ".Lm_%x_p", i);
3319                         emit_symbol_diff (acfg, symbol, "mi", 0);
3320                 } else {
3321                         emit_int32 (acfg, 0);
3322                 }
3323         }
3324         emit_line (acfg);
3325 }
3326
3327 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
3328
3329 /*
3330  * mono_aot_str_hash:
3331  *
3332  * Hash function for strings which we use to hash strings for things which are
3333  * saved in the AOT image, since g_str_hash () can change.
3334  */
3335 guint
3336 mono_aot_str_hash (gconstpointer v1)
3337 {
3338         /* Same as g_str_hash () in glib */
3339         char *p = (char *) v1;
3340         guint hash = *p;
3341
3342         while (*p++) {
3343                 if (*p)
3344                         hash = (hash << 5) - hash + *p;
3345         }
3346
3347         return hash;
3348
3349
3350 /*
3351  * mono_aot_method_hash:
3352  *
3353  *   Return a hash code for methods which only depends on metadata.
3354  */
3355 guint32
3356 mono_aot_method_hash (MonoMethod *method)
3357 {
3358         guint32 hash;
3359
3360         if (method->wrapper_type) {
3361                 hash = mono_aot_str_hash (method->name);
3362         } else {
3363                 char *full_name = mono_method_full_name (method, TRUE);
3364                 // FIXME: Improve this (changing this requires bumping MONO_AOT_FILE_VERSION)
3365                 hash = mono_aot_str_hash (full_name);
3366                 g_free (full_name);
3367         }
3368
3369         return hash;
3370 }
3371
3372 /*
3373  * mono_aot_wrapper_name:
3374  *
3375  *   Return a string which uniqely identifies the given wrapper method.
3376  */
3377 char*
3378 mono_aot_wrapper_name (MonoMethod *method)
3379 {
3380         char *name, *tmpsig, *klass_desc;
3381
3382         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3383
3384         switch (method->wrapper_type) {
3385         case MONO_WRAPPER_RUNTIME_INVOKE:
3386         case MONO_WRAPPER_DELEGATE_INVOKE:
3387         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3388         case MONO_WRAPPER_DELEGATE_END_INVOKE:
3389                 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
3390                 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
3391                 break;
3392         default:
3393                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
3394
3395                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
3396                 break;
3397         }
3398
3399         g_free (tmpsig);
3400
3401         return name;
3402 }
3403
3404 /*
3405  * mono_aot_tramp_info_create:
3406  *
3407  *   Create a MonoAotTrampInfo structure from the arguments.
3408  */
3409 MonoAotTrampInfo*
3410 mono_aot_tramp_info_create (char *name, guint8 *code, guint32 code_size)
3411 {
3412         MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
3413
3414         info->name = name;
3415         info->code = code;
3416         info->code_size = code_size;
3417
3418         return info;
3419 }
3420
3421 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
3422
3423 typedef struct HashEntry {
3424     guint32 key, value, index;
3425         struct HashEntry *next;
3426 } HashEntry;
3427
3428 /*
3429  * emit_extra_methods:
3430  *
3431  * Emit methods which are not in the METHOD table, like wrappers.
3432  */
3433 static void
3434 emit_extra_methods (MonoAotCompile *acfg)
3435 {
3436         int i, table_size, buf_size;
3437         char symbol [256];
3438         guint8 *p, *buf;
3439         guint32 *info_offsets;
3440         guint32 hash;
3441         GPtrArray *table;
3442         HashEntry *entry, *new_entry;
3443         int nmethods, max_chain_length;
3444         int *chain_lengths;
3445
3446         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3447
3448         buf_size = acfg->extra_methods->len * 256 + 256;
3449         p = buf = g_malloc (buf_size);
3450
3451         /* Encode method info */
3452         nmethods = 0;
3453         /* So offsets are > 0 */
3454         *p = 0;
3455         p++;
3456         for (i = 0; i < acfg->extra_methods->len; ++i) {
3457                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3458                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3459                 char *name;
3460
3461                 if (!cfg)
3462                         continue;
3463
3464                 nmethods ++;
3465                 info_offsets [i] = p - buf;
3466
3467                 name = NULL;
3468                 if (method->wrapper_type) {
3469                         /* 
3470                          * We encode some wrappers using their name, since encoding them
3471                          * directly would be difficult. This also avoids creating the wrapper
3472                          * methods at runtime, since they are not needed anyway.
3473                          */
3474                         switch (method->wrapper_type) {
3475                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3476                         case MONO_WRAPPER_SYNCHRONIZED:
3477                                 /* encode_method_ref () can handle these */
3478                                 break;
3479                         default:
3480                                 name = mono_aot_wrapper_name (method);
3481                                 break;
3482                         }
3483                 }
3484
3485                 if (name) {
3486                         encode_value (1, p, &p);
3487                         encode_value (method->wrapper_type, p, &p);
3488                         strcpy ((char*)p, name);
3489                         p += strlen (name ) + 1;
3490                         g_free (name);
3491                 } else {
3492                         encode_value (0, p, &p);
3493                         encode_method_ref (acfg, method, p, &p);
3494                 }
3495
3496                 g_assert ((p - buf) < buf_size);
3497         }
3498
3499         g_assert ((p - buf) < buf_size);
3500
3501         /* Emit method info */
3502         sprintf (symbol, "extra_method_info");
3503         emit_section_change (acfg, ".text", 1);
3504         emit_global (acfg, symbol, FALSE);
3505         emit_alignment (acfg, 8);
3506         emit_label (acfg, symbol);
3507
3508         emit_bytes (acfg, buf, p - buf);
3509
3510         emit_line (acfg);
3511
3512         /*
3513          * Construct a chained hash table for mapping indexes in extra_method_info to
3514          * method indexes.
3515          */
3516         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3517         table = g_ptr_array_sized_new (table_size);
3518         for (i = 0; i < table_size; ++i)
3519                 g_ptr_array_add (table, NULL);
3520         chain_lengths = g_new0 (int, table_size);
3521         max_chain_length = 0;
3522         for (i = 0; i < acfg->extra_methods->len; ++i) {
3523                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3524                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3525                 guint32 key, value;
3526
3527                 if (!cfg)
3528                         continue;
3529
3530                 key = info_offsets [i];
3531                 value = get_method_index (acfg, method);
3532
3533                 hash = mono_aot_method_hash (method) % table_size;
3534
3535                 chain_lengths [hash] ++;
3536                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3537
3538                 /* FIXME: Allocate from the mempool */
3539                 new_entry = g_new0 (HashEntry, 1);
3540                 new_entry->key = key;
3541                 new_entry->value = value;
3542
3543                 entry = g_ptr_array_index (table, hash);
3544                 if (entry == NULL) {
3545                         new_entry->index = hash;
3546                         g_ptr_array_index (table, hash) = new_entry;
3547                 } else {
3548                         while (entry->next)
3549                                 entry = entry->next;
3550                         
3551                         entry->next = new_entry;
3552                         new_entry->index = table->len;
3553                         g_ptr_array_add (table, new_entry);
3554                 }
3555         }
3556
3557         //printf ("MAX: %d\n", max_chain_length);
3558
3559         /* Emit the table */
3560         sprintf (symbol, "extra_method_table");
3561         emit_section_change (acfg, ".text", 0);
3562         emit_global (acfg, symbol, FALSE);
3563         emit_alignment (acfg, 8);
3564         emit_label (acfg, symbol);
3565
3566         g_assert (table_size < 65000);
3567         emit_int32 (acfg, table_size);
3568         g_assert (table->len < 65000);
3569         for (i = 0; i < table->len; ++i) {
3570                 HashEntry *entry = g_ptr_array_index (table, i);
3571
3572                 if (entry == NULL) {
3573                         emit_int32 (acfg, 0);
3574                         emit_int32 (acfg, 0);
3575                         emit_int32 (acfg, 0);
3576                 } else {
3577                         g_assert (entry->key > 0);
3578                         emit_int32 (acfg, entry->key);
3579                         emit_int32 (acfg, entry->value);
3580                         if (entry->next)
3581                                 emit_int32 (acfg, entry->next->index);
3582                         else
3583                                 emit_int32 (acfg, 0);
3584                 }
3585         }
3586
3587         /* 
3588          * Emit a table reverse mapping method indexes to their index in extra_method_info.
3589          * This is used by mono_aot_find_jit_info ().
3590          */
3591         sprintf (symbol, "extra_method_info_offsets");
3592         emit_section_change (acfg, ".text", 0);
3593         emit_global (acfg, symbol, FALSE);
3594         emit_alignment (acfg, 8);
3595         emit_label (acfg, symbol);
3596
3597         emit_int32 (acfg, acfg->extra_methods->len);
3598         for (i = 0; i < acfg->extra_methods->len; ++i) {
3599                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3600
3601                 emit_int32 (acfg, get_method_index (acfg, method));
3602                 emit_int32 (acfg, info_offsets [i]);
3603         }
3604 }       
3605
3606 static void
3607 emit_method_order (MonoAotCompile *acfg)
3608 {
3609         int i, index, len;
3610         char symbol [256];
3611         GList *l;
3612
3613         sprintf (symbol, "method_order");
3614         emit_section_change (acfg, ".text", 1);
3615         emit_global (acfg, symbol, FALSE);
3616         emit_alignment (acfg, 8);
3617         emit_label (acfg, symbol);
3618
3619         /* First emit an index table */
3620         index = 0;
3621         len = 0;
3622         for (l = acfg->method_order; l != NULL; l = l->next) {
3623                 i = GPOINTER_TO_UINT (l->data);
3624
3625                 if (acfg->cfgs [i]) {
3626                         if ((index % 1024) == 0) {
3627                                 emit_int32 (acfg, i);
3628                         }
3629
3630                         index ++;
3631                 }
3632
3633                 len ++;
3634         }
3635         emit_int32 (acfg, 0xffffff);
3636
3637         /* Then emit the whole method order */
3638         for (l = acfg->method_order; l != NULL; l = l->next) {
3639                 i = GPOINTER_TO_UINT (l->data);
3640
3641                 if (acfg->cfgs [i]) {
3642                         emit_int32 (acfg, i);
3643                 }
3644         }       
3645         emit_line (acfg);
3646
3647         sprintf (symbol, "method_order_end");
3648         emit_section_change (acfg, ".text", 1);
3649         emit_global (acfg, symbol, FALSE);
3650         emit_label (acfg, symbol);
3651 }
3652
3653 static void
3654 emit_exception_info (MonoAotCompile *acfg)
3655 {
3656         int i;
3657         char symbol [256];
3658
3659         sprintf (symbol, "ex_info");
3660         emit_section_change (acfg, ".text", 1);
3661         emit_global (acfg, symbol, FALSE);
3662         emit_alignment (acfg, 8);
3663         emit_label (acfg, symbol);
3664
3665         /* To reduce size of generated assembly */
3666         sprintf (symbol, "ex");
3667         emit_label (acfg, symbol);
3668
3669         for (i = 0; i < acfg->nmethods; ++i) {
3670                 if (acfg->cfgs [i])
3671                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
3672         }
3673
3674         sprintf (symbol, "ex_info_offsets");
3675         emit_section_change (acfg, ".text", 1);
3676         emit_global (acfg, symbol, FALSE);
3677         emit_alignment (acfg, 8);
3678         emit_label (acfg, symbol);
3679
3680         for (i = 0; i < acfg->nmethods; ++i) {
3681                 if (acfg->cfgs [i]) {
3682                         sprintf (symbol, ".Le_%x_p", i);
3683                         emit_symbol_diff (acfg, symbol, "ex", 0);
3684                 } else {
3685                         emit_int32 (acfg, 0);
3686                 }
3687         }
3688         emit_line (acfg);
3689 }
3690
3691 static void
3692 emit_unwind_info (MonoAotCompile *acfg)
3693 {
3694         int i;
3695         char symbol [128];
3696
3697         /* 
3698          * The unwind info contains a lot of duplicates so we emit each unique
3699          * entry once, and only store the offset from the start of the table in the
3700          * exception info.
3701          */
3702
3703         sprintf (symbol, "unwind_info");
3704         emit_section_change (acfg, ".text", 1);
3705         emit_alignment (acfg, 8);
3706         emit_label (acfg, symbol);
3707         emit_global (acfg, symbol, FALSE);
3708
3709         for (i = 0; i < acfg->unwind_ops->len; ++i) {
3710                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
3711                 guint8 *unwind_info;
3712                 guint32 unwind_info_len;
3713                 guint8 buf [16];
3714                 guint8 *p;
3715
3716                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
3717
3718                 p = buf;
3719                 encode_value (unwind_info_len, p, &p);
3720                 emit_bytes (acfg, buf, p - buf);
3721                 emit_bytes (acfg, unwind_info, unwind_info_len);
3722
3723                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
3724         }
3725 }
3726
3727 static void
3728 emit_class_info (MonoAotCompile *acfg)
3729 {
3730         int i;
3731         char symbol [256];
3732
3733         sprintf (symbol, "class_info");
3734         emit_section_change (acfg, ".text", 1);
3735         emit_global (acfg, symbol, FALSE);
3736         emit_alignment (acfg, 8);
3737         emit_label (acfg, symbol);
3738
3739         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3740                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3741
3742         sprintf (symbol, "class_info_offsets");
3743         emit_section_change (acfg, ".text", 1);
3744         emit_global (acfg, symbol, FALSE);
3745         emit_alignment (acfg, 8);
3746         emit_label (acfg, symbol);
3747
3748         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3749                 sprintf (symbol, ".LK_I_%x", i);
3750                 emit_symbol_diff (acfg, symbol, "class_info", 0);
3751         }
3752         emit_line (acfg);
3753 }
3754
3755 typedef struct ClassNameTableEntry {
3756         guint32 token, index;
3757         struct ClassNameTableEntry *next;
3758 } ClassNameTableEntry;
3759
3760 static void
3761 emit_class_name_table (MonoAotCompile *acfg)
3762 {
3763         int i, table_size;
3764         guint32 token, hash;
3765         MonoClass *klass;
3766         GPtrArray *table;
3767         char *full_name;
3768         char symbol [256];
3769         ClassNameTableEntry *entry, *new_entry;
3770
3771         /*
3772          * Construct a chained hash table for mapping class names to typedef tokens.
3773          */
3774         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
3775         table = g_ptr_array_sized_new (table_size);
3776         for (i = 0; i < table_size; ++i)
3777                 g_ptr_array_add (table, NULL);
3778         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3779                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3780                 klass = mono_class_get (acfg->image, token);
3781                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
3782                 hash = mono_aot_str_hash (full_name) % table_size;
3783                 g_free (full_name);
3784
3785                 /* FIXME: Allocate from the mempool */
3786                 new_entry = g_new0 (ClassNameTableEntry, 1);
3787                 new_entry->token = token;
3788
3789                 entry = g_ptr_array_index (table, hash);
3790                 if (entry == NULL) {
3791                         new_entry->index = hash;
3792                         g_ptr_array_index (table, hash) = new_entry;
3793                 } else {
3794                         while (entry->next)
3795                                 entry = entry->next;
3796                         
3797                         entry->next = new_entry;
3798                         new_entry->index = table->len;
3799                         g_ptr_array_add (table, new_entry);
3800                 }
3801         }
3802
3803         /* Emit the table */
3804         sprintf (symbol, "class_name_table");
3805         emit_section_change (acfg, ".text", 0);
3806         emit_global (acfg, symbol, FALSE);
3807         emit_alignment (acfg, 8);
3808         emit_label (acfg, symbol);
3809
3810         /* FIXME: Optimize memory usage */
3811         g_assert (table_size < 65000);
3812         emit_int16 (acfg, table_size);
3813         g_assert (table->len < 65000);
3814         for (i = 0; i < table->len; ++i) {
3815                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3816
3817                 if (entry == NULL) {
3818                         emit_int16 (acfg, 0);
3819                         emit_int16 (acfg, 0);
3820                 } else {
3821                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
3822                         if (entry->next)
3823                                 emit_int16 (acfg, entry->next->index);
3824                         else
3825                                 emit_int16 (acfg, 0);
3826                 }
3827         }
3828 }
3829
3830 static void
3831 emit_image_table (MonoAotCompile *acfg)
3832 {
3833         int i;
3834         char symbol [256];
3835
3836         /*
3837          * The image table is small but referenced in a lot of places.
3838          * So we emit it at once, and reference its elements by an index.
3839          */
3840
3841         sprintf (symbol, "mono_image_table");
3842         emit_section_change (acfg, ".text", 1);
3843         emit_global (acfg, symbol, FALSE);
3844         emit_alignment (acfg, 8);
3845         emit_label (acfg, symbol);
3846
3847         emit_int32 (acfg, acfg->image_table->len);
3848         for (i = 0; i < acfg->image_table->len; i++) {
3849                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3850                 MonoAssemblyName *aname = &image->assembly->aname;
3851
3852                 /* FIXME: Support multi-module assemblies */
3853                 g_assert (image->assembly->image == image);
3854
3855                 emit_string (acfg, image->assembly_name);
3856                 emit_string (acfg, image->guid);
3857                 emit_string (acfg, aname->culture ? aname->culture : "");
3858                 emit_string (acfg, (const char*)aname->public_key_token);
3859
3860                 emit_alignment (acfg, 8);
3861                 emit_int32 (acfg, aname->flags);
3862                 emit_int32 (acfg, aname->major);
3863                 emit_int32 (acfg, aname->minor);
3864                 emit_int32 (acfg, aname->build);
3865                 emit_int32 (acfg, aname->revision);
3866         }
3867 }
3868
3869 static void
3870 emit_got_info (MonoAotCompile *acfg)
3871 {
3872         char symbol [256];
3873         int i, first_plt_got_patch, buf_size;
3874         guint8 *p, *buf;
3875         guint32 *got_info_offsets;
3876
3877         /* Add the patches needed by the PLT to the GOT */
3878         acfg->plt_got_offset_base = acfg->got_offset;
3879         first_plt_got_patch = acfg->shared_patches->len;
3880         for (i = 1; i < acfg->plt_offset; ++i) {
3881                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3882
3883                 g_ptr_array_add (acfg->shared_patches, patch_info);
3884         }
3885
3886         acfg->got_offset += acfg->plt_offset;
3887
3888         /**
3889          * FIXME: 
3890          * - optimize offsets table.
3891          * - reduce number of exported symbols.
3892          * - emit info for a klass only once.
3893          * - determine when a method uses a GOT slot which is guaranteed to be already 
3894          *   initialized.
3895          * - clean up and document the code.
3896          * - use String.Empty in class libs.
3897          */
3898
3899         /* Encode info required to decode shared GOT entries */
3900         buf_size = acfg->shared_patches->len * 64;
3901         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3902         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3903         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
3904         for (i = 0; i < acfg->shared_patches->len; ++i) {
3905                 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3906
3907                 got_info_offsets [i] = p - buf;
3908                 /* No need to encode the patch type for non-PLT patches */
3909                 if (i >= first_plt_got_patch) {
3910                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
3911                         encode_value (ji->type, p, &p);
3912                 }
3913                 encode_patch (acfg, ji, p, &p);
3914         }
3915
3916         g_assert (p - buf <= buf_size);
3917
3918         acfg->stats.got_info_size = p - buf;
3919
3920         /* Emit got_info table */
3921         sprintf (symbol, "got_info");
3922         emit_section_change (acfg, ".text", 1);
3923         emit_global (acfg, symbol, FALSE);
3924         emit_alignment (acfg, 8);
3925         emit_label (acfg, symbol);
3926
3927         emit_bytes (acfg, buf, p - buf);
3928
3929         /* Emit got_info_offsets table */
3930         sprintf (symbol, "got_info_offsets");
3931         emit_section_change (acfg, ".text", 1);
3932         emit_global (acfg, symbol, FALSE);
3933         emit_alignment (acfg, 8);
3934         emit_label (acfg, symbol);
3935
3936         for (i = 0; i < acfg->shared_patches->len; ++i)
3937                 emit_int32 (acfg, got_info_offsets [i]);
3938
3939         acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3940 }
3941
3942 static void
3943 emit_got (MonoAotCompile *acfg)
3944 {
3945         char symbol [256];
3946
3947         /* Don't make GOT global so accesses to it don't need relocations */
3948         sprintf (symbol, "got");
3949         emit_section_change (acfg, ".bss", 0);
3950         emit_alignment (acfg, 8);
3951         emit_label (acfg, symbol);
3952         if (acfg->got_offset > 0)
3953                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3954 }
3955
3956 static void
3957 emit_globals (MonoAotCompile *acfg)
3958 {
3959         char *opts_str;
3960         char *build_info;
3961
3962         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3963
3964         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3965
3966         opts_str = g_strdup_printf ("%d", acfg->opts);
3967         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3968         g_free (opts_str);
3969
3970         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
3971
3972         if (acfg->aot_opts.bind_to_runtime_version) {
3973                 build_info = mono_get_runtime_build_info ();
3974                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
3975                 g_free (build_info);
3976         } else {
3977                 emit_string_symbol (acfg, "mono_runtime_version", "");
3978         }
3979
3980         /* 
3981          * When static linking, we emit a global which will point to the symbol table.
3982          */
3983         if (acfg->aot_opts.static_link) {
3984                 int i;
3985                 char symbol [256];
3986                 char *p;
3987
3988                 /* Emit a string holding the assembly name */
3989                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
3990
3991                 /* Emit the names */
3992                 for (i = 0; i < acfg->globals->len; ++i) {
3993                         char *name = g_ptr_array_index (acfg->globals, i);
3994
3995                         sprintf (symbol, "name_%d", i);
3996                         emit_section_change (acfg, ".text", 1);
3997                         emit_label (acfg, symbol);
3998                         emit_string (acfg, name);
3999                 }
4000
4001                 /* Emit the globals table */
4002                 sprintf (symbol, "globals");
4003                 emit_section_change (acfg, ".data", 0);
4004                 /* This is not a global, since it is accessed by the init function */
4005                 emit_alignment (acfg, 8);
4006                 emit_label (acfg, symbol);
4007
4008                 for (i = 0; i < acfg->globals->len; ++i) {
4009                         char *name = g_ptr_array_index (acfg->globals, i);
4010
4011                         sprintf (symbol, "name_%d", i);
4012                         emit_pointer (acfg, symbol);
4013
4014                         sprintf (symbol, "%s", name);
4015                         emit_pointer (acfg, symbol);
4016                 }
4017                 /* Null terminate the table */
4018                 emit_int32 (acfg, 0);
4019                 emit_int32 (acfg, 0);
4020
4021                 /* 
4022                  * Emit a global symbol which can be passed by an embedding app to
4023                  * mono_aot_register_module ().
4024                  */
4025 #if defined(__MACH__)
4026                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4027 #else
4028                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4029 #endif
4030
4031                 /* Get rid of characters which cannot occur in symbols */
4032                 p = symbol;
4033                 for (p = symbol; *p; ++p) {
4034                         if (!(isalnum (*p) || *p == '_'))
4035                                 *p = '_';
4036                 }
4037                 acfg->static_linking_symbol = g_strdup (symbol);
4038                 emit_global_inner (acfg, symbol, FALSE);
4039                 emit_alignment (acfg, 8);
4040                 emit_label (acfg, symbol);
4041                 emit_pointer (acfg, "globals");
4042         }
4043 }
4044
4045 static void
4046 emit_mem_end (MonoAotCompile *acfg)
4047 {
4048         char symbol [128];
4049
4050         sprintf (symbol, "mem_end");
4051         emit_section_change (acfg, ".text", 1);
4052         emit_global (acfg, symbol, FALSE);
4053         emit_alignment (acfg, 8);
4054         emit_label (acfg, symbol);
4055 }
4056
4057 /*
4058  * Emit a structure containing all the information not stored elsewhere.
4059  */
4060 static void
4061 emit_file_info (MonoAotCompile *acfg)
4062 {
4063         char symbol [128];
4064
4065         sprintf (symbol, "mono_aot_file_info");
4066         emit_section_change (acfg, ".data", 0);
4067         emit_alignment (acfg, 8);
4068         emit_label (acfg, symbol);
4069         emit_global (acfg, symbol, FALSE);
4070
4071         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4072         emit_int32 (acfg, acfg->plt_got_offset_base);
4073         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4074         emit_int32 (acfg, acfg->plt_offset);
4075         emit_int32 (acfg, acfg->num_specific_trampolines);
4076         emit_int32 (acfg, acfg->specific_trampoline_size);
4077         emit_int32 (acfg, acfg->specific_trampoline_got_offset_base);
4078         emit_int32 (acfg, acfg->num_static_rgctx_trampolines);
4079         emit_int32 (acfg, acfg->static_rgctx_trampoline_size);
4080         emit_int32 (acfg, acfg->static_rgctx_trampoline_got_offset_base);
4081         emit_pointer (acfg, "got");
4082 }
4083
4084 static void
4085 emit_dwarf_info (MonoAotCompile *acfg)
4086 {
4087 #ifdef EMIT_DWARF_INFO
4088         int i;
4089         char symbol [128], symbol2 [128];
4090
4091         /* DIEs for methods */
4092         for (i = 0; i < acfg->nmethods; ++i) {
4093                 MonoCompile *cfg = acfg->cfgs [i];
4094
4095                 if (!cfg)
4096                         continue;
4097
4098                 sprintf (symbol, ".Lm_%x", i);
4099                 sprintf (symbol2, ".Lme_%x", i);
4100
4101                 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
4102         }
4103 #endif
4104 }
4105
4106 static void
4107 collect_methods (MonoAotCompile *acfg)
4108 {
4109         int i;
4110         MonoImage *image = acfg->image;
4111
4112         /* Collect methods */
4113         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4114                 MonoMethod *method;
4115                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4116
4117                 method = mono_get_method (acfg->image, token, NULL);
4118
4119                 if (!method) {
4120                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4121                         exit (1);
4122                 }
4123                         
4124                 /* Load all methods eagerly to skip the slower lazy loading code */
4125                 mono_class_setup_methods (method->klass);
4126
4127                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4128                         /* Compile the wrapper instead */
4129                         /* We do this here instead of add_wrappers () because it is easy to do it here */
4130                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4131                         method = wrapper;
4132                 }
4133
4134                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4135                 add_method_with_index (acfg, method, i);
4136                 acfg->method_index ++;
4137         }
4138
4139         add_generic_instances (acfg);
4140
4141         if (acfg->aot_opts.full_aot)
4142                 add_wrappers (acfg);
4143 }
4144
4145 static void
4146 compile_methods (MonoAotCompile *acfg)
4147 {
4148         int i, methods_len;
4149
4150         if (acfg->aot_opts.nthreads > 0) {
4151                 GPtrArray *frag;
4152                 int len, j;
4153                 GPtrArray *threads;
4154                 HANDLE handle;
4155                 gpointer *user_data;
4156                 MonoMethod **methods;
4157
4158                 methods_len = acfg->methods->len;
4159
4160                 len = acfg->methods->len / acfg->aot_opts.nthreads;
4161                 g_assert (len > 0);
4162                 /* 
4163                  * Partition the list of methods into fragments, and hand it to threads to
4164                  * process.
4165                  */
4166                 threads = g_ptr_array_new ();
4167                 /* Make a copy since acfg->methods is modified by compile_method () */
4168                 methods = g_new0 (MonoMethod*, methods_len);
4169                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4170                 for (i = 0; i < methods_len; ++i)
4171                         methods [i] = g_ptr_array_index (acfg->methods, i);
4172                 i = 0;
4173                 while (i < methods_len) {
4174                         frag = g_ptr_array_new ();
4175                         for (j = 0; j < len; ++j) {
4176                                 if (i < methods_len) {
4177                                         g_ptr_array_add (frag, methods [i]);
4178                                         i ++;
4179                                 }
4180                         }
4181
4182                         user_data = g_new0 (gpointer, 3);
4183                         user_data [0] = mono_domain_get ();
4184                         user_data [1] = acfg;
4185                         user_data [2] = frag;
4186                         
4187                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4188                         g_ptr_array_add (threads, handle);
4189                 }
4190                 g_free (methods);
4191
4192                 for (i = 0; i < threads->len; ++i) {
4193                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4194                 }
4195         } else {
4196                 methods_len = 0;
4197         }
4198
4199         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4200         for (i = methods_len; i < acfg->methods->len; ++i) {
4201                 /* This can new methods to acfg->methods */
4202                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4203         }
4204 }
4205
4206 static int
4207 compile_asm (MonoAotCompile *acfg)
4208 {
4209         char *command, *objfile;
4210         char *outfile_name, *tmp_outfile_name;
4211
4212 #if defined(TARGET_AMD64)
4213 #define AS_OPTIONS "--64"
4214 #elif defined(sparc) && SIZEOF_VOID_P == 8
4215 #define AS_OPTIONS "-xarch=v9"
4216 #else
4217 #define AS_OPTIONS ""
4218 #endif
4219
4220         if (acfg->aot_opts.asm_only) {
4221                 printf ("Output file: '%s'.\n", acfg->tmpfname);
4222                 if (acfg->aot_opts.static_link)
4223                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4224                 return 0;
4225         }
4226
4227         if (acfg->aot_opts.static_link) {
4228                 if (acfg->aot_opts.outfile)
4229                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4230                 else
4231                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
4232         } else {
4233                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
4234         }
4235         command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
4236         printf ("Executing the native assembler: %s\n", command);
4237         if (system (command) != 0) {
4238                 g_free (command);
4239                 g_free (objfile);
4240                 return 1;
4241         }
4242
4243         g_free (command);
4244
4245         if (acfg->aot_opts.static_link) {
4246                 printf ("Output file: '%s'.\n", objfile);
4247                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4248                 g_free (objfile);
4249                 return 0;
4250         }
4251
4252         if (acfg->aot_opts.outfile)
4253                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4254         else
4255                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4256
4257         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4258
4259 #if defined(sparc)
4260         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4261 #elif defined(__ppc__) && defined(__MACH__)
4262         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4263 #elif defined(PLATFORM_WIN32)
4264         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4265 #else
4266         command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4267 #endif
4268         printf ("Executing the native linker: %s\n", command);
4269         if (system (command) != 0) {
4270                 g_free (tmp_outfile_name);
4271                 g_free (outfile_name);
4272                 g_free (command);
4273                 g_free (objfile);
4274                 return 1;
4275         }
4276
4277         g_free (command);
4278         unlink (objfile);
4279         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
4280         printf ("Stripping the binary: %s\n", com);
4281         system (com);
4282         g_free (com);*/
4283
4284 #if defined(TARGET_ARM) && !defined(__MACH__)
4285         /* 
4286          * gas generates 'mapping symbols' each time code and data is mixed, which 
4287          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
4288          */
4289         command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
4290         printf ("Stripping the binary: %s\n", command);
4291         if (system (command) != 0) {
4292                 g_free (tmp_outfile_name);
4293                 g_free (outfile_name);
4294                 g_free (command);
4295                 g_free (objfile);
4296                 return 1;
4297         }
4298 #endif
4299
4300         rename (tmp_outfile_name, outfile_name);
4301
4302         g_free (tmp_outfile_name);
4303         g_free (outfile_name);
4304         g_free (objfile);
4305
4306         if (acfg->aot_opts.save_temps)
4307                 printf ("Retained input file.\n");
4308         else
4309                 unlink (acfg->tmpfname);
4310
4311         return 0;
4312 }
4313
4314 static MonoAotCompile*
4315 acfg_create (MonoAssembly *ass, guint32 opts)
4316 {
4317         MonoImage *image = ass->image;
4318         MonoAotCompile *acfg;
4319
4320         acfg = g_new0 (MonoAotCompile, 1);
4321         acfg->methods = g_ptr_array_new ();
4322         acfg->method_indexes = g_hash_table_new (NULL, NULL);
4323         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4324         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4325         acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4326         acfg->shared_patches = g_ptr_array_new ();
4327         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4328         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4329         acfg->image_hash = g_hash_table_new (NULL, NULL);
4330         acfg->image_table = g_ptr_array_new ();
4331         acfg->globals = g_ptr_array_new ();
4332         acfg->image = image;
4333         acfg->opts = opts;
4334         acfg->mempool = mono_mempool_new ();
4335         acfg->extra_methods = g_ptr_array_new ();
4336         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
4337         acfg->unwind_ops = g_ptr_array_new ();
4338         InitializeCriticalSection (&acfg->mutex);
4339
4340         return acfg;
4341 }
4342
4343 static void
4344 acfg_free (MonoAotCompile *acfg)
4345 {
4346         int i;
4347
4348         img_writer_destroy (acfg->w);
4349         for (i = 0; i < acfg->nmethods; ++i)
4350                 if (acfg->cfgs [i])
4351                         g_free (acfg->cfgs [i]);
4352         g_free (acfg->cfgs);
4353         g_free (acfg->static_linking_symbol);
4354         g_ptr_array_free (acfg->methods, TRUE);
4355         g_ptr_array_free (acfg->shared_patches, TRUE);
4356         g_ptr_array_free (acfg->image_table, TRUE);
4357         g_ptr_array_free (acfg->globals, TRUE);
4358         g_ptr_array_free (acfg->unwind_ops, TRUE);
4359         g_hash_table_destroy (acfg->method_indexes);
4360         g_hash_table_destroy (acfg->plt_offset_to_patch);
4361         g_hash_table_destroy (acfg->patch_to_plt_offset);
4362         g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4363         g_hash_table_destroy (acfg->method_to_cfg);
4364         g_hash_table_destroy (acfg->token_info_hash);
4365         g_hash_table_destroy (acfg->image_hash);
4366         g_hash_table_destroy (acfg->unwind_info_offsets);
4367         mono_mempool_destroy (acfg->mempool);
4368         g_free (acfg);
4369 }
4370
4371 int
4372 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4373 {
4374         MonoImage *image = ass->image;
4375         int res;
4376         MonoAotCompile *acfg;
4377         char *outfile_name, *tmp_outfile_name;
4378         TV_DECLARE (atv);
4379         TV_DECLARE (btv);
4380
4381         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4382
4383         acfg = acfg_create (ass, opts);
4384
4385         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4386         acfg->aot_opts.write_symbols = TRUE;
4387         acfg->aot_opts.ntrampolines = 10240;
4388
4389         mono_aot_parse_options (aot_options, &acfg->aot_opts);
4390
4391         //acfg->aot_opts.print_skipped_methods = TRUE;
4392
4393 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4394         if (acfg->aot_opts.full_aot) {
4395                 printf ("--aot=full is not supported on this platform.\n");
4396                 return 1;
4397         }
4398 #endif
4399
4400         if (acfg->aot_opts.static_link)
4401                 acfg->aot_opts.asm_writer = TRUE;
4402
4403         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4404                 if (acfg->aot_opts.outfile)
4405                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4406                 else
4407                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4408
4409                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4410
4411                 acfg->fp = fopen (tmp_outfile_name, "w");
4412                 g_assert (acfg->fp);
4413
4414                 acfg->w = img_writer_create (acfg->fp, TRUE);
4415                 acfg->use_bin_writer = TRUE;
4416         } else {
4417                 if (acfg->aot_opts.asm_only) {
4418                         if (acfg->aot_opts.outfile)
4419                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4420                         else
4421                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4422                         acfg->fp = fopen (acfg->tmpfname, "w+");
4423                 } else {
4424                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4425                         acfg->fp = fdopen (i, "w+");
4426                 }
4427                 g_assert (acfg->fp);
4428
4429                 acfg->w = img_writer_create (acfg->fp, FALSE);
4430                 
4431                 tmp_outfile_name = NULL;
4432                 outfile_name = NULL;
4433         }
4434
4435         load_profile_files (acfg);
4436
4437         if (!acfg->aot_opts.nodebug)
4438                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4439
4440         acfg->num_specific_trampolines = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
4441 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
4442         acfg->num_static_rgctx_trampolines = acfg->aot_opts.full_aot ? 1024 : 0;
4443 #endif
4444
4445         acfg->method_index = 1;
4446
4447         collect_methods (acfg);
4448
4449         acfg->cfgs_size = acfg->methods->len + 32;
4450         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4451
4452         /* PLT offset 0 is reserved for the PLT trampoline */
4453         acfg->plt_offset = 1;
4454
4455         TV_GETTIME (atv);
4456
4457         compile_methods (acfg);
4458
4459         TV_GETTIME (btv);
4460
4461         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4462
4463         TV_GETTIME (atv);
4464
4465         alloc_got_slots (acfg);
4466
4467         img_writer_emit_start (acfg->w);
4468
4469         if (acfg->dwarf)
4470                 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4471
4472         emit_code (acfg);
4473
4474         emit_info (acfg);
4475
4476         emit_extra_methods (acfg);
4477
4478         emit_method_order (acfg);
4479
4480         emit_trampolines (acfg);
4481
4482         emit_class_name_table (acfg);
4483
4484         emit_got_info (acfg);
4485
4486         emit_exception_info (acfg);
4487
4488         emit_unwind_info (acfg);
4489
4490         emit_class_info (acfg);
4491
4492         emit_plt (acfg);
4493
4494         emit_image_table (acfg);
4495
4496         emit_got (acfg);
4497
4498         emit_file_info (acfg);
4499
4500         emit_globals (acfg);
4501
4502         if (acfg->dwarf)
4503                 emit_dwarf_info (acfg);
4504
4505         emit_mem_end (acfg);
4506
4507         TV_GETTIME (btv);
4508
4509         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4510
4511         printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %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, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
4512
4513         TV_GETTIME (atv);
4514         res = img_writer_emit_writeout (acfg->w);
4515         if (res != 0) {
4516                 acfg_free (acfg);
4517                 return res;
4518         }
4519         if (acfg->use_bin_writer) {
4520                 rename (tmp_outfile_name, outfile_name);
4521         } else {
4522                 res = compile_asm (acfg);
4523                 if (res != 0) {
4524                         acfg_free (acfg);
4525                         return res;
4526                 }
4527         }
4528         TV_GETTIME (btv);
4529         acfg->stats.link_time = TV_ELAPSED (atv, btv);
4530
4531         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);
4532         if (acfg->stats.genericcount)
4533                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4534         if (acfg->stats.abscount)
4535                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4536         if (acfg->stats.lmfcount)
4537                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4538         if (acfg->stats.ocount)
4539                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4540         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);
4541         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4542
4543         /*
4544         printf ("GOT slot distribution:\n");
4545         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4546                 if (acfg->stats.got_slot_types [i])
4547                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4548         */
4549
4550         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);
4551
4552         acfg_free (acfg);
4553         
4554         return 0;
4555 }
4556  
4557 /*
4558  * Support for emitting debug info for JITted code.
4559  *
4560  *   This works as follows:
4561  * - the runtime writes out an xdb.s file containing DWARF debug info.
4562  * - the user calls a gdb macro
4563  * - the macro compiles and loads this shared library using add-symbol-file.
4564  *
4565  * This is based on the xdebug functionality in the Kaffe Java VM.
4566  * 
4567  * We emit assembly code instead of using the ELF writer, so we can emit debug info
4568  * incrementally as each method is JITted, and the debugger doesn't have to call
4569  * into the runtime to emit the shared library, which would cause all kinds of
4570  * complications, like threading issues, and the fact that the ELF writer's
4571  * emit_writeout () function cannot be called more than once.
4572  */
4573
4574 /* The recommended gdb macro is: */
4575 /*
4576   define xdb
4577   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4578   add-symbol-file xdb.so 0
4579   end
4580 */
4581
4582 static MonoDwarfWriter *xdebug_writer;
4583 static FILE *xdebug_fp;
4584
4585 void
4586 mono_xdebug_init (void)
4587 {
4588         FILE *il_file;
4589         MonoImageWriter *w;
4590
4591         unlink ("xdb.s");
4592         xdebug_fp = fopen ("xdb.s", "w");
4593
4594         w = img_writer_create (xdebug_fp, FALSE);
4595
4596         img_writer_emit_start (w);
4597
4598         /* This file will contain the IL code for methods which don't have debug info */
4599         il_file = fopen ("xdb.il", "w");
4600
4601         xdebug_writer = mono_dwarf_writer_create (w, il_file);
4602
4603         /* Emit something so the file has a text segment */
4604         img_writer_emit_section_change (w, ".text", 0);
4605         img_writer_emit_string (w, "");
4606
4607         mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4608 }
4609
4610 /*
4611  * mono_save_xdebug_info:
4612  *
4613  *   Emit debugging info for METHOD into an assembly file which can be assembled
4614  * and loaded into gdb to provide debugging info for JITted code.
4615  * LOCKING: Acquires the loader lock.
4616  */
4617 void
4618 mono_save_xdebug_info (MonoCompile *cfg)
4619 {
4620         if (!xdebug_writer)
4621                 return;
4622
4623         mono_loader_lock ();
4624         mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, 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 ()));
4625         fflush (xdebug_fp);
4626         mono_loader_unlock ();
4627 }
4628
4629 /*
4630  * mono_save_trampoline_xdebug_info:
4631  *
4632  *   Same as mono_save_xdebug_info, but for trampolines.
4633  * LOCKING: Acquires the loader lock.
4634  */
4635 void
4636 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4637 {
4638         if (!xdebug_writer)
4639                 return;
4640
4641         mono_loader_lock ();
4642         mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4643         fflush (xdebug_fp);
4644         mono_loader_unlock ();
4645 }
4646
4647 #else
4648
4649 /* AOT disabled */
4650
4651 int
4652 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4653 {
4654         return 0;
4655 }
4656
4657 void
4658 mono_xdebug_init (void)
4659 {
4660 }
4661
4662 void
4663 mono_save_xdebug_info (MonoCompile *cfg)
4664 {
4665 }
4666
4667 void
4668 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4669 {
4670 }
4671
4672 #endif