Merge pull request #1909 from esdrubal/reflection
[mono.git] / mono / mini / mini-llvm.c
1 /*
2  * mini-llvm.c: llvm "Backend" for the mono JIT
3  *
4  * Copyright 2009-2011 Novell Inc (http://www.novell.com)
5  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
6  */
7
8 #include "mini.h"
9 #include <mono/metadata/debug-helpers.h>
10 #include <mono/metadata/debug-mono-symfile.h>
11 #include <mono/metadata/mempool-internals.h>
12 #include <mono/utils/mono-tls.h>
13 #include <mono/utils/mono-dl.h>
14 #include <mono/utils/mono-time.h>
15 #include <mono/utils/freebsd-dwarf.h>
16
17 #ifndef __STDC_LIMIT_MACROS
18 #define __STDC_LIMIT_MACROS
19 #endif
20 #ifndef __STDC_CONSTANT_MACROS
21 #define __STDC_CONSTANT_MACROS
22 #endif
23
24 #include "llvm-c/Core.h"
25 #include "llvm-c/ExecutionEngine.h"
26 #include "llvm-c/BitWriter.h"
27 #include "llvm-c/Analysis.h"
28
29 #include "mini-llvm-cpp.h"
30
31 #ifdef __MINGW32__
32
33 #include <stddef.h>
34 extern void *memset(void *, int, size_t);
35 void bzero (void *to, size_t count) { memset (to, 0, count); }
36
37 #endif
38
39 #if LLVM_API_VERSION < 4
40 #error "The version of the mono llvm repository is too old."
41 #endif
42
43  /*
44   * Information associated by mono with LLVM modules.
45   */
46 typedef struct {
47         LLVMModuleRef module;
48         LLVMValueRef throw, rethrow, throw_corlib_exception;
49         GHashTable *llvm_types;
50         LLVMValueRef got_var;
51         const char *got_symbol;
52         GHashTable *plt_entries;
53         GHashTable *plt_entries_ji;
54         GHashTable *method_to_lmethod;
55         char **bb_names;
56         int bb_names_len;
57         GPtrArray *used;
58         LLVMTypeRef ptr_type;
59         GPtrArray *subprogram_mds;
60         MonoEERef *mono_ee;
61         LLVMExecutionEngineRef ee;
62         gboolean external_symbols;
63         gboolean emit_dwarf;
64         int max_got_offset;
65
66         /* For AOT */
67         MonoAssembly *assembly;
68         char *global_prefix;
69         MonoAotFileInfo aot_info;
70         const char *jit_got_symbol;
71         const char *eh_frame_symbol;
72         LLVMValueRef code_start, code_end;
73         gboolean has_jitted_code;
74         gboolean static_link;
75 } MonoLLVMModule;
76
77 /*
78  * Information associated by the backend with mono basic blocks.
79  */
80 typedef struct {
81         LLVMBasicBlockRef bblock, end_bblock;
82         LLVMValueRef finally_ind;
83         gboolean added, invoke_target;
84         /* 
85          * If this bblock is the start of a finally clause, this is a list of bblocks it
86          * needs to branch to in ENDFINALLY.
87          */
88         GSList *call_handler_return_bbs;
89         /*
90          * If this bblock is the start of a finally clause, this is the bblock that
91          * CALL_HANDLER needs to branch to.
92          */
93         LLVMBasicBlockRef call_handler_target_bb;
94         /* The list of switch statements generated by ENDFINALLY instructions */
95         GSList *endfinally_switch_ins_list;
96         GSList *phi_nodes;
97 } BBInfo;
98
99 /*
100  * Structure containing emit state
101  */
102 typedef struct {
103         MonoMemPool *mempool;
104
105         /* Maps method names to the corresponding LLVMValueRef */
106         GHashTable *emitted_method_decls;
107
108         MonoCompile *cfg;
109         LLVMValueRef lmethod;
110         MonoLLVMModule *lmodule;
111         LLVMModuleRef module;
112         BBInfo *bblocks;
113         int sindex, default_index, ex_index;
114         LLVMBuilderRef builder;
115         LLVMValueRef *values, *addresses;
116         MonoType **vreg_cli_types;
117         LLVMCallInfo *linfo;
118         MonoMethodSignature *sig;
119         GSList *builders;
120         GHashTable *region_to_handler;
121         GHashTable *clause_to_handler;
122         LLVMBuilderRef alloca_builder;
123         LLVMValueRef last_alloca;
124         LLVMValueRef rgctx_arg;
125         LLVMTypeRef *vreg_types;
126         gboolean *is_dead;
127         gboolean *unreachable;
128         int *pindexes;
129         LLVMValueRef imt_rgctx_loc;
130         GHashTable *llvm_types;
131         LLVMValueRef dbg_md;
132         MonoDebugMethodInfo *minfo;
133         char temp_name [32];
134         /* For every clause, the clauses it is nested in */
135         GSList **nested_in;
136         LLVMValueRef ex_var;
137 } EmitContext;
138
139 typedef struct {
140         MonoBasicBlock *bb;
141         MonoInst *phi;
142         MonoBasicBlock *in_bb;
143         int sreg;
144 } PhiNode;
145
146 /*
147  * Instruction metadata
148  * This is the same as ins_info, but LREG != IREG.
149  */
150 #ifdef MINI_OP
151 #undef MINI_OP
152 #endif
153 #ifdef MINI_OP3
154 #undef MINI_OP3
155 #endif
156 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
157 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
158 #define NONE ' '
159 #define IREG 'i'
160 #define FREG 'f'
161 #define VREG 'v'
162 #define XREG 'x'
163 #define LREG 'l'
164 /* keep in sync with the enum in mini.h */
165 const char
166 llvm_ins_info[] = {
167 #include "mini-ops.h"
168 };
169 #undef MINI_OP
170 #undef MINI_OP3
171
172 #if SIZEOF_VOID_P == 4
173 #define GET_LONG_IMM(ins) (((guint64)(ins)->inst_ms_word << 32) | (guint64)(guint32)(ins)->inst_ls_word)
174 #else
175 #define GET_LONG_IMM(ins) ((ins)->inst_imm)
176 #endif
177
178 #define LLVM_INS_INFO(opcode) (&llvm_ins_info [((opcode) - OP_START - 1) * 4])
179
180 #if 0
181 #define TRACE_FAILURE(msg) do { printf ("%s\n", msg); } while (0)
182 #else
183 #define TRACE_FAILURE(msg)
184 #endif
185
186 #ifdef TARGET_X86
187 #define IS_TARGET_X86 1
188 #else
189 #define IS_TARGET_X86 0
190 #endif
191
192 #ifdef TARGET_AMD64
193 #define IS_TARGET_AMD64 1
194 #else
195 #define IS_TARGET_AMD64 0
196 #endif
197
198 #define LLVM_FAILURE(ctx, reason) do { \
199         TRACE_FAILURE (reason); \
200         (ctx)->cfg->exception_message = g_strdup (reason); \
201         (ctx)->cfg->disable_llvm = TRUE; \
202         goto FAILURE; \
203 } while (0)
204
205 #define CHECK_FAILURE(ctx) do { \
206     if ((ctx)->cfg->disable_llvm) \
207                 goto FAILURE; \
208 } while (0)
209
210 static LLVMIntPredicate cond_to_llvm_cond [] = {
211         LLVMIntEQ,
212         LLVMIntNE,
213         LLVMIntSLE,
214         LLVMIntSGE,
215         LLVMIntSLT,
216         LLVMIntSGT,
217         LLVMIntULE,
218         LLVMIntUGE,
219         LLVMIntULT,
220         LLVMIntUGT,
221 };
222
223 static LLVMRealPredicate fpcond_to_llvm_cond [] = {
224         LLVMRealOEQ,
225         LLVMRealUNE,
226         LLVMRealOLE,
227         LLVMRealOGE,
228         LLVMRealOLT,
229         LLVMRealOGT,
230         LLVMRealULE,
231         LLVMRealUGE,
232         LLVMRealULT,
233         LLVMRealUGT,
234 };
235
236 static MonoNativeTlsKey current_cfg_tls_id;
237
238 static MonoLLVMModule aot_module;
239 static int memset_param_count, memcpy_param_count;
240 static const char *memset_func_name;
241 static const char *memcpy_func_name;
242
243 static void init_jit_module (MonoDomain *domain);
244
245 static void emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code);
246 static LLVMValueRef emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name);
247 static void emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name);
248
249 /*
250  * IntPtrType:
251  *
252  *   The LLVM type with width == sizeof (gpointer)
253  */
254 static LLVMTypeRef
255 IntPtrType (void)
256 {
257         return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
258 }
259
260 static LLVMTypeRef
261 ObjRefType (void)
262 {
263         return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
264 }
265
266 static LLVMTypeRef
267 ThisType (void)
268 {
269         return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
270 }
271
272 /*
273  * get_vtype_size:
274  *
275  *   Return the size of the LLVM representation of the vtype T.
276  */
277 static guint32
278 get_vtype_size (MonoType *t)
279 {
280         int size;
281
282         size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
283
284         /* LLVMArgAsIArgs depends on this since it stores whole words */
285         while (size < 2 * sizeof (gpointer) && mono_is_power_of_two (size) == -1)
286                 size ++;
287
288         return size;
289 }
290
291 /*
292  * simd_class_to_llvm_type:
293  *
294  *   Return the LLVM type corresponding to the Mono.SIMD class KLASS
295  */
296 static LLVMTypeRef
297 simd_class_to_llvm_type (EmitContext *ctx, MonoClass *klass)
298 {
299         if (!strcmp (klass->name, "Vector2d")) {
300                 return LLVMVectorType (LLVMDoubleType (), 2);
301         } else if (!strcmp (klass->name, "Vector2l")) {
302                 return LLVMVectorType (LLVMInt64Type (), 2);
303         } else if (!strcmp (klass->name, "Vector2ul")) {
304                 return LLVMVectorType (LLVMInt64Type (), 2);
305         } else if (!strcmp (klass->name, "Vector4i")) {
306                 return LLVMVectorType (LLVMInt32Type (), 4);
307         } else if (!strcmp (klass->name, "Vector4ui")) {
308                 return LLVMVectorType (LLVMInt32Type (), 4);
309         } else if (!strcmp (klass->name, "Vector4f")) {
310                 return LLVMVectorType (LLVMFloatType (), 4);
311         } else if (!strcmp (klass->name, "Vector8s")) {
312                 return LLVMVectorType (LLVMInt16Type (), 8);
313         } else if (!strcmp (klass->name, "Vector8us")) {
314                 return LLVMVectorType (LLVMInt16Type (), 8);
315         } else if (!strcmp (klass->name, "Vector16sb")) {
316                 return LLVMVectorType (LLVMInt8Type (), 16);
317         } else if (!strcmp (klass->name, "Vector16b")) {
318                 return LLVMVectorType (LLVMInt8Type (), 16);
319         } else {
320                 printf ("%s\n", klass->name);
321                 NOT_IMPLEMENTED;
322                 return NULL;
323         }
324 }
325
326 /* Return the 128 bit SIMD type corresponding to the mono type TYPE */
327 static inline G_GNUC_UNUSED LLVMTypeRef
328 type_to_simd_type (int type)
329 {
330         switch (type) {
331         case MONO_TYPE_I1:
332                 return LLVMVectorType (LLVMInt8Type (), 16);
333         case MONO_TYPE_I2:
334                 return LLVMVectorType (LLVMInt16Type (), 8);
335         case MONO_TYPE_I4:
336                 return LLVMVectorType (LLVMInt32Type (), 4);
337         case MONO_TYPE_I8:
338                 return LLVMVectorType (LLVMInt64Type (), 2);
339         case MONO_TYPE_R8:
340                 return LLVMVectorType (LLVMDoubleType (), 2);
341         case MONO_TYPE_R4:
342                 return LLVMVectorType (LLVMFloatType (), 4);
343         default:
344                 g_assert_not_reached ();
345                 return NULL;
346         }
347 }
348
349 static LLVMTypeRef
350 create_llvm_type_for_type (MonoClass *klass)
351 {
352         int i, size, nfields, esize;
353         LLVMTypeRef *eltypes;
354         char *name;
355         MonoType *t;
356         LLVMTypeRef ltype;
357
358         t = &klass->byval_arg;
359
360         if (mini_type_is_hfa (t, &nfields, &esize)) {
361                 /*
362                  * This is needed on arm64 where HFAs are returned in
363                  * registers.
364                  */
365                 size = nfields;
366                 eltypes = g_new (LLVMTypeRef, size);
367                 for (i = 0; i < size; ++i)
368                         eltypes [i] = esize == 4 ? LLVMFloatType () : LLVMDoubleType ();
369         } else {
370                 size = get_vtype_size (t);
371
372                 eltypes = g_new (LLVMTypeRef, size);
373                 for (i = 0; i < size; ++i)
374                         eltypes [i] = LLVMInt8Type ();
375         }
376
377         name = mono_type_full_name (&klass->byval_arg);
378         ltype = LLVMStructCreateNamed (LLVMGetGlobalContext (), name);
379         LLVMStructSetBody (ltype, eltypes, size, FALSE);
380         g_free (eltypes);
381         g_free (name);
382
383         return ltype;
384 }
385
386 /*
387  * type_to_llvm_type:
388  *
389  *   Return the LLVM type corresponding to T.
390  */
391 static LLVMTypeRef
392 type_to_llvm_type (EmitContext *ctx, MonoType *t)
393 {
394         if (t->byref)
395                 return LLVMPointerType (LLVMInt8Type (), 0);
396
397         t = mini_get_underlying_type (t);
398         switch (t->type) {
399         case MONO_TYPE_VOID:
400                 return LLVMVoidType ();
401         case MONO_TYPE_I1:
402                 return LLVMInt8Type ();
403         case MONO_TYPE_I2:
404                 return LLVMInt16Type ();
405         case MONO_TYPE_I4:
406                 return LLVMInt32Type ();
407         case MONO_TYPE_U1:
408                 return LLVMInt8Type ();
409         case MONO_TYPE_U2:
410                 return LLVMInt16Type ();
411         case MONO_TYPE_U4:
412                 return LLVMInt32Type ();
413         case MONO_TYPE_BOOLEAN:
414                 return LLVMInt8Type ();
415         case MONO_TYPE_I8:
416         case MONO_TYPE_U8:
417                 return LLVMInt64Type ();
418         case MONO_TYPE_CHAR:
419                 return LLVMInt16Type ();
420         case MONO_TYPE_R4:
421                 return LLVMFloatType ();
422         case MONO_TYPE_R8:
423                 return LLVMDoubleType ();
424         case MONO_TYPE_I:
425         case MONO_TYPE_U:
426                 return IntPtrType ();
427         case MONO_TYPE_OBJECT:
428         case MONO_TYPE_CLASS:
429         case MONO_TYPE_ARRAY:
430         case MONO_TYPE_SZARRAY:
431         case MONO_TYPE_STRING:
432         case MONO_TYPE_PTR:
433                 return ObjRefType ();
434         case MONO_TYPE_VAR:
435         case MONO_TYPE_MVAR:
436                 /* Because of generic sharing */
437                 return ObjRefType ();
438         case MONO_TYPE_GENERICINST:
439                 if (!mono_type_generic_inst_is_valuetype (t))
440                         return ObjRefType ();
441                 /* Fall through */
442         case MONO_TYPE_VALUETYPE:
443         case MONO_TYPE_TYPEDBYREF: {
444                 MonoClass *klass;
445                 LLVMTypeRef ltype;
446
447                 klass = mono_class_from_mono_type (t);
448
449                 if (MONO_CLASS_IS_SIMD (ctx->cfg, klass))
450                         return simd_class_to_llvm_type (ctx, klass);
451
452                 if (klass->enumtype)
453                         return type_to_llvm_type (ctx, mono_class_enum_basetype (klass));
454
455                 ltype = g_hash_table_lookup (ctx->lmodule->llvm_types, klass);
456                 if (!ltype) {
457                         ltype = create_llvm_type_for_type (klass);
458                         g_hash_table_insert (ctx->lmodule->llvm_types, klass, ltype);
459                 }
460                 return ltype;
461         }
462
463         default:
464                 printf ("X: %d\n", t->type);
465                 ctx->cfg->exception_message = g_strdup_printf ("type %s", mono_type_full_name (t));
466                 ctx->cfg->disable_llvm = TRUE;
467                 return NULL;
468         }
469 }
470
471 /*
472  * type_is_unsigned:
473  *
474  *   Return whenever T is an unsigned int type.
475  */
476 static gboolean
477 type_is_unsigned (EmitContext *ctx, MonoType *t)
478 {
479         if (t->byref)
480                 return FALSE;
481         switch (t->type) {
482         case MONO_TYPE_U1:
483         case MONO_TYPE_U2:
484         case MONO_TYPE_CHAR:
485         case MONO_TYPE_U4:
486         case MONO_TYPE_U8:
487                 return TRUE;
488         default:
489                 return FALSE;
490         }
491 }
492
493 /*
494  * type_to_llvm_arg_type:
495  *
496  *   Same as type_to_llvm_type, but treat i8/i16 as i32.
497  */
498 static LLVMTypeRef
499 type_to_llvm_arg_type (EmitContext *ctx, MonoType *t)
500 {
501         LLVMTypeRef ptype = type_to_llvm_type (ctx, t);
502
503         /*
504          * This works on all abis except arm64/ios which passes multiple
505          * arguments in one stack slot.
506          */
507 #ifndef TARGET_ARM64
508         if (ptype == LLVMInt8Type () || ptype == LLVMInt16Type ()) {
509                 /* 
510                  * LLVM generates code which only sets the lower bits, while JITted
511                  * code expects all the bits to be set.
512                  */
513                 ptype = LLVMInt32Type ();
514         }
515 #endif
516
517         return ptype;
518 }
519
520 /*
521  * llvm_type_to_stack_type:
522  *
523  *   Return the LLVM type which needs to be used when a value of type TYPE is pushed
524  * on the IL stack.
525  */
526 static G_GNUC_UNUSED LLVMTypeRef
527 llvm_type_to_stack_type (MonoCompile *cfg, LLVMTypeRef type)
528 {
529         if (type == NULL)
530                 return NULL;
531         if (type == LLVMInt8Type ())
532                 return LLVMInt32Type ();
533         else if (type == LLVMInt16Type ())
534                 return LLVMInt32Type ();
535         else if (!cfg->r4fp && type == LLVMFloatType ())
536                 return LLVMDoubleType ();
537         else
538                 return type;
539 }
540
541 /*
542  * regtype_to_llvm_type:
543  *
544  *   Return the LLVM type corresponding to the regtype C used in instruction 
545  * descriptions.
546  */
547 static LLVMTypeRef
548 regtype_to_llvm_type (char c)
549 {
550         switch (c) {
551         case 'i':
552                 return LLVMInt32Type ();
553         case 'l':
554                 return LLVMInt64Type ();
555         case 'f':
556                 return LLVMDoubleType ();
557         default:
558                 return NULL;
559         }
560 }
561
562 /*
563  * op_to_llvm_type:
564  *
565  *   Return the LLVM type corresponding to the unary/binary opcode OPCODE.
566  */
567 static LLVMTypeRef
568 op_to_llvm_type (int opcode)
569 {
570         switch (opcode) {
571         case OP_ICONV_TO_I1:
572         case OP_LCONV_TO_I1:
573                 return LLVMInt8Type ();
574         case OP_ICONV_TO_U1:
575         case OP_LCONV_TO_U1:
576                 return LLVMInt8Type ();
577         case OP_ICONV_TO_I2:
578         case OP_LCONV_TO_I2:
579                 return LLVMInt16Type ();
580         case OP_ICONV_TO_U2:
581         case OP_LCONV_TO_U2:
582                 return LLVMInt16Type ();
583         case OP_ICONV_TO_I4:
584         case OP_LCONV_TO_I4:
585                 return LLVMInt32Type ();
586         case OP_ICONV_TO_U4:
587         case OP_LCONV_TO_U4:
588                 return LLVMInt32Type ();
589         case OP_ICONV_TO_I8:
590                 return LLVMInt64Type ();
591         case OP_ICONV_TO_R4:
592                 return LLVMFloatType ();
593         case OP_ICONV_TO_R8:
594                 return LLVMDoubleType ();
595         case OP_ICONV_TO_U8:
596                 return LLVMInt64Type ();
597         case OP_FCONV_TO_I4:
598                 return LLVMInt32Type ();
599         case OP_FCONV_TO_I8:
600                 return LLVMInt64Type ();
601         case OP_FCONV_TO_I1:
602         case OP_FCONV_TO_U1:
603         case OP_RCONV_TO_I1:
604         case OP_RCONV_TO_U1:
605                 return LLVMInt8Type ();
606         case OP_FCONV_TO_I2:
607         case OP_FCONV_TO_U2:
608         case OP_RCONV_TO_I2:
609         case OP_RCONV_TO_U2:
610                 return LLVMInt16Type ();
611         case OP_FCONV_TO_I:
612         case OP_FCONV_TO_U:
613                 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
614         case OP_IADD_OVF:
615         case OP_IADD_OVF_UN:
616         case OP_ISUB_OVF:
617         case OP_ISUB_OVF_UN:
618         case OP_IMUL_OVF:
619         case OP_IMUL_OVF_UN:
620                 return LLVMInt32Type ();
621         case OP_LADD_OVF:
622         case OP_LADD_OVF_UN:
623         case OP_LSUB_OVF:
624         case OP_LSUB_OVF_UN:
625         case OP_LMUL_OVF:
626         case OP_LMUL_OVF_UN:
627                 return LLVMInt64Type ();
628         default:
629                 printf ("%s\n", mono_inst_name (opcode));
630                 g_assert_not_reached ();
631                 return NULL;
632         }
633 }               
634
635 /*
636  * load_store_to_llvm_type:
637  *
638  *   Return the size/sign/zero extension corresponding to the load/store opcode
639  * OPCODE.
640  */
641 static LLVMTypeRef
642 load_store_to_llvm_type (int opcode, int *size, gboolean *sext, gboolean *zext)
643 {
644         *sext = FALSE;
645         *zext = FALSE;
646
647         switch (opcode) {
648         case OP_LOADI1_MEMBASE:
649         case OP_STOREI1_MEMBASE_REG:
650         case OP_STOREI1_MEMBASE_IMM:
651         case OP_ATOMIC_LOAD_I1:
652         case OP_ATOMIC_STORE_I1:
653                 *size = 1;
654                 *sext = TRUE;
655                 return LLVMInt8Type ();
656         case OP_LOADU1_MEMBASE:
657         case OP_LOADU1_MEM:
658         case OP_ATOMIC_LOAD_U1:
659         case OP_ATOMIC_STORE_U1:
660                 *size = 1;
661                 *zext = TRUE;
662                 return LLVMInt8Type ();
663         case OP_LOADI2_MEMBASE:
664         case OP_STOREI2_MEMBASE_REG:
665         case OP_STOREI2_MEMBASE_IMM:
666         case OP_ATOMIC_LOAD_I2:
667         case OP_ATOMIC_STORE_I2:
668                 *size = 2;
669                 *sext = TRUE;
670                 return LLVMInt16Type ();
671         case OP_LOADU2_MEMBASE:
672         case OP_LOADU2_MEM:
673         case OP_ATOMIC_LOAD_U2:
674         case OP_ATOMIC_STORE_U2:
675                 *size = 2;
676                 *zext = TRUE;
677                 return LLVMInt16Type ();
678         case OP_LOADI4_MEMBASE:
679         case OP_LOADU4_MEMBASE:
680         case OP_LOADI4_MEM:
681         case OP_LOADU4_MEM:
682         case OP_STOREI4_MEMBASE_REG:
683         case OP_STOREI4_MEMBASE_IMM:
684         case OP_ATOMIC_LOAD_I4:
685         case OP_ATOMIC_STORE_I4:
686         case OP_ATOMIC_LOAD_U4:
687         case OP_ATOMIC_STORE_U4:
688                 *size = 4;
689                 return LLVMInt32Type ();
690         case OP_LOADI8_MEMBASE:
691         case OP_LOADI8_MEM:
692         case OP_STOREI8_MEMBASE_REG:
693         case OP_STOREI8_MEMBASE_IMM:
694         case OP_ATOMIC_LOAD_I8:
695         case OP_ATOMIC_STORE_I8:
696         case OP_ATOMIC_LOAD_U8:
697         case OP_ATOMIC_STORE_U8:
698                 *size = 8;
699                 return LLVMInt64Type ();
700         case OP_LOADR4_MEMBASE:
701         case OP_STORER4_MEMBASE_REG:
702         case OP_ATOMIC_LOAD_R4:
703         case OP_ATOMIC_STORE_R4:
704                 *size = 4;
705                 return LLVMFloatType ();
706         case OP_LOADR8_MEMBASE:
707         case OP_STORER8_MEMBASE_REG:
708         case OP_ATOMIC_LOAD_R8:
709         case OP_ATOMIC_STORE_R8:
710                 *size = 8;
711                 return LLVMDoubleType ();
712         case OP_LOAD_MEMBASE:
713         case OP_LOAD_MEM:
714         case OP_STORE_MEMBASE_REG:
715         case OP_STORE_MEMBASE_IMM:
716                 *size = sizeof (gpointer);
717                 return IntPtrType ();
718         default:
719                 g_assert_not_reached ();
720                 return NULL;
721         }
722 }
723
724 /*
725  * ovf_op_to_intrins:
726  *
727  *   Return the LLVM intrinsics corresponding to the overflow opcode OPCODE.
728  */
729 static const char*
730 ovf_op_to_intrins (int opcode)
731 {
732         switch (opcode) {
733         case OP_IADD_OVF:
734                 return "llvm.sadd.with.overflow.i32";
735         case OP_IADD_OVF_UN:
736                 return "llvm.uadd.with.overflow.i32";
737         case OP_ISUB_OVF:
738                 return "llvm.ssub.with.overflow.i32";
739         case OP_ISUB_OVF_UN:
740                 return "llvm.usub.with.overflow.i32";
741         case OP_IMUL_OVF:
742                 return "llvm.smul.with.overflow.i32";
743         case OP_IMUL_OVF_UN:
744                 return "llvm.umul.with.overflow.i32";
745         case OP_LADD_OVF:
746                 return "llvm.sadd.with.overflow.i64";
747         case OP_LADD_OVF_UN:
748                 return "llvm.uadd.with.overflow.i64";
749         case OP_LSUB_OVF:
750                 return "llvm.ssub.with.overflow.i64";
751         case OP_LSUB_OVF_UN:
752                 return "llvm.usub.with.overflow.i64";
753         case OP_LMUL_OVF:
754                 return "llvm.smul.with.overflow.i64";
755         case OP_LMUL_OVF_UN:
756                 return "llvm.umul.with.overflow.i64";
757         default:
758                 g_assert_not_reached ();
759                 return NULL;
760         }
761 }
762
763 static const char*
764 simd_op_to_intrins (int opcode)
765 {
766         switch (opcode) {
767 #if defined(TARGET_X86) || defined(TARGET_AMD64)
768         case OP_MINPD:
769                 return "llvm.x86.sse2.min.pd";
770         case OP_MINPS:
771                 return "llvm.x86.sse.min.ps";
772         case OP_PMIND_UN:
773                 return "llvm.x86.sse41.pminud";
774         case OP_PMINW_UN:
775                 return "llvm.x86.sse41.pminuw";
776         case OP_PMINB_UN:
777                 return "llvm.x86.sse2.pminu.b";
778         case OP_PMINW:
779                 return "llvm.x86.sse2.pmins.w";
780         case OP_MAXPD:
781                 return "llvm.x86.sse2.max.pd";
782         case OP_MAXPS:
783                 return "llvm.x86.sse.max.ps";
784         case OP_HADDPD:
785                 return "llvm.x86.sse3.hadd.pd";
786         case OP_HADDPS:
787                 return "llvm.x86.sse3.hadd.ps";
788         case OP_HSUBPD:
789                 return "llvm.x86.sse3.hsub.pd";
790         case OP_HSUBPS:
791                 return "llvm.x86.sse3.hsub.ps";
792         case OP_PMAXD_UN:
793                 return "llvm.x86.sse41.pmaxud";
794         case OP_PMAXW_UN:
795                 return "llvm.x86.sse41.pmaxuw";
796         case OP_PMAXB_UN:
797                 return "llvm.x86.sse2.pmaxu.b";
798         case OP_ADDSUBPS:
799                 return "llvm.x86.sse3.addsub.ps";
800         case OP_ADDSUBPD:
801                 return "llvm.x86.sse3.addsub.pd";
802         case OP_EXTRACT_MASK:
803                 return "llvm.x86.sse2.pmovmskb.128";
804         case OP_PSHRW:
805         case OP_PSHRW_REG:
806                 return "llvm.x86.sse2.psrli.w";
807         case OP_PSHRD:
808         case OP_PSHRD_REG:
809                 return "llvm.x86.sse2.psrli.d";
810         case OP_PSHRQ:
811         case OP_PSHRQ_REG:
812                 return "llvm.x86.sse2.psrli.q";
813         case OP_PSHLW:
814         case OP_PSHLW_REG:
815                 return "llvm.x86.sse2.pslli.w";
816         case OP_PSHLD:
817         case OP_PSHLD_REG:
818                 return "llvm.x86.sse2.pslli.d";
819         case OP_PSHLQ:
820         case OP_PSHLQ_REG:
821                 return "llvm.x86.sse2.pslli.q";
822         case OP_PSARW:
823         case OP_PSARW_REG:
824                 return "llvm.x86.sse2.psrai.w";
825         case OP_PSARD:
826         case OP_PSARD_REG:
827                 return "llvm.x86.sse2.psrai.d";
828         case OP_PADDB_SAT:
829                 return "llvm.x86.sse2.padds.b";
830         case OP_PADDW_SAT:
831                 return "llvm.x86.sse2.padds.w";
832         case OP_PSUBB_SAT:
833                 return "llvm.x86.sse2.psubs.b";
834         case OP_PSUBW_SAT:
835                 return "llvm.x86.sse2.psubs.w";
836         case OP_PADDB_SAT_UN:
837                 return "llvm.x86.sse2.paddus.b";
838         case OP_PADDW_SAT_UN:
839                 return "llvm.x86.sse2.paddus.w";
840         case OP_PSUBB_SAT_UN:
841                 return "llvm.x86.sse2.psubus.b";
842         case OP_PSUBW_SAT_UN:
843                 return "llvm.x86.sse2.psubus.w";
844         case OP_PAVGB_UN:
845                 return "llvm.x86.sse2.pavg.b";
846         case OP_PAVGW_UN:
847                 return "llvm.x86.sse2.pavg.w";
848         case OP_SQRTPS:
849                 return "llvm.x86.sse.sqrt.ps";
850         case OP_SQRTPD:
851                 return "llvm.x86.sse2.sqrt.pd";
852         case OP_RSQRTPS:
853                 return "llvm.x86.sse.rsqrt.ps";
854         case OP_RCPPS:
855                 return "llvm.x86.sse.rcp.ps";
856         case OP_CVTDQ2PD:
857                 return "llvm.x86.sse2.cvtdq2pd";
858         case OP_CVTDQ2PS:
859                 return "llvm.x86.sse2.cvtdq2ps";
860         case OP_CVTPD2DQ:
861                 return "llvm.x86.sse2.cvtpd2dq";
862         case OP_CVTPS2DQ:
863                 return "llvm.x86.sse2.cvtps2dq";
864         case OP_CVTPD2PS:
865                 return "llvm.x86.sse2.cvtpd2ps";
866         case OP_CVTPS2PD:
867                 return "llvm.x86.sse2.cvtps2pd";
868         case OP_CVTTPD2DQ:
869                 return "llvm.x86.sse2.cvttpd2dq";
870         case OP_CVTTPS2DQ:
871                 return "llvm.x86.sse2.cvttps2dq";
872         case OP_COMPPS:
873                 return "llvm.x86.sse.cmp.ps";
874         case OP_COMPPD:
875                 return "llvm.x86.sse2.cmp.pd";
876         case OP_PACKW:
877                 return "llvm.x86.sse2.packsswb.128";
878         case OP_PACKD:
879                 return "llvm.x86.sse2.packssdw.128";
880         case OP_PACKW_UN:
881                 return "llvm.x86.sse2.packuswb.128";
882         case OP_PACKD_UN:
883                 return "llvm.x86.sse41.packusdw";
884         case OP_PMULW_HIGH:
885                 return "llvm.x86.sse2.pmulh.w";
886         case OP_PMULW_HIGH_UN:
887                 return "llvm.x86.sse2.pmulhu.w";
888 #endif
889         default:
890                 g_assert_not_reached ();
891                 return NULL;
892         }
893 }
894
895 static LLVMTypeRef
896 simd_op_to_llvm_type (int opcode)
897 {
898 #if defined(TARGET_X86) || defined(TARGET_AMD64)
899         switch (opcode) {
900         case OP_EXTRACT_R8:
901         case OP_EXPAND_R8:
902                 return type_to_simd_type (MONO_TYPE_R8);
903         case OP_EXTRACT_I8:
904         case OP_EXPAND_I8:
905                 return type_to_simd_type (MONO_TYPE_I8);
906         case OP_EXTRACT_I4:
907         case OP_EXPAND_I4:
908                 return type_to_simd_type (MONO_TYPE_I4);
909         case OP_EXTRACT_I2:
910         case OP_EXTRACT_U2:
911         case OP_EXTRACTX_U2:
912         case OP_EXPAND_I2:
913                 return type_to_simd_type (MONO_TYPE_I2);
914         case OP_EXTRACT_I1:
915         case OP_EXTRACT_U1:
916         case OP_EXPAND_I1:
917                 return type_to_simd_type (MONO_TYPE_I1);
918         case OP_EXPAND_R4:
919                 return type_to_simd_type (MONO_TYPE_R4);
920         case OP_CVTDQ2PD:
921         case OP_CVTDQ2PS:
922                 return type_to_simd_type (MONO_TYPE_I4);
923         case OP_CVTPD2DQ:
924         case OP_CVTPD2PS:
925         case OP_CVTTPD2DQ:
926                 return type_to_simd_type (MONO_TYPE_R8);
927         case OP_CVTPS2DQ:
928         case OP_CVTPS2PD:
929         case OP_CVTTPS2DQ:
930                 return type_to_simd_type (MONO_TYPE_R4);
931         case OP_EXTRACT_MASK:
932                 return type_to_simd_type (MONO_TYPE_I1);
933         case OP_SQRTPS:
934         case OP_RSQRTPS:
935         case OP_RCPPS:
936         case OP_DUPPS_LOW:
937         case OP_DUPPS_HIGH:
938                 return type_to_simd_type (MONO_TYPE_R4);
939         case OP_SQRTPD:
940         case OP_DUPPD:
941                 return type_to_simd_type (MONO_TYPE_R8);
942         default:
943                 g_assert_not_reached ();
944                 return NULL;
945         }
946 #else
947         return NULL;
948 #endif
949 }
950
951 /*
952  * get_bb:
953  *
954  *   Return the LLVM basic block corresponding to BB.
955  */
956 static LLVMBasicBlockRef
957 get_bb (EmitContext *ctx, MonoBasicBlock *bb)
958 {
959         char bb_name_buf [128];
960         char *bb_name;
961
962         if (ctx->bblocks [bb->block_num].bblock == NULL) {
963                 if (bb->flags & BB_EXCEPTION_HANDLER) {
964                         int clause_index = (mono_get_block_region_notry (ctx->cfg, bb->region) >> 8) - 1;
965                         sprintf (bb_name_buf, "EH_CLAUSE%d_BB%d", clause_index, bb->block_num);
966                         bb_name = bb_name_buf;
967                 } else if (bb->block_num < 256) {
968                         if (!ctx->lmodule->bb_names) {
969                                 ctx->lmodule->bb_names_len = 256;
970                                 ctx->lmodule->bb_names = g_new0 (char*, ctx->lmodule->bb_names_len);
971                         }
972                         if (!ctx->lmodule->bb_names [bb->block_num]) {
973                                 char *n;
974
975                                 n = g_strdup_printf ("BB%d", bb->block_num);
976                                 mono_memory_barrier ();
977                                 ctx->lmodule->bb_names [bb->block_num] = n;
978                         }
979                         bb_name = ctx->lmodule->bb_names [bb->block_num];
980                 } else {
981                         sprintf (bb_name_buf, "BB%d", bb->block_num);
982                         bb_name = bb_name_buf;
983                 }
984
985                 ctx->bblocks [bb->block_num].bblock = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
986                 ctx->bblocks [bb->block_num].end_bblock = ctx->bblocks [bb->block_num].bblock;
987         }
988
989         return ctx->bblocks [bb->block_num].bblock;
990 }
991
992 /* 
993  * get_end_bb:
994  *
995  *   Return the last LLVM bblock corresponding to BB.
996  * This might not be equal to the bb returned by get_bb () since we need to generate
997  * multiple LLVM bblocks for a mono bblock to handle throwing exceptions.
998  */
999 static LLVMBasicBlockRef
1000 get_end_bb (EmitContext *ctx, MonoBasicBlock *bb)
1001 {
1002         get_bb (ctx, bb);
1003         return ctx->bblocks [bb->block_num].end_bblock;
1004 }
1005
1006 static LLVMBasicBlockRef
1007 gen_bb (EmitContext *ctx, const char *prefix)
1008 {
1009         char bb_name [128];
1010
1011         sprintf (bb_name, "%s%d", prefix, ++ ctx->ex_index);
1012         return LLVMAppendBasicBlock (ctx->lmethod, bb_name);
1013 }
1014
1015 /*
1016  * resolve_patch:
1017  *
1018  *   Return the target of the patch identified by TYPE and TARGET.
1019  */
1020 static gpointer
1021 resolve_patch (MonoCompile *cfg, MonoJumpInfoType type, gconstpointer target)
1022 {
1023         MonoJumpInfo ji;
1024
1025         memset (&ji, 0, sizeof (ji));
1026         ji.type = type;
1027         ji.data.target = target;
1028
1029         return mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
1030 }
1031
1032 /*
1033  * convert_full:
1034  *
1035  *   Emit code to convert the LLVM value V to DTYPE.
1036  */
1037 static LLVMValueRef
1038 convert_full (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype, gboolean is_unsigned)
1039 {
1040         LLVMTypeRef stype = LLVMTypeOf (v);
1041
1042         if (stype != dtype) {
1043                 gboolean ext = FALSE;
1044
1045                 /* Extend */
1046                 if (dtype == LLVMInt64Type () && (stype == LLVMInt32Type () || stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
1047                         ext = TRUE;
1048                 else if (dtype == LLVMInt32Type () && (stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
1049                         ext = TRUE;
1050                 else if (dtype == LLVMInt16Type () && (stype == LLVMInt8Type ()))
1051                         ext = TRUE;
1052
1053                 if (ext)
1054                         return is_unsigned ? LLVMBuildZExt (ctx->builder, v, dtype, "") : LLVMBuildSExt (ctx->builder, v, dtype, "");
1055
1056                 if (dtype == LLVMDoubleType () && stype == LLVMFloatType ())
1057                         return LLVMBuildFPExt (ctx->builder, v, dtype, "");
1058
1059                 /* Trunc */
1060                 if (stype == LLVMInt64Type () && (dtype == LLVMInt32Type () || dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
1061                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
1062                 if (stype == LLVMInt32Type () && (dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
1063                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
1064                 if (stype == LLVMInt16Type () && dtype == LLVMInt8Type ())
1065                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
1066                 if (stype == LLVMDoubleType () && dtype == LLVMFloatType ())
1067                         return LLVMBuildFPTrunc (ctx->builder, v, dtype, "");
1068
1069                 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind && LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
1070                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1071                 if (LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
1072                         return LLVMBuildIntToPtr (ctx->builder, v, dtype, "");
1073                 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind)
1074                         return LLVMBuildPtrToInt (ctx->builder, v, dtype, "");
1075
1076                 if (mono_arch_is_soft_float ()) {
1077                         if (stype == LLVMInt32Type () && dtype == LLVMFloatType ())
1078                                 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1079                         if (stype == LLVMInt32Type () && dtype == LLVMDoubleType ())
1080                                 return LLVMBuildBitCast (ctx->builder, LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), ""), dtype, "");
1081                 }
1082
1083                 if (LLVMGetTypeKind (stype) == LLVMVectorTypeKind && LLVMGetTypeKind (dtype) == LLVMVectorTypeKind)
1084                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1085
1086                 LLVMDumpValue (v);
1087                 LLVMDumpValue (LLVMConstNull (dtype));
1088                 g_assert_not_reached ();
1089                 return NULL;
1090         } else {
1091                 return v;
1092         }
1093 }
1094
1095 static LLVMValueRef
1096 convert (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype)
1097 {
1098         return convert_full (ctx, v, dtype, FALSE);
1099 }
1100
1101 /*
1102  * emit_volatile_load:
1103  *
1104  *   If vreg is volatile, emit a load from its address.
1105  */
1106 static LLVMValueRef
1107 emit_volatile_load (EmitContext *ctx, int vreg)
1108 {
1109         MonoType *t;
1110
1111         LLVMValueRef v = LLVMBuildLoad (ctx->builder, ctx->addresses [vreg], "");
1112         t = ctx->vreg_cli_types [vreg];
1113         if (t && !t->byref) {
1114                 /* 
1115                  * Might have to zero extend since llvm doesn't have 
1116                  * unsigned types.
1117                  */
1118                 if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_U2 || t->type == MONO_TYPE_CHAR || t->type == MONO_TYPE_BOOLEAN)
1119                         v = LLVMBuildZExt (ctx->builder, v, LLVMInt32Type (), "");
1120                 else if (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2)
1121                         v = LLVMBuildSExt (ctx->builder, v, LLVMInt32Type (), "");
1122                 else if (t->type == MONO_TYPE_U8)
1123                         v = LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), "");
1124         }
1125
1126         return v;
1127 }
1128
1129 /*
1130  * emit_volatile_store:
1131  *
1132  *   If VREG is volatile, emit a store from its value to its address.
1133  */
1134 static void
1135 emit_volatile_store (EmitContext *ctx, int vreg)
1136 {
1137         MonoInst *var = get_vreg_to_inst (ctx->cfg, vreg);
1138
1139         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
1140                 g_assert (ctx->addresses [vreg]);
1141                 LLVMBuildStore (ctx->builder, convert (ctx, ctx->values [vreg], type_to_llvm_type (ctx, var->inst_vtype)), ctx->addresses [vreg]);
1142         }
1143 }
1144
1145 typedef struct {
1146         /* 
1147          * Maps parameter indexes in the original signature to parameter indexes
1148          * in the LLVM signature.
1149          */
1150         int *pindexes;
1151         /* The indexes of various special arguments in the LLVM signature */
1152         int vret_arg_pindex, this_arg_pindex, rgctx_arg_pindex, imt_arg_pindex;
1153 } LLVMSigInfo;
1154
1155 /*
1156  * sig_to_llvm_sig_full:
1157  *
1158  *   Return the LLVM signature corresponding to the mono signature SIG using the
1159  * calling convention information in CINFO. Return parameter mapping information in SINFO.
1160  */
1161 static LLVMTypeRef
1162 sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *cinfo,
1163                                           LLVMSigInfo *sinfo)
1164 {
1165         LLVMTypeRef ret_type;
1166         LLVMTypeRef *param_types = NULL;
1167         LLVMTypeRef res;
1168         int i, j, pindex, vret_arg_pindex = 0;
1169         int *pindexes;
1170         gboolean vretaddr = FALSE;
1171         MonoType *rtype;
1172
1173         if (sinfo)
1174                 memset (sinfo, 0, sizeof (LLVMSigInfo));
1175
1176         rtype = mini_get_underlying_type (sig->ret);
1177         ret_type = type_to_llvm_type (ctx, rtype);
1178         CHECK_FAILURE (ctx);
1179
1180         if (cinfo) {
1181                 switch (cinfo->ret.storage) {
1182                 case LLVMArgVtypeInReg:
1183                         /* LLVM models this by returning an aggregate value */
1184                         if (cinfo->ret.pair_storage [0] == LLVMArgInIReg && cinfo->ret.pair_storage [1] == LLVMArgNone) {
1185                                 LLVMTypeRef members [2];
1186
1187                                 members [0] = IntPtrType ();
1188                                 ret_type = LLVMStructType (members, 1, FALSE);
1189                         } else {
1190                                 g_assert_not_reached ();
1191                         }
1192                         break;
1193                 case LLVMArgVtypeByVal:
1194                         /* Vtype returned normally by val */
1195                         break;
1196                 case LLVMArgVtypeAsScalar:
1197                         /* LLVM models this by returning an int */
1198                         g_assert (cinfo->ret.nslots == 1 || cinfo->ret.nslots == 2);
1199                         ret_type = LLVMIntType (cinfo->ret.nslots * sizeof (mgreg_t) * 8);
1200                         break;
1201                 case LLVMArgFpStruct: {
1202                         /* Vtype returned as a fp struct */
1203                         LLVMTypeRef members [16];
1204
1205                         /* Have to create our own structure since we don't map fp structures to LLVM fp structures yet */
1206                         for (i = 0; i < cinfo->ret.nslots; ++i)
1207                                 members [i] = cinfo->ret.esize == 8 ? LLVMDoubleType () : LLVMFloatType ();
1208                         ret_type = LLVMStructType (members, cinfo->ret.nslots, FALSE);
1209                         break;
1210                 }
1211                 case LLVMArgVtypeByRef:
1212                         /* Vtype returned using a hidden argument */
1213                         ret_type = LLVMVoidType ();
1214                         break;
1215                 default:
1216                         if (mini_type_is_vtype (rtype)) {
1217                                 g_assert (cinfo->ret.storage == LLVMArgVtypeRetAddr);
1218                                 vretaddr = TRUE;
1219                                 ret_type = LLVMVoidType ();
1220                         }
1221                         break;
1222                 }
1223         }
1224
1225         pindexes = g_new0 (int, sig->param_count);
1226         param_types = g_new0 (LLVMTypeRef, (sig->param_count * 8) + 3);
1227         pindex = 0;
1228         if (cinfo && cinfo->ret.storage == LLVMArgVtypeByRef) {
1229                 /*
1230                  * Has to be the first argument because of the sret argument attribute
1231                  * FIXME: This might conflict with passing 'this' as the first argument, but
1232                  * this is only used on arm64 which has a dedicated struct return register.
1233                  */
1234                 if (sinfo)
1235                         sinfo->vret_arg_pindex = pindex;
1236                 param_types [pindex] = type_to_llvm_arg_type (ctx, sig->ret);
1237                 CHECK_FAILURE (ctx);
1238                 param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1239                 pindex ++;
1240         }
1241         if (cinfo && cinfo->rgctx_arg) {
1242                 if (sinfo)
1243                         sinfo->rgctx_arg_pindex = pindex;
1244                 param_types [pindex] = ctx->lmodule->ptr_type;
1245                 pindex ++;
1246         }
1247         if (cinfo && cinfo->imt_arg) {
1248                 if (sinfo)
1249                         sinfo->imt_arg_pindex = pindex;
1250                 param_types [pindex] = ctx->lmodule->ptr_type;
1251                 pindex ++;
1252         }
1253         if (vretaddr) {
1254                 /* Compute the index in the LLVM signature where the vret arg needs to be passed */
1255                 vret_arg_pindex = pindex;
1256                 if (cinfo->vret_arg_index == 1) {
1257                         /* Add the slots consumed by the first argument */
1258                         LLVMArgInfo *ainfo = &cinfo->args [0];
1259                         switch (ainfo->storage) {
1260                         case LLVMArgVtypeInReg:
1261                                 for (j = 0; j < 2; ++j) {
1262                                         if (ainfo->pair_storage [j] == LLVMArgInIReg)
1263                                                 vret_arg_pindex ++;
1264                                 }
1265                                 break;
1266                         default:
1267                                 vret_arg_pindex ++;
1268                         }
1269                 }
1270
1271                 if (sinfo)
1272                         sinfo->vret_arg_pindex = vret_arg_pindex;
1273         }                               
1274
1275         if (vretaddr && vret_arg_pindex == pindex)
1276                 param_types [pindex ++] = IntPtrType ();
1277         if (sig->hasthis) {
1278                 if (sinfo)
1279                         sinfo->this_arg_pindex = pindex;
1280                 param_types [pindex ++] = ThisType ();
1281         }
1282         if (vretaddr && vret_arg_pindex == pindex)
1283                 param_types [pindex ++] = IntPtrType ();
1284         for (i = 0; i < sig->param_count; ++i) {
1285                 LLVMArgInfo *ainfo = cinfo ? &cinfo->args [i + sig->hasthis] : NULL;
1286
1287                 if (vretaddr && vret_arg_pindex == pindex)
1288                         param_types [pindex ++] = IntPtrType ();
1289                 pindexes [i] = pindex;
1290
1291                 if (!ainfo) {
1292                         param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1293                         continue;
1294                 }
1295
1296                 switch (ainfo->storage) {
1297                 case LLVMArgVtypeInReg:
1298                         for (j = 0; j < 2; ++j) {
1299                                 switch (ainfo->pair_storage [j]) {
1300                                 case LLVMArgInIReg:
1301                                         param_types [pindex ++] = LLVMIntType (sizeof (gpointer) * 8);
1302                                         break;
1303                                 case LLVMArgNone:
1304                                         break;
1305                                 default:
1306                                         g_assert_not_reached ();
1307                                 }
1308                         }
1309                         break;
1310                 case LLVMArgVtypeByVal:
1311                         param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1312                         CHECK_FAILURE (ctx);
1313                         param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1314                         pindex ++;
1315                         break;
1316                 case LLVMArgAsIArgs:
1317                         param_types [pindex] = LLVMArrayType (IntPtrType (), ainfo->nslots);
1318                         pindex ++;
1319                         break;
1320                 case LLVMArgVtypeByRef:
1321                         param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1322                         CHECK_FAILURE (ctx);
1323                         param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1324                         pindex ++;
1325                         break;
1326                 case LLVMArgAsFpArgs: {
1327                         int j;
1328
1329                         for (j = 0; j < ainfo->nslots; ++j)
1330                                 param_types [pindex + j] = ainfo->esize == 8 ? LLVMDoubleType () : LLVMFloatType ();
1331                         pindex += ainfo->nslots;
1332                         break;
1333                 }
1334                 case LLVMArgVtypeAsScalar:
1335                         g_assert_not_reached ();
1336                         break;
1337                 default:
1338                         param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1339                         break;
1340                 }
1341         }
1342         if (vretaddr && vret_arg_pindex == pindex)
1343                 param_types [pindex ++] = IntPtrType ();
1344
1345         CHECK_FAILURE (ctx);
1346
1347         res = LLVMFunctionType (ret_type, param_types, pindex, FALSE);
1348         g_free (param_types);
1349
1350         if (sinfo) {
1351                 sinfo->pindexes = pindexes;
1352         } else {
1353                 g_free (pindexes);
1354         }
1355
1356         return res;
1357
1358  FAILURE:
1359         g_free (param_types);
1360
1361         return NULL;
1362 }
1363
1364 static LLVMTypeRef
1365 sig_to_llvm_sig (EmitContext *ctx, MonoMethodSignature *sig)
1366 {
1367         return sig_to_llvm_sig_full (ctx, sig, NULL, NULL);
1368 }
1369
1370 /*
1371  * LLVMFunctionType1:
1372  *
1373  *   Create an LLVM function type from the arguments.
1374  */
1375 static G_GNUC_UNUSED LLVMTypeRef 
1376 LLVMFunctionType1(LLVMTypeRef ReturnType,
1377                                   LLVMTypeRef ParamType1,
1378                                   int IsVarArg)
1379 {
1380         LLVMTypeRef param_types [1];
1381
1382         param_types [0] = ParamType1;
1383
1384         return LLVMFunctionType (ReturnType, param_types, 1, IsVarArg);
1385 }
1386
1387 /*
1388  * LLVMFunctionType2:
1389  *
1390  *   Create an LLVM function type from the arguments.
1391  */
1392 static G_GNUC_UNUSED LLVMTypeRef
1393 LLVMFunctionType2(LLVMTypeRef ReturnType,
1394                                   LLVMTypeRef ParamType1,
1395                                   LLVMTypeRef ParamType2,
1396                                   int IsVarArg)
1397 {
1398         LLVMTypeRef param_types [2];
1399
1400         param_types [0] = ParamType1;
1401         param_types [1] = ParamType2;
1402
1403         return LLVMFunctionType (ReturnType, param_types, 2, IsVarArg);
1404 }
1405
1406 /*
1407  * LLVMFunctionType3:
1408  *
1409  *   Create an LLVM function type from the arguments.
1410  */
1411 static G_GNUC_UNUSED LLVMTypeRef
1412 LLVMFunctionType3(LLVMTypeRef ReturnType,
1413                                   LLVMTypeRef ParamType1,
1414                                   LLVMTypeRef ParamType2,
1415                                   LLVMTypeRef ParamType3,
1416                                   int IsVarArg)
1417 {
1418         LLVMTypeRef param_types [3];
1419
1420         param_types [0] = ParamType1;
1421         param_types [1] = ParamType2;
1422         param_types [2] = ParamType3;
1423
1424         return LLVMFunctionType (ReturnType, param_types, 3, IsVarArg);
1425 }
1426
1427 /*
1428  * create_builder:
1429  *
1430  *   Create an LLVM builder and remember it so it can be freed later.
1431  */
1432 static LLVMBuilderRef
1433 create_builder (EmitContext *ctx)
1434 {
1435         LLVMBuilderRef builder = LLVMCreateBuilder ();
1436
1437         ctx->builders = g_slist_prepend_mempool (ctx->cfg->mempool, ctx->builders, builder);
1438
1439         return builder;
1440 }
1441
1442 static LLVMValueRef
1443 get_plt_entry (EmitContext *ctx, LLVMTypeRef llvm_sig, MonoJumpInfoType type, gconstpointer data)
1444 {
1445         char *callee_name = mono_aot_get_plt_symbol (type, data);
1446         LLVMValueRef callee;
1447         MonoJumpInfo *ji = NULL;
1448
1449         if (!callee_name)
1450                 return NULL;
1451
1452         if (ctx->cfg->compile_aot)
1453                 /* Add a patch so referenced wrappers can be compiled in full aot mode */
1454                 mono_add_patch_info (ctx->cfg, 0, type, data);
1455
1456         // FIXME: Locking
1457         callee = g_hash_table_lookup (ctx->lmodule->plt_entries, callee_name);
1458         if (!callee) {
1459                 callee = LLVMAddFunction (ctx->module, callee_name, llvm_sig);
1460
1461                 LLVMSetVisibility (callee, LLVMHiddenVisibility);
1462
1463                 g_hash_table_insert (ctx->lmodule->plt_entries, (char*)callee_name, callee);
1464         }
1465
1466         if (ctx->cfg->compile_aot) {
1467                 ji = g_new0 (MonoJumpInfo, 1);
1468                 ji->type = type;
1469                 ji->data.target = data;
1470
1471                 g_hash_table_insert (ctx->lmodule->plt_entries_ji, ji, callee);
1472         }
1473
1474         return callee;
1475 }
1476
1477 static int
1478 get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
1479 {
1480         MonoMethodHeader *header = cfg->header;
1481         MonoExceptionClause *clause;
1482         int i;
1483
1484         /* Directly */
1485         if (bb->region != -1 && MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
1486                 return (bb->region >> 8) - 1;
1487
1488         /* Indirectly */
1489         for (i = 0; i < header->num_clauses; ++i) {
1490                 clause = &header->clauses [i];
1491                            
1492                 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset) && clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
1493                         return i;
1494         }
1495
1496         return -1;
1497 }
1498
1499 static void
1500 set_metadata_flag (LLVMValueRef v, const char *flag_name)
1501 {
1502         LLVMValueRef md_arg;
1503         int md_kind;
1504
1505         md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1506         md_arg = LLVMMDString ("mono", 4);
1507         LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1508 }
1509
1510 static void
1511 set_invariant_load_flag (LLVMValueRef v)
1512 {
1513         LLVMValueRef md_arg;
1514         int md_kind;
1515         const char *flag_name;
1516
1517         // FIXME: Cache this
1518         flag_name = "invariant.load";
1519         md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1520         md_arg = LLVMMDString ("<index>", strlen ("<index>"));
1521         LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1522 }
1523
1524 /*
1525  * emit_call:
1526  *
1527  *   Emit an LLVM call or invoke instruction depending on whenever the call is inside
1528  * a try region.
1529  */
1530 static LLVMValueRef
1531 emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LLVMValueRef callee, LLVMValueRef *args, int pindex)
1532 {
1533         MonoCompile *cfg = ctx->cfg;
1534         LLVMValueRef lcall;
1535         LLVMBuilderRef builder = *builder_ref;
1536         int clause_index;
1537
1538         clause_index = get_handler_clause (cfg, bb);
1539
1540         if (clause_index != -1) {
1541                 MonoMethodHeader *header = cfg->header;
1542                 MonoExceptionClause *ec = &header->clauses [clause_index];
1543                 MonoBasicBlock *tblock;
1544                 LLVMBasicBlockRef ex_bb, noex_bb;
1545
1546                 /*
1547                  * Have to use an invoke instead of a call, branching to the
1548                  * handler bblock of the clause containing this bblock.
1549                  */
1550
1551                 g_assert (ec->flags == MONO_EXCEPTION_CLAUSE_NONE || ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY);
1552
1553                 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
1554                 g_assert (tblock);
1555
1556                 ctx->bblocks [tblock->block_num].invoke_target = TRUE;
1557
1558                 ex_bb = get_bb (ctx, tblock);
1559
1560                 noex_bb = gen_bb (ctx, "NOEX_BB");
1561
1562                 /* Use an invoke */
1563                 lcall = LLVMBuildInvoke (builder, callee, args, pindex, noex_bb, ex_bb, "");
1564
1565                 builder = ctx->builder = create_builder (ctx);
1566                 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1567
1568                 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1569         } else {
1570                 lcall = LLVMBuildCall (builder, callee, args, pindex, "");
1571                 ctx->builder = builder;
1572         }
1573
1574         *builder_ref = ctx->builder;
1575
1576         return lcall;
1577 }
1578
1579 static LLVMValueRef
1580 emit_load_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting, BarrierKind barrier)
1581 {
1582         const char *intrins_name;
1583         LLVMValueRef args [16], res;
1584         LLVMTypeRef addr_type;
1585
1586         if (is_faulting && bb->region != -1) {
1587                 LLVMAtomicOrdering ordering;
1588
1589                 switch (barrier) {
1590                 case LLVM_BARRIER_NONE:
1591                         ordering = LLVMAtomicOrderingNotAtomic;
1592                         break;
1593                 case LLVM_BARRIER_ACQ:
1594                         ordering = LLVMAtomicOrderingAcquire;
1595                         break;
1596                 case LLVM_BARRIER_SEQ:
1597                         ordering = LLVMAtomicOrderingSequentiallyConsistent;
1598                         break;
1599                 default:
1600                         g_assert_not_reached ();
1601                         break;
1602                 }
1603
1604                 /*
1605                  * We handle loads which can fault by calling a mono specific intrinsic
1606                  * using an invoke, so they are handled properly inside try blocks.
1607                  * We can't use this outside clauses, since LLVM optimizes intrinsics which
1608                  * are marked with IntrReadArgMem.
1609                  */
1610                 switch (size) {
1611                 case 1:
1612                         intrins_name = "llvm.mono.load.i8.p0i8";
1613                         break;
1614                 case 2:
1615                         intrins_name = "llvm.mono.load.i16.p0i16";
1616                         break;
1617                 case 4:
1618                         intrins_name = "llvm.mono.load.i32.p0i32";
1619                         break;
1620                 case 8:
1621                         intrins_name = "llvm.mono.load.i64.p0i64";
1622                         break;
1623                 default:
1624                         g_assert_not_reached ();
1625                 }
1626
1627                 addr_type = LLVMTypeOf (addr);
1628                 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0) || addr_type == LLVMPointerType (LLVMFloatType (), 0))
1629                         addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1630
1631                 args [0] = addr;
1632                 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1633                 args [2] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1634                 args [3] = LLVMConstInt (LLVMInt32Type (), ordering, FALSE);
1635                 res = emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 4);
1636
1637                 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0))
1638                         res = LLVMBuildBitCast (*builder_ref, res, LLVMDoubleType (), "");
1639                 else if (addr_type == LLVMPointerType (LLVMFloatType (), 0))
1640                         res = LLVMBuildBitCast (*builder_ref, res, LLVMFloatType (), "");
1641                 
1642                 return res;
1643         } else {
1644                 LLVMValueRef res;
1645
1646                 /* 
1647                  * We emit volatile loads for loads which can fault, because otherwise
1648                  * LLVM will generate invalid code when encountering a load from a
1649                  * NULL address.
1650                  */
1651                  res = mono_llvm_build_load (*builder_ref, addr, name, is_faulting, barrier);
1652
1653                  /* Mark it with a custom metadata */
1654                  /*
1655                  if (is_faulting)
1656                          set_metadata_flag (res, "mono.faulting.load");
1657                  */
1658
1659                  return res;
1660         }
1661 }
1662
1663 static LLVMValueRef
1664 emit_load (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting)
1665 {
1666         return emit_load_general (ctx, bb, builder_ref, size, addr, name, is_faulting, LLVM_BARRIER_NONE);
1667 }
1668
1669 static void
1670 emit_store_general (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting, BarrierKind barrier)
1671 {
1672         const char *intrins_name;
1673         LLVMValueRef args [16];
1674
1675         if (is_faulting && bb->region != -1) {
1676                 LLVMAtomicOrdering ordering;
1677
1678                 switch (barrier) {
1679                 case LLVM_BARRIER_NONE:
1680                         ordering = LLVMAtomicOrderingNotAtomic;
1681                         break;
1682                 case LLVM_BARRIER_REL:
1683                         ordering = LLVMAtomicOrderingRelease;
1684                         break;
1685                 case LLVM_BARRIER_SEQ:
1686                         ordering = LLVMAtomicOrderingSequentiallyConsistent;
1687                         break;
1688                 default:
1689                         g_assert_not_reached ();
1690                         break;
1691                 }
1692
1693                 switch (size) {
1694                 case 1:
1695                         intrins_name = "llvm.mono.store.i8.p0i8";
1696                         break;
1697                 case 2:
1698                         intrins_name = "llvm.mono.store.i16.p0i16";
1699                         break;
1700                 case 4:
1701                         intrins_name = "llvm.mono.store.i32.p0i32";
1702                         break;
1703                 case 8:
1704                         intrins_name = "llvm.mono.store.i64.p0i64";
1705                         break;
1706                 default:
1707                         g_assert_not_reached ();
1708                 }
1709
1710                 if (LLVMTypeOf (value) == LLVMDoubleType () || LLVMTypeOf (value) == LLVMFloatType ()) {
1711                         value = LLVMBuildBitCast (*builder_ref, value, LLVMIntType (size * 8), "");
1712                         addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1713                 }
1714
1715                 args [0] = value;
1716                 args [1] = addr;
1717                 args [2] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1718                 args [3] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1719                 args [4] = LLVMConstInt (LLVMInt32Type (), ordering, FALSE);
1720                 emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 5);
1721         } else {
1722                 mono_llvm_build_store (*builder_ref, value, addr, is_faulting, barrier);
1723         }
1724 }
1725
1726 static void
1727 emit_store (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting)
1728 {
1729         emit_store_general (ctx, bb, builder_ref, size, value, addr, is_faulting, LLVM_BARRIER_NONE);
1730 }
1731
1732 /*
1733  * emit_cond_system_exception:
1734  *
1735  *   Emit code to throw the exception EXC_TYPE if the condition CMP is false.
1736  * Might set the ctx exception.
1737  */
1738 static void
1739 emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp)
1740 {
1741         LLVMBasicBlockRef ex_bb, noex_bb;
1742         LLVMBuilderRef builder;
1743         MonoClass *exc_class;
1744         LLVMValueRef args [2];
1745         
1746         ex_bb = gen_bb (ctx, "EX_BB");
1747         noex_bb = gen_bb (ctx, "NOEX_BB");
1748
1749         LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb);
1750
1751         exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type);
1752         g_assert (exc_class);
1753
1754         /* Emit exception throwing code */
1755         builder = create_builder (ctx);
1756         LLVMPositionBuilderAtEnd (builder, ex_bb);
1757
1758         if (!ctx->lmodule->throw_corlib_exception) {
1759                 LLVMValueRef callee;
1760                 LLVMTypeRef sig;
1761                 const char *icall_name;
1762
1763                 MonoMethodSignature *throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 2);
1764                 throw_sig->ret = &mono_get_void_class ()->byval_arg;
1765                 throw_sig->params [0] = &mono_get_int32_class ()->byval_arg;
1766                 icall_name = "llvm_throw_corlib_exception_abs_trampoline";
1767                 /* This will become i8* */
1768                 throw_sig->params [1] = &mono_get_byte_class ()->this_arg;
1769                 sig = sig_to_llvm_sig (ctx, throw_sig);
1770
1771                 if (ctx->cfg->compile_aot) {
1772                         callee = get_plt_entry (ctx, sig, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
1773                 } else {
1774                         callee = LLVMAddFunction (ctx->module, "llvm_throw_corlib_exception_trampoline", sig_to_llvm_sig (ctx, throw_sig));
1775
1776                         /*
1777                          * Differences between the LLVM/non-LLVM throw corlib exception trampoline:
1778                          * - On x86, LLVM generated code doesn't push the arguments
1779                          * - The trampoline takes the throw address as an arguments, not a pc offset.
1780                          */
1781                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (ctx->cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
1782                 }
1783
1784                 mono_memory_barrier ();
1785                 ctx->lmodule->throw_corlib_exception = callee;
1786         }
1787
1788         if (IS_TARGET_X86 || IS_TARGET_AMD64)
1789                 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token - MONO_TOKEN_TYPE_DEF, FALSE);
1790         else
1791                 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token, FALSE);
1792
1793         /*
1794          * The LLVM mono branch contains changes so a block address can be passed as an
1795          * argument to a call.
1796          */
1797         args [1] = LLVMBlockAddress (ctx->lmethod, ex_bb);
1798         emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1799
1800         LLVMBuildUnreachable (builder);
1801
1802         ctx->builder = create_builder (ctx);
1803         LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1804
1805         ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1806
1807         ctx->ex_index ++;
1808         return;
1809 }
1810
1811 /*
1812  * emit_args_to_vtype:
1813  *
1814  *   Emit code to store the vtype in the arguments args to the address ADDRESS.
1815  */
1816 static void
1817 emit_args_to_vtype (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *args)
1818 {
1819         int j, size, nslots;
1820
1821         size = get_vtype_size (t);
1822
1823         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1824                 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1825         }
1826
1827         if (ainfo->storage == LLVMArgAsFpArgs)
1828                 nslots = ainfo->nslots;
1829         else
1830                 nslots = 2;
1831
1832         for (j = 0; j < nslots; ++j) {
1833                 LLVMValueRef index [2], addr, daddr;
1834                 int part_size = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1835                 LLVMTypeRef part_type;
1836
1837                 if (ainfo->pair_storage [j] == LLVMArgNone)
1838                         continue;
1839
1840                 switch (ainfo->pair_storage [j]) {
1841                 case LLVMArgInIReg: {
1842                         part_type = LLVMIntType (part_size * 8);
1843                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1844                                 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1845                                 addr = LLVMBuildGEP (builder, address, index, 1, "");
1846                         } else {
1847                                 daddr = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (IntPtrType (), 0), "");
1848                                 index [0] = LLVMConstInt (LLVMInt32Type (), j, FALSE);
1849                                 addr = LLVMBuildGEP (builder, daddr, index, 1, "");
1850                         }
1851                         LLVMBuildStore (builder, convert (ctx, args [j], part_type), LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (part_type, 0), ""));
1852                         break;
1853                 }
1854                 case LLVMArgInFPReg: {
1855                         LLVMTypeRef arg_type;
1856
1857                         if (ainfo->esize == 8)
1858                                 arg_type = LLVMDoubleType ();
1859                         else
1860                                 arg_type = LLVMFloatType ();
1861
1862                         index [0] = LLVMConstInt (LLVMInt32Type (), j, FALSE);
1863                         daddr = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (arg_type, 0), "");
1864                         addr = LLVMBuildGEP (builder, daddr, index, 1, "");
1865                         LLVMBuildStore (builder, args [j], addr);
1866                         break;
1867                 }
1868                 case LLVMArgNone:
1869                         break;
1870                 default:
1871                         g_assert_not_reached ();
1872                 }
1873
1874                 size -= sizeof (gpointer);
1875         }
1876 }
1877
1878 /*
1879  * emit_vtype_to_args:
1880  *
1881  *   Emit code to load a vtype at address ADDRESS into scalar arguments. Store the arguments
1882  * into ARGS, and the number of arguments into NARGS.
1883  */
1884 static void
1885 emit_vtype_to_args (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *args, guint32 *nargs)
1886 {
1887         int pindex = 0;
1888         int j, size, nslots;
1889         LLVMTypeRef arg_type;
1890
1891         size = get_vtype_size (t);
1892
1893         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t)))
1894                 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1895
1896         if (ainfo->storage == LLVMArgAsFpArgs)
1897                 nslots = ainfo->nslots;
1898         else
1899                 nslots = 2;
1900         for (j = 0; j < nslots; ++j) {
1901                 LLVMValueRef index [2], addr, daddr;
1902                 int partsize = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1903
1904                 if (ainfo->pair_storage [j] == LLVMArgNone)
1905                         continue;
1906
1907                 switch (ainfo->pair_storage [j]) {
1908                 case LLVMArgInIReg:
1909                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1910                                 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1911                                 addr = LLVMBuildGEP (builder, address, index, 1, "");
1912                         } else {
1913                                 daddr = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (IntPtrType (), 0), "");
1914                                 index [0] = LLVMConstInt (LLVMInt32Type (), j, FALSE);
1915                                 addr = LLVMBuildGEP (builder, daddr, index, 1, "");
1916                         }
1917                         args [pindex ++] = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (LLVMIntType (partsize * 8), 0), ""), ""), IntPtrType ());
1918                         break;
1919                 case LLVMArgInFPReg:
1920                         if (ainfo->esize == 8)
1921                                 arg_type = LLVMDoubleType ();
1922                         else
1923                                 arg_type = LLVMFloatType ();
1924                         daddr = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (arg_type, 0), "");
1925                         index [0] = LLVMConstInt (LLVMInt32Type (), j, FALSE);
1926                         addr = LLVMBuildGEP (builder, daddr, index, 1, "");
1927                         args [pindex ++] = LLVMBuildLoad (builder, addr, "");
1928                         break;
1929                 case LLVMArgNone:
1930                         break;
1931                 default:
1932                         g_assert_not_reached ();
1933                 }
1934                 size -= sizeof (gpointer);
1935         }
1936
1937         *nargs = pindex;
1938 }
1939
1940 static LLVMValueRef
1941 build_alloca_llvm_type (EmitContext *ctx, LLVMTypeRef t, int align)
1942 {
1943         /*
1944          * Have to place all alloca's at the end of the entry bb, since otherwise they would
1945          * get executed every time control reaches them.
1946          */
1947         LLVMPositionBuilder (ctx->alloca_builder, get_bb (ctx, ctx->cfg->bb_entry), ctx->last_alloca);
1948
1949         ctx->last_alloca = mono_llvm_build_alloca (ctx->alloca_builder, t, NULL, align, "");
1950         return ctx->last_alloca;
1951 }
1952
1953 static LLVMValueRef
1954 build_alloca (EmitContext *ctx, MonoType *t)
1955 {
1956         MonoClass *k = mono_class_from_mono_type (t);
1957         int align;
1958
1959         if (MONO_CLASS_IS_SIMD (ctx->cfg, k))
1960                 align = 16;
1961         else
1962                 align = mono_class_min_align (k);
1963
1964         /* Sometimes align is not a power of 2 */
1965         while (mono_is_power_of_two (align) == -1)
1966                 align ++;
1967
1968         return build_alloca_llvm_type (ctx, type_to_llvm_type (ctx, t), align);
1969 }
1970
1971 /*
1972  * Put the global into the 'llvm.used' array to prevent it from being optimized away.
1973  */
1974 static void
1975 mark_as_used (MonoLLVMModule *lmodule, LLVMValueRef global)
1976 {
1977         if (!lmodule->used)
1978                 lmodule->used = g_ptr_array_sized_new (16);
1979         g_ptr_array_add (lmodule->used, global);
1980 }
1981
1982 static void
1983 emit_llvm_used (MonoLLVMModule *lmodule)
1984 {
1985         LLVMModuleRef module = lmodule->module;
1986         LLVMTypeRef used_type;
1987         LLVMValueRef used, *used_elem;
1988         int i;
1989                 
1990         if (!lmodule->used)
1991                 return;
1992
1993         used_type = LLVMArrayType (LLVMPointerType (LLVMInt8Type (), 0), lmodule->used->len);
1994         used = LLVMAddGlobal (module, used_type, "llvm.used");
1995         used_elem = g_new0 (LLVMValueRef, lmodule->used->len);
1996         for (i = 0; i < lmodule->used->len; ++i)
1997                 used_elem [i] = LLVMConstBitCast (g_ptr_array_index (lmodule->used, i), LLVMPointerType (LLVMInt8Type (), 0));
1998         LLVMSetInitializer (used, LLVMConstArray (LLVMPointerType (LLVMInt8Type (), 0), used_elem, lmodule->used->len));
1999         LLVMSetLinkage (used, LLVMAppendingLinkage);
2000         LLVMSetSection (used, "llvm.metadata");
2001 }
2002
2003 static void
2004 emit_div_check (EmitContext *ctx, LLVMBuilderRef builder, MonoBasicBlock *bb, MonoInst *ins, LLVMValueRef lhs, LLVMValueRef rhs)
2005 {
2006         gboolean need_div_check = FALSE;
2007
2008 #ifdef MONO_ARCH_NEED_DIV_CHECK
2009         need_div_check = TRUE;
2010 #endif
2011         if (bb->region)
2012                 /* LLVM doesn't know that these can throw an exception since they are not called through an intrinsic */
2013                 need_div_check = TRUE;
2014
2015         if (!need_div_check)
2016                 return;
2017
2018         switch (ins->opcode) {
2019         case OP_IDIV:
2020         case OP_LDIV:
2021         case OP_IREM:
2022         case OP_LREM:
2023         case OP_IDIV_UN:
2024         case OP_LDIV_UN:
2025         case OP_IREM_UN:
2026         case OP_LREM_UN:
2027         case OP_IDIV_IMM:
2028         case OP_LDIV_IMM:
2029         case OP_IREM_IMM:
2030         case OP_LREM_IMM:
2031         case OP_IDIV_UN_IMM:
2032         case OP_LDIV_UN_IMM:
2033         case OP_IREM_UN_IMM:
2034         case OP_LREM_UN_IMM: {
2035                 LLVMValueRef cmp;
2036                 gboolean is_signed = (ins->opcode == OP_IDIV || ins->opcode == OP_LDIV || ins->opcode == OP_IREM || ins->opcode == OP_LREM ||
2037                                                           ins->opcode == OP_IDIV_IMM || ins->opcode == OP_LDIV_IMM || ins->opcode == OP_IREM_IMM || ins->opcode == OP_LREM_IMM);
2038
2039                 cmp = LLVMBuildICmp (builder, LLVMIntEQ, rhs, LLVMConstInt (LLVMTypeOf (rhs), 0, FALSE), "");
2040                 emit_cond_system_exception (ctx, bb, "DivideByZeroException", cmp);
2041                 CHECK_FAILURE (ctx);
2042                 builder = ctx->builder;
2043
2044                 /* b == -1 && a == 0x80000000 */
2045                 if (is_signed) {
2046                         LLVMValueRef c = (LLVMTypeOf (lhs) == LLVMInt32Type ()) ? LLVMConstInt (LLVMTypeOf (lhs), 0x80000000, FALSE) : LLVMConstInt (LLVMTypeOf (lhs), 0x8000000000000000LL, FALSE);
2047                         LLVMValueRef cond1 = LLVMBuildICmp (builder, LLVMIntEQ, rhs, LLVMConstInt (LLVMTypeOf (rhs), -1, FALSE), "");
2048                         LLVMValueRef cond2 = LLVMBuildICmp (builder, LLVMIntEQ, lhs, c, "");
2049
2050                         cmp = LLVMBuildICmp (builder, LLVMIntEQ, LLVMBuildAnd (builder, cond1, cond2, ""), LLVMConstInt (LLVMInt1Type (), 1, FALSE), "");
2051                         emit_cond_system_exception (ctx, bb, "OverflowException", cmp);
2052                         CHECK_FAILURE (ctx);
2053                         builder = ctx->builder;
2054                 }
2055                 break;
2056         }
2057         default:
2058                 break;
2059         }
2060
2061  FAILURE:
2062         return;
2063 }
2064
2065 /*
2066  * emit_entry_bb:
2067  *
2068  *   Emit code to load/convert arguments.
2069  */
2070 static void
2071 emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder)
2072 {
2073         int i, j, pindex;
2074         MonoCompile *cfg = ctx->cfg;
2075         MonoMethodSignature *sig = ctx->sig;
2076         LLVMCallInfo *linfo = ctx->linfo;
2077         MonoBasicBlock *bb;
2078
2079         ctx->alloca_builder = create_builder (ctx);
2080
2081         /*
2082          * Handle indirect/volatile variables by allocating memory for them
2083          * using 'alloca', and storing their address in a temporary.
2084          */
2085         for (i = 0; i < cfg->num_varinfo; ++i) {
2086                 MonoInst *var = cfg->varinfo [i];
2087                 LLVMTypeRef vtype;
2088
2089                 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || mini_type_is_vtype (var->inst_vtype)) {
2090                         vtype = type_to_llvm_type (ctx, var->inst_vtype);
2091                         CHECK_FAILURE (ctx);
2092                         /* Could be already created by an OP_VPHI */
2093                         if (!ctx->addresses [var->dreg])
2094                                 ctx->addresses [var->dreg] = build_alloca (ctx, var->inst_vtype);
2095                         ctx->vreg_cli_types [var->dreg] = var->inst_vtype;
2096                 }
2097         }
2098
2099         for (i = 0; i < sig->param_count; ++i) {
2100                 LLVMArgInfo *ainfo = &linfo->args [i + sig->hasthis];
2101                 int reg = cfg->args [i + sig->hasthis]->dreg;
2102
2103                 switch (ainfo->storage) {
2104                 case LLVMArgVtypeInReg:
2105                 case LLVMArgAsFpArgs: {
2106                         LLVMValueRef args [8];
2107                         int j;
2108
2109                         /* The argument is received as a set of int/fp arguments, store them into the real argument */
2110                         memset (args, 0, sizeof (args));
2111                         pindex = ctx->pindexes [i];
2112                         if (ainfo->storage == LLVMArgVtypeInReg) {
2113                                 args [0] = LLVMGetParam (ctx->lmethod, pindex);
2114                                 if (ainfo->pair_storage [1] != LLVMArgNone)
2115                                         args [1] = LLVMGetParam (ctx->lmethod, pindex + 1);
2116                         } else {
2117                                 g_assert (ainfo->nslots <= 8);
2118                                 for (j = 0; j < ainfo->nslots; ++j)
2119                                         args [j] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i] + j);
2120                         }
2121                         ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
2122
2123                         emit_args_to_vtype (ctx, builder, sig->params [i], ctx->addresses [reg], ainfo, args);
2124
2125                         if (ainfo->storage == LLVMArgVtypeInReg && MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
2126                                 /* Treat these as normal values */
2127                                 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
2128                         }
2129                         break;
2130                 }
2131                 case LLVMArgVtypeByVal: {
2132                         ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
2133
2134                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
2135                                 /* Treat these as normal values */
2136                                 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
2137                         }
2138                         break;
2139                 }
2140                 case LLVMArgVtypeByRef: {
2141                         /* The argument is passed by ref */
2142                         ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
2143                         break;
2144                 }
2145                 case LLVMArgAsIArgs: {
2146                         LLVMValueRef arg = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
2147
2148                         ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
2149
2150                         /* The argument is received as an array of ints, store it into the real argument */
2151                         LLVMBuildStore (ctx->builder, arg, convert (ctx, ctx->addresses [reg], LLVMPointerType (LLVMTypeOf (arg), 0)));
2152                         break;
2153                 }
2154                 case LLVMArgVtypeAsScalar:
2155                         g_assert_not_reached ();
2156                         break;
2157                 default:
2158                         ctx->values [reg] = convert_full (ctx, ctx->values [reg], llvm_type_to_stack_type (cfg, type_to_llvm_type (ctx, sig->params [i])), type_is_unsigned (ctx, sig->params [i]));
2159                         break;
2160                 }
2161         }
2162
2163         if (cfg->vret_addr)
2164                 emit_volatile_store (ctx, cfg->vret_addr->dreg);
2165         if (sig->hasthis)
2166                 emit_volatile_store (ctx, cfg->args [0]->dreg);
2167         for (i = 0; i < sig->param_count; ++i)
2168                 if (!mini_type_is_vtype (sig->params [i]))
2169                         emit_volatile_store (ctx, cfg->args [i + sig->hasthis]->dreg);
2170
2171         if (sig->hasthis && !cfg->rgctx_var && cfg->gshared) {
2172                 LLVMValueRef this_alloc;
2173
2174                 /*
2175                  * The exception handling code needs the location where the this argument was
2176                  * stored for gshared methods. We create a separate alloca to hold it, and mark it
2177                  * with the "mono.this" custom metadata to tell llvm that it needs to save its
2178                  * location into the LSDA.
2179                  */
2180                 this_alloc = mono_llvm_build_alloca (builder, ThisType (), LLVMConstInt (LLVMInt32Type (), 1, FALSE), 0, "");
2181                 /* This volatile store will keep the alloca alive */
2182                 mono_llvm_build_store (builder, ctx->values [cfg->args [0]->dreg], this_alloc, TRUE, LLVM_BARRIER_NONE);
2183
2184                 set_metadata_flag (this_alloc, "mono.this");
2185         }
2186
2187         if (cfg->rgctx_var) {
2188                 LLVMValueRef rgctx_alloc, store;
2189
2190                 /*
2191                  * We handle the rgctx arg similarly to the this pointer.
2192                  */
2193                 g_assert (ctx->addresses [cfg->rgctx_var->dreg]);
2194                 rgctx_alloc = ctx->addresses [cfg->rgctx_var->dreg];
2195                 /* This volatile store will keep the alloca alive */
2196                 store = mono_llvm_build_store (builder, convert (ctx, ctx->rgctx_arg, IntPtrType ()), rgctx_alloc, TRUE, LLVM_BARRIER_NONE);
2197
2198                 set_metadata_flag (rgctx_alloc, "mono.this");
2199         }
2200
2201         /* Compute nesting between clauses */
2202         ctx->nested_in = mono_mempool_alloc0 (cfg->mempool, sizeof (GSList*) * cfg->header->num_clauses);
2203         for (i = 0; i < cfg->header->num_clauses; ++i) {
2204                 for (j = 0; j < cfg->header->num_clauses; ++j) {
2205                         MonoExceptionClause *clause1 = &cfg->header->clauses [i];
2206                         MonoExceptionClause *clause2 = &cfg->header->clauses [j];
2207
2208                         if (i != j && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
2209                                 ctx->nested_in [i] = g_slist_prepend_mempool (cfg->mempool, ctx->nested_in [i], GINT_TO_POINTER (j));
2210                 }
2211         }
2212
2213         /*
2214          * For finally clauses, create an indicator variable telling OP_ENDFINALLY whenever
2215          * it needs to continue normally, or return back to the exception handling system.
2216          */
2217         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2218                 int clause_index;
2219                 char name [128];
2220
2221                 if (!(bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER)))
2222                         continue;
2223
2224                 clause_index = MONO_REGION_CLAUSE_INDEX (bb->region);
2225                 g_hash_table_insert (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)), bb);
2226                 g_hash_table_insert (ctx->clause_to_handler, GINT_TO_POINTER (clause_index), bb);
2227
2228                 if (bb->in_scount == 0) {
2229                         LLVMValueRef val;
2230
2231                         sprintf (name, "finally_ind_bb%d", bb->block_num);
2232                         val = LLVMBuildAlloca (builder, LLVMInt32Type (), name);
2233                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), val);
2234
2235                         ctx->bblocks [bb->block_num].finally_ind = val;
2236                 } else {
2237                         /* Create a variable to hold the exception var */
2238                         if (!ctx->ex_var)
2239                                 ctx->ex_var = LLVMBuildAlloca (builder, ObjRefType (), "exvar");
2240                 }
2241
2242                 /*
2243                  * Create a new bblock which CALL_HANDLER/landing pads can branch to, because branching to the
2244                  * LLVM bblock containing a landing pad causes problems for the
2245                  * LLVM optimizer passes.
2246                  */
2247                 sprintf (name, "BB_%d_CALL_HANDLER_TARGET", bb->block_num);
2248                 ctx->bblocks [bb->block_num].call_handler_target_bb = LLVMAppendBasicBlock (ctx->lmethod, name);
2249         }
2250
2251  FAILURE:
2252         ;
2253 }
2254
2255 /* Have to export this for AOT */
2256 void
2257 mono_personality (void)
2258 {
2259         /* Not used */
2260         g_assert_not_reached ();
2261 }
2262
2263 static void
2264 process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, MonoInst *ins)
2265 {
2266         MonoCompile *cfg = ctx->cfg;
2267         LLVMModuleRef module = ctx->module;
2268         LLVMValueRef *values = ctx->values;
2269         LLVMValueRef *addresses = ctx->addresses;
2270         MonoCallInst *call = (MonoCallInst*)ins;
2271         MonoMethodSignature *sig = call->signature;
2272         LLVMValueRef callee = NULL, lcall;
2273         LLVMValueRef *args;
2274         LLVMCallInfo *cinfo;
2275         GSList *l;
2276         int i, len, nargs;
2277         gboolean vretaddr;
2278         LLVMTypeRef llvm_sig;
2279         gpointer target;
2280         gboolean virtual, calli;
2281         LLVMBuilderRef builder = *builder_ref;
2282         LLVMSigInfo sinfo;
2283
2284         if (call->signature->call_convention != MONO_CALL_DEFAULT)
2285                 LLVM_FAILURE (ctx, "non-default callconv");
2286
2287         cinfo = call->cinfo;
2288         if (call->rgctx_arg_reg)
2289                 cinfo->rgctx_arg = TRUE;
2290         if (call->imt_arg_reg)
2291                 cinfo->imt_arg = TRUE;
2292
2293         vretaddr = cinfo && (cinfo->ret.storage == LLVMArgVtypeRetAddr || cinfo->ret.storage == LLVMArgVtypeByRef);
2294
2295         llvm_sig = sig_to_llvm_sig_full (ctx, sig, cinfo, &sinfo);
2296         CHECK_FAILURE (ctx);
2297
2298         virtual = (ins->opcode == OP_VOIDCALL_MEMBASE || ins->opcode == OP_CALL_MEMBASE || ins->opcode == OP_VCALL_MEMBASE || ins->opcode == OP_LCALL_MEMBASE || ins->opcode == OP_FCALL_MEMBASE || ins->opcode == OP_RCALL_MEMBASE);
2299         calli = !call->fptr_is_patch && (ins->opcode == OP_VOIDCALL_REG || ins->opcode == OP_CALL_REG || ins->opcode == OP_VCALL_REG || ins->opcode == OP_LCALL_REG || ins->opcode == OP_FCALL_REG || ins->opcode == OP_RCALL_REG);
2300
2301         /* FIXME: Avoid creating duplicate methods */
2302
2303         if (ins->flags & MONO_INST_HAS_METHOD) {
2304                 if (virtual) {
2305                         callee = NULL;
2306                 } else {
2307                         if (cfg->compile_aot) {
2308                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_METHOD, call->method);
2309                                 if (!callee)
2310                                         LLVM_FAILURE (ctx, "can't encode patch");
2311                         } else {
2312                                 callee = LLVMAddFunction (module, "", llvm_sig);
2313  
2314                                 target =
2315                                         mono_create_jit_trampoline_in_domain (mono_domain_get (),
2316                                                                                                                   call->method);
2317                                 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2318                         }
2319                 }
2320
2321                 if (call->method && strstr (call->method->klass->name, "AsyncVoidMethodBuilder"))
2322                         /* LLVM miscompiles async methods */
2323                         LLVM_FAILURE (ctx, "#13734");
2324         } else if (calli) {
2325         } else {
2326                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
2327
2328                 if (info) {
2329                         /*
2330                           MonoJumpInfo ji;
2331
2332                           memset (&ji, 0, sizeof (ji));
2333                           ji.type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
2334                           ji.data.target = info->name;
2335
2336                           target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
2337                         */
2338                         if (cfg->compile_aot) {
2339                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_INTERNAL_METHOD, (char*)info->name);
2340                                 if (!callee)
2341                                         LLVM_FAILURE (ctx, "can't encode patch");
2342                         } else {
2343                                 callee = LLVMAddFunction (module, "", llvm_sig);
2344                                 target = (gpointer)mono_icall_get_wrapper (info);
2345                                 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2346                         }
2347                 } else {
2348                         if (cfg->compile_aot) {
2349                                 callee = NULL;
2350                                 if (cfg->abs_patches) {
2351                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2352                                         if (abs_ji) {
2353                                                 callee = get_plt_entry (ctx, llvm_sig, abs_ji->type, abs_ji->data.target);
2354                                                 if (!callee)
2355                                                         LLVM_FAILURE (ctx, "can't encode patch");
2356                                         }
2357                                 }
2358                                 if (!callee)
2359                                         LLVM_FAILURE (ctx, "aot");
2360                         } else {
2361                                 callee = LLVMAddFunction (module, "", llvm_sig);
2362                                 target = NULL;
2363                                 if (cfg->abs_patches) {
2364                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2365                                         if (abs_ji) {
2366                                                 /*
2367                                                  * FIXME: Some trampolines might have
2368                                                  * their own calling convention on some platforms.
2369                                                  */
2370 #ifndef TARGET_AMD64
2371                                                 if (abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER || abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER_V4 ||
2372                                                                 abs_ji->type == MONO_PATCH_INFO_MONITOR_EXIT)
2373                                                         LLVM_FAILURE (ctx, "trampoline with own cconv");
2374 #endif
2375                                                 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, abs_ji, FALSE);
2376                                                 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2377                                         }
2378                                 }
2379                                 if (!target)
2380                                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, (gpointer)call->fptr);
2381                         }
2382                 }
2383         }
2384
2385         if (virtual) {
2386                 int size = sizeof (gpointer);
2387                 LLVMValueRef index;
2388
2389                 g_assert (ins->inst_offset % size == 0);
2390                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
2391
2392                 callee = convert (ctx, LLVMBuildLoad (builder, LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMPointerType (IntPtrType (), 0), 0)), &index, 1, ""), ""), LLVMPointerType (llvm_sig, 0));
2393         } else if (calli) {
2394                 callee = convert (ctx, values [ins->sreg1], LLVMPointerType (llvm_sig, 0));
2395         } else {
2396                 if (ins->flags & MONO_INST_HAS_METHOD) {
2397                 }
2398         }
2399
2400         /* 
2401          * Collect and convert arguments
2402          */
2403         nargs = (sig->param_count * 16) + sig->hasthis + vretaddr + call->rgctx_reg + call->imt_arg_reg;
2404         len = sizeof (LLVMValueRef) * nargs;
2405         args = alloca (len);
2406         memset (args, 0, len);
2407         l = call->out_ireg_args;
2408
2409         if (call->rgctx_arg_reg) {
2410                 g_assert (values [call->rgctx_arg_reg]);
2411                 g_assert (sinfo.rgctx_arg_pindex < nargs);
2412                 /*
2413                  * On ARM, the imt/rgctx argument is passed in a caller save register, but some of our trampolines etc. clobber it, leading to
2414                  * problems is LLVM moves the arg assignment earlier. To work around this, save the argument into a stack slot and load
2415                  * it using a volatile load.
2416                  */
2417 #ifdef TARGET_ARM
2418                 if (!ctx->imt_rgctx_loc)
2419                         ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2420                 LLVMBuildStore (builder, convert (ctx, ctx->values [call->rgctx_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2421                 args [sinfo.rgctx_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE, LLVM_BARRIER_NONE);
2422 #else
2423                 args [sinfo.rgctx_arg_pindex] = convert (ctx, values [call->rgctx_arg_reg], ctx->lmodule->ptr_type);
2424 #endif
2425         }
2426         if (call->imt_arg_reg) {
2427                 g_assert (values [call->imt_arg_reg]);
2428                 g_assert (sinfo.imt_arg_pindex < nargs);
2429 #ifdef TARGET_ARM
2430                 if (!ctx->imt_rgctx_loc)
2431                         ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2432                 LLVMBuildStore (builder, convert (ctx, ctx->values [call->imt_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2433                 args [sinfo.imt_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE, LLVM_BARRIER_NONE);
2434 #else
2435                 args [sinfo.imt_arg_pindex] = convert (ctx, values [call->imt_arg_reg], ctx->lmodule->ptr_type);
2436 #endif
2437         }
2438         if (vretaddr) {
2439                 if (!addresses [call->inst.dreg])
2440                         addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2441                 g_assert (sinfo.vret_arg_pindex < nargs);
2442                 if (cinfo && cinfo->ret.storage == LLVMArgVtypeByRef)
2443                         args [sinfo.vret_arg_pindex] = addresses [call->inst.dreg];
2444                 else
2445                         args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2446         }
2447
2448         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2449                 guint32 regpair;
2450                 int reg, pindex;
2451                 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i] : NULL;
2452
2453                 if (sig->hasthis) {
2454                         if (i == 0)
2455                                 pindex = sinfo.this_arg_pindex;
2456                         else
2457                                 pindex = sinfo.pindexes [i - 1];
2458                 } else {
2459                         pindex = sinfo.pindexes [i];
2460                 }
2461
2462                 regpair = (guint32)(gssize)(l->data);
2463                 reg = regpair & 0xffffff;
2464                 args [pindex] = values [reg];
2465                 switch (ainfo->storage) {
2466                 case LLVMArgVtypeInReg:
2467                 case LLVMArgAsFpArgs: {
2468                         guint32 nargs;
2469
2470                         g_assert (addresses [reg]);
2471                         emit_vtype_to_args (ctx, builder, sig->params [i - sig->hasthis], addresses [reg], ainfo, args + pindex, &nargs);
2472                         pindex += nargs;
2473
2474                         // FIXME: alignment
2475                         // FIXME: Get rid of the VMOVE
2476                         break;
2477                 }
2478                 case LLVMArgVtypeByVal:
2479                         g_assert (addresses [reg]);
2480                         args [pindex] = addresses [reg];
2481                         break;
2482                 case LLVMArgVtypeByRef:
2483                         g_assert (addresses [reg]);
2484                         args [pindex] = addresses [reg];
2485                         break;
2486                 case LLVMArgAsIArgs:
2487                         g_assert (addresses [reg]);
2488                         args [pindex] = LLVMBuildLoad (ctx->builder, convert (ctx, addresses [reg], LLVMPointerType (LLVMArrayType (IntPtrType (), ainfo->nslots), 0)), "");
2489                         break;
2490                 case LLVMArgVtypeAsScalar:
2491                         g_assert_not_reached ();
2492                         break;
2493                 default:
2494                         g_assert (args [pindex]);
2495                         if (i == 0 && sig->hasthis)
2496                                 args [pindex] = convert (ctx, args [pindex], ThisType ());
2497                         else
2498                                 args [pindex] = convert (ctx, args [pindex], type_to_llvm_arg_type (ctx, sig->params [i - sig->hasthis]));
2499                         break;
2500                 }
2501                 g_assert (pindex <= nargs);
2502
2503                 l = l->next;
2504         }
2505
2506         // FIXME: Align call sites
2507
2508         /*
2509          * Emit the call
2510          */
2511
2512         lcall = emit_call (ctx, bb, &builder, callee, args, LLVMCountParamTypes (llvm_sig));
2513
2514         /*
2515          * Modify cconv and parameter attributes to pass rgctx/imt correctly.
2516          */
2517 #if defined(MONO_ARCH_IMT_REG) && defined(MONO_ARCH_RGCTX_REG)
2518         g_assert (MONO_ARCH_IMT_REG == MONO_ARCH_RGCTX_REG);
2519 #endif
2520         /* The two can't be used together, so use only one LLVM calling conv to pass them */
2521         g_assert (!(call->rgctx_arg_reg && call->imt_arg_reg));
2522         if (!sig->pinvoke)
2523                 LLVMSetInstructionCallConv (lcall, LLVMMono1CallConv);
2524
2525         if (cinfo && cinfo->ret.storage == LLVMArgVtypeByRef)
2526                 LLVMAddInstrAttribute (lcall, 1 + sinfo.vret_arg_pindex, LLVMStructRetAttribute);
2527         if (call->rgctx_arg_reg)
2528                 LLVMAddInstrAttribute (lcall, 1 + sinfo.rgctx_arg_pindex, LLVMInRegAttribute);
2529         if (call->imt_arg_reg)
2530                 LLVMAddInstrAttribute (lcall, 1 + sinfo.imt_arg_pindex, LLVMInRegAttribute);
2531
2532         /* Add byval attributes if needed */
2533         for (i = 0; i < sig->param_count; ++i) {
2534                 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i + sig->hasthis] : NULL;
2535
2536                 if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
2537                         LLVMAddInstrAttribute (lcall, 1 + sinfo.pindexes [i], LLVMByValAttribute);
2538                 }
2539         }
2540
2541         /*
2542          * Convert the result
2543          */
2544         if (cinfo) {
2545                 switch (cinfo->ret.storage) {
2546                 case LLVMArgVtypeInReg: {
2547                         LLVMValueRef regs [2];
2548
2549                         if (!addresses [ins->dreg])
2550                                 addresses [ins->dreg] = build_alloca (ctx, sig->ret);
2551
2552                         regs [0] = LLVMBuildExtractValue (builder, lcall, 0, "");
2553                         if (cinfo->ret.pair_storage [1] != LLVMArgNone)
2554                                 regs [1] = LLVMBuildExtractValue (builder, lcall, 1, "");
2555                         emit_args_to_vtype (ctx, builder, sig->ret, addresses [ins->dreg], &cinfo->ret, regs);
2556                         break;
2557                 }
2558                 case LLVMArgVtypeByVal:
2559                         if (!addresses [call->inst.dreg])
2560                                 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2561                         LLVMBuildStore (builder, lcall, addresses [call->inst.dreg]);
2562                         break;
2563                 case LLVMArgFpStruct:
2564                         if (!addresses [call->inst.dreg])
2565                                 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2566                         LLVMBuildStore (builder, lcall, convert_full (ctx, addresses [call->inst.dreg], LLVMPointerType (LLVMTypeOf (lcall), 0), FALSE));
2567                         break;
2568                 case LLVMArgVtypeAsScalar:
2569                         if (!addresses [call->inst.dreg])
2570                                 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2571                         LLVMBuildStore (builder, lcall, convert_full (ctx, addresses [call->inst.dreg], LLVMPointerType (LLVMTypeOf (lcall), 0), FALSE));
2572                         break;
2573                 default:
2574                         if (sig->ret->type != MONO_TYPE_VOID && !vretaddr)
2575                                 /* If the method returns an unsigned value, need to zext it */
2576                                 values [ins->dreg] = convert_full (ctx, lcall, llvm_type_to_stack_type (cfg, type_to_llvm_type (ctx, sig->ret)), type_is_unsigned (ctx, sig->ret));
2577                         break;
2578                 }
2579         } else {
2580                 if (sig->ret->type != MONO_TYPE_VOID && !vretaddr)
2581                         /* If the method returns an unsigned value, need to zext it */
2582                         values [ins->dreg] = convert_full (ctx, lcall, llvm_type_to_stack_type (cfg, type_to_llvm_type (ctx, sig->ret)), type_is_unsigned (ctx, sig->ret));
2583         }
2584
2585         if (vretaddr) {
2586                 if (!addresses [call->inst.dreg])
2587                         addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2588                 g_assert (sinfo.vret_arg_pindex < nargs);
2589                 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2590         }
2591
2592         *builder_ref = ctx->builder;
2593
2594         g_free (sinfo.pindexes);
2595         
2596         return;
2597  FAILURE:
2598         return;
2599 }
2600
2601 static void
2602 emit_handler_start (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef builder)
2603 {
2604         MonoCompile *cfg = ctx->cfg;
2605         LLVMValueRef *values = ctx->values;
2606         LLVMModuleRef module = ctx->module;
2607         BBInfo *bblocks = ctx->bblocks;
2608         LLVMTypeRef i8ptr;
2609         LLVMValueRef personality;
2610         LLVMValueRef landing_pad;
2611         LLVMBasicBlockRef target_bb;
2612         MonoInst *exvar;
2613         static gint32 mapping_inited;
2614         static int ti_generator;
2615         char ti_name [128];
2616         MonoClass **ti;
2617         LLVMValueRef type_info;
2618         int clause_index;
2619         GSList *l;
2620
2621         // <resultval> = landingpad <somety> personality <type> <pers_fn> <clause>+
2622
2623         if (cfg->compile_aot) {
2624                 /* Use a dummy personality function */
2625                 personality = LLVMGetNamedFunction (module, "mono_aot_personality");
2626                 g_assert (personality);
2627         } else {
2628                 personality = LLVMGetNamedFunction (module, "mono_personality");
2629                 if (InterlockedCompareExchange (&mapping_inited, 1, 0) == 0)
2630                         LLVMAddGlobalMapping (ctx->lmodule->ee, personality, mono_personality);
2631         }
2632
2633         i8ptr = LLVMPointerType (LLVMInt8Type (), 0);
2634
2635         clause_index = (mono_get_block_region_notry (cfg, bb->region) >> 8) - 1;
2636
2637         /*
2638          * Create the type info
2639          */
2640         sprintf (ti_name, "type_info_%d", ti_generator);
2641         ti_generator ++;
2642
2643         if (cfg->compile_aot) {
2644                 /* decode_eh_frame () in aot-runtime.c will decode this */
2645                 type_info = LLVMAddGlobal (module, LLVMInt32Type (), ti_name);
2646                 LLVMSetInitializer (type_info, LLVMConstInt (LLVMInt32Type (), clause_index, FALSE));
2647
2648                 /*
2649                  * These symbols are not really used, the clause_index is embedded into the EH tables generated by DwarfMonoException in LLVM.
2650                  */
2651                 LLVMSetLinkage (type_info, LLVMInternalLinkage);
2652         } else {
2653                 /*
2654                  * After the cfg mempool is freed, the type info will point to stale memory,
2655                  * but this is not a problem, since we decode it once in exception_cb during
2656                  * compilation.
2657                  */
2658                 ti = mono_mempool_alloc (cfg->mempool, sizeof (gint32));
2659                 *(gint32*)ti = clause_index;
2660
2661                 type_info = LLVMAddGlobal (module, i8ptr, ti_name);
2662
2663                 LLVMAddGlobalMapping (ctx->lmodule->ee, type_info, ti);
2664         }
2665
2666         {
2667                 LLVMTypeRef members [2], ret_type;
2668
2669                 members [0] = i8ptr;
2670                 members [1] = LLVMInt32Type ();
2671                 ret_type = LLVMStructType (members, 2, FALSE);
2672
2673                 landing_pad = LLVMBuildLandingPad (builder, ret_type, personality, 1, "");
2674                 LLVMAddClause (landing_pad, type_info);
2675
2676                 /* Store the exception into the exvar */
2677                 if (ctx->ex_var)
2678                         LLVMBuildStore (builder, convert (ctx, LLVMBuildExtractValue (builder, landing_pad, 0, "ex_obj"), ObjRefType ()), ctx->ex_var);
2679         }
2680
2681         /*
2682          * LLVM throw sites are associated with a one landing pad, and LLVM generated
2683          * code expects control to be transferred to this landing pad even in the
2684          * presence of nested clauses. The landing pad needs to branch to the landing
2685          * pads belonging to nested clauses based on the selector value returned by
2686          * the landing pad instruction, which is passed to the landing pad in a
2687          * register by the EH code.
2688          */
2689         target_bb = bblocks [bb->block_num].call_handler_target_bb;
2690         g_assert (target_bb);
2691
2692         /*
2693          * Branch to the correct landing pad
2694          */
2695         LLVMValueRef ex_selector = LLVMBuildExtractValue (builder, landing_pad, 1, "ex_selector");
2696         LLVMValueRef switch_ins = LLVMBuildSwitch (builder, ex_selector, target_bb, 0);
2697
2698         for (l = ctx->nested_in [clause_index]; l; l = l->next) {
2699                 int nesting_clause_index = GPOINTER_TO_INT (l->data);
2700                 MonoBasicBlock *handler_bb;
2701
2702                 handler_bb = g_hash_table_lookup (ctx->clause_to_handler, GINT_TO_POINTER (nesting_clause_index));
2703                 g_assert (handler_bb);
2704
2705                 g_assert (ctx->bblocks [handler_bb->block_num].call_handler_target_bb);
2706                 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), nesting_clause_index, FALSE), ctx->bblocks [handler_bb->block_num].call_handler_target_bb);
2707         }
2708
2709         /* Start a new bblock which CALL_HANDLER can branch to */
2710         target_bb = bblocks [bb->block_num].call_handler_target_bb;
2711         if (target_bb) {
2712                 ctx->builder = builder = create_builder (ctx);
2713                 LLVMPositionBuilderAtEnd (ctx->builder, target_bb);
2714
2715                 ctx->bblocks [bb->block_num].end_bblock = target_bb;
2716
2717                 /* Store the exception into the IL level exvar */
2718                 if (bb->in_scount == 1) {
2719                         g_assert (bb->in_scount == 1);
2720                         exvar = bb->in_stack [0];
2721
2722                         // FIXME: This is shared with filter clauses ?
2723                         g_assert (!values [exvar->dreg]);
2724
2725                         g_assert (ctx->ex_var);
2726                         values [exvar->dreg] = LLVMBuildLoad (builder, ctx->ex_var, "");
2727                         emit_volatile_store (ctx, exvar->dreg);
2728                 }
2729         }
2730 }
2731
2732 static void
2733 process_bb (EmitContext *ctx, MonoBasicBlock *bb)
2734 {
2735         MonoCompile *cfg = ctx->cfg;
2736         MonoMethodSignature *sig = ctx->sig;
2737         LLVMValueRef method = ctx->lmethod;
2738         LLVMValueRef *values = ctx->values;
2739         LLVMValueRef *addresses = ctx->addresses;
2740         LLVMCallInfo *linfo = ctx->linfo;
2741         LLVMModuleRef module = ctx->module;
2742         BBInfo *bblocks = ctx->bblocks;
2743         MonoInst *ins;
2744         LLVMBasicBlockRef cbb;
2745         LLVMBuilderRef builder, starting_builder;
2746         gboolean has_terminator;
2747         LLVMValueRef v;
2748         LLVMValueRef lhs, rhs;
2749         int nins = 0;
2750
2751         cbb = get_bb (ctx, bb);
2752         builder = create_builder (ctx);
2753         ctx->builder = builder;
2754         LLVMPositionBuilderAtEnd (builder, cbb);
2755
2756         if (bb == cfg->bb_entry)
2757                 emit_entry_bb (ctx, builder);
2758         CHECK_FAILURE (ctx);
2759
2760         if (bb->flags & BB_EXCEPTION_HANDLER) {
2761                 if (!bblocks [bb->block_num].invoke_target) {
2762                         //LLVM_FAILURE (ctx, "handler without invokes");
2763                 }
2764
2765                 emit_handler_start (ctx, bb, builder);
2766                 CHECK_FAILURE (ctx);
2767                 builder = ctx->builder;
2768         }
2769
2770         has_terminator = FALSE;
2771         starting_builder = builder;
2772         for (ins = bb->code; ins; ins = ins->next) {
2773                 const char *spec = LLVM_INS_INFO (ins->opcode);
2774                 char *dname = NULL;
2775                 char dname_buf [128];
2776
2777                 emit_dbg_loc (ctx, builder, ins->cil_code);
2778
2779                 nins ++;
2780                 if (nins > 3000 && builder == starting_builder) {
2781                         /* some steps in llc are non-linear in the size of basic blocks, see #5714 */
2782                         LLVM_FAILURE (ctx, "basic block too long");
2783                 }
2784
2785                 if (has_terminator)
2786                         /* There could be instructions after a terminator, skip them */
2787                         break;
2788
2789                 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins)) {
2790                         sprintf (dname_buf, "t%d", ins->dreg);
2791                         dname = dname_buf;
2792                 }
2793
2794                 if (spec [MONO_INST_SRC1] != ' ' && spec [MONO_INST_SRC1] != 'v') {
2795                         MonoInst *var = get_vreg_to_inst (cfg, ins->sreg1);
2796
2797                         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2798                                 lhs = emit_volatile_load (ctx, ins->sreg1);
2799                         } else {
2800                                 /* It is ok for SETRET to have an uninitialized argument */
2801                                 if (!values [ins->sreg1] && ins->opcode != OP_SETRET)
2802                                         LLVM_FAILURE (ctx, "sreg1");
2803                                 lhs = values [ins->sreg1];
2804                         }
2805                 } else {
2806                         lhs = NULL;
2807                 }
2808
2809                 if (spec [MONO_INST_SRC2] != ' ' && spec [MONO_INST_SRC2] != ' ') {
2810                         MonoInst *var = get_vreg_to_inst (cfg, ins->sreg2);
2811                         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2812                                 rhs = emit_volatile_load (ctx, ins->sreg2);
2813                         } else {
2814                                 if (!values [ins->sreg2])
2815                                         LLVM_FAILURE (ctx, "sreg2");
2816                                 rhs = values [ins->sreg2];
2817                         }
2818                 } else {
2819                         rhs = NULL;
2820                 }
2821
2822                 //mono_print_ins (ins);
2823                 switch (ins->opcode) {
2824                 case OP_NOP:
2825                 case OP_NOT_NULL:
2826                 case OP_LIVERANGE_START:
2827                 case OP_LIVERANGE_END:
2828                         break;
2829                 case OP_ICONST:
2830                         values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE);
2831                         break;
2832                 case OP_I8CONST:
2833 #if SIZEOF_VOID_P == 4
2834                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2835 #else
2836                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), (gint64)ins->inst_c0, FALSE);
2837 #endif
2838                         break;
2839                 case OP_R8CONST:
2840                         values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), *(double*)ins->inst_p0);
2841                         break;
2842                 case OP_R4CONST:
2843                         if (cfg->r4fp)
2844                                 values [ins->dreg] = LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0);
2845                         else
2846                                 values [ins->dreg] = LLVMConstFPExt (LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0), LLVMDoubleType ());
2847                         break;
2848                 case OP_DUMMY_ICONST:
2849                         values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
2850                         break;
2851                 case OP_DUMMY_I8CONST:
2852                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
2853                         break;
2854                 case OP_DUMMY_R8CONST:
2855                         values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), 0.0f);
2856                         break;
2857                 case OP_BR:
2858                         LLVMBuildBr (builder, get_bb (ctx, ins->inst_target_bb));
2859                         has_terminator = TRUE;
2860                         break;
2861                 case OP_SWITCH: {
2862                         int i;
2863                         LLVMValueRef v;
2864                         char bb_name [128];
2865                         LLVMBasicBlockRef new_bb;
2866                         LLVMBuilderRef new_builder;
2867
2868                         // The default branch is already handled
2869                         // FIXME: Handle it here
2870
2871                         /* Start new bblock */
2872                         sprintf (bb_name, "SWITCH_DEFAULT_BB%d", ctx->default_index ++);
2873                         new_bb = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
2874
2875                         lhs = convert (ctx, lhs, LLVMInt32Type ());
2876                         v = LLVMBuildSwitch (builder, lhs, new_bb, GPOINTER_TO_UINT (ins->klass));
2877                         for (i = 0; i < GPOINTER_TO_UINT (ins->klass); ++i) {
2878                                 MonoBasicBlock *target_bb = ins->inst_many_bb [i];
2879
2880                                 LLVMAddCase (v, LLVMConstInt (LLVMInt32Type (), i, FALSE), get_bb (ctx, target_bb));
2881                         }
2882
2883                         new_builder = create_builder (ctx);
2884                         LLVMPositionBuilderAtEnd (new_builder, new_bb);
2885                         LLVMBuildUnreachable (new_builder);
2886
2887                         has_terminator = TRUE;
2888                         g_assert (!ins->next);
2889                                 
2890                         break;
2891                 }
2892
2893                 case OP_SETRET:
2894                         switch (linfo->ret.storage) {
2895                         case LLVMArgVtypeInReg: {
2896                                 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2897                                 LLVMValueRef part1, retval;
2898                                 int size;
2899
2900                                 size = get_vtype_size (sig->ret);
2901
2902                                 g_assert (addresses [ins->sreg1]);
2903
2904                                 g_assert (linfo->ret.pair_storage [0] == LLVMArgInIReg);
2905                                 g_assert (linfo->ret.pair_storage [1] == LLVMArgNone);
2906                                         
2907                                 part1 = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMIntType (size * 8), 0), ""), ""), IntPtrType ());
2908
2909                                 retval = LLVMBuildInsertValue (builder, LLVMGetUndef (ret_type), part1, 0, "");
2910
2911                                 LLVMBuildRet (builder, retval);
2912                                 break;
2913                         }
2914                         case LLVMArgVtypeAsScalar: {
2915                                 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2916                                 LLVMValueRef retval;
2917                                 int size;
2918
2919                                 size = get_vtype_size (sig->ret);
2920
2921                                 g_assert (addresses [ins->sreg1]);
2922
2923                                 retval = LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (ret_type, 0), ""), "");
2924                                 LLVMBuildRet (builder, retval);
2925                                 break;
2926                         }
2927                         case LLVMArgVtypeByVal: {
2928                                 LLVMValueRef retval;
2929
2930                                 g_assert (addresses [ins->sreg1]);
2931                                 retval = LLVMBuildLoad (builder, addresses [ins->sreg1], "");
2932                                 LLVMBuildRet (builder, retval);
2933                                 break;
2934                         }
2935                         case LLVMArgVtypeByRef: {
2936                                 LLVMBuildRetVoid (builder);
2937                                 break;
2938                         }
2939                         case LLVMArgVtypeRetAddr: {
2940                                 LLVMBuildRetVoid (builder);
2941                                 break;
2942                         }
2943                         case LLVMArgFpStruct: {
2944                                 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2945                                 LLVMValueRef retval;
2946
2947                                 g_assert (addresses [ins->sreg1]);
2948                                 retval = LLVMBuildLoad (builder, convert (ctx, addresses [ins->sreg1], LLVMPointerType (ret_type, 0)), "");
2949                                 LLVMBuildRet (builder, retval);
2950                                 break;
2951                         }
2952                         default: {
2953                                 if (!lhs || ctx->is_dead [ins->sreg1]) {
2954                                         /*
2955                                          * The method did not set its return value, probably because it
2956                                          * ends with a throw.
2957                                          */
2958                                         if (cfg->vret_addr)
2959                                                 LLVMBuildRetVoid (builder);
2960                                         else
2961                                                 LLVMBuildRet (builder, LLVMConstNull (type_to_llvm_type (ctx, sig->ret)));
2962                                 } else {
2963                                         LLVMBuildRet (builder, convert (ctx, lhs, type_to_llvm_type (ctx, sig->ret)));
2964                                 }
2965                                 has_terminator = TRUE;
2966                                 break;
2967                         }
2968                         }
2969                         break;
2970                 case OP_ICOMPARE:
2971                 case OP_FCOMPARE:
2972                 case OP_RCOMPARE:
2973                 case OP_LCOMPARE:
2974                 case OP_COMPARE:
2975                 case OP_ICOMPARE_IMM:
2976                 case OP_LCOMPARE_IMM:
2977                 case OP_COMPARE_IMM: {
2978                         CompRelation rel;
2979                         LLVMValueRef cmp;
2980
2981                         if (ins->next->opcode == OP_NOP)
2982                                 break;
2983
2984                         if (ins->next->opcode == OP_BR)
2985                                 /* The comparison result is not needed */
2986                                 continue;
2987
2988                         rel = mono_opcode_to_cond (ins->next->opcode);
2989
2990                         if (ins->opcode == OP_ICOMPARE_IMM) {
2991                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2992                                 rhs = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2993                         }
2994                         if (ins->opcode == OP_LCOMPARE_IMM) {
2995                                 lhs = convert (ctx, lhs, LLVMInt64Type ());
2996                                 rhs = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2997                         }
2998                         if (ins->opcode == OP_LCOMPARE) {
2999                                 lhs = convert (ctx, lhs, LLVMInt64Type ());
3000                                 rhs = convert (ctx, rhs, LLVMInt64Type ());
3001                         }
3002                         if (ins->opcode == OP_ICOMPARE) {
3003                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
3004                                 rhs = convert (ctx, rhs, LLVMInt32Type ());
3005                         }
3006
3007                         if (lhs && rhs) {
3008                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
3009                                         rhs = convert (ctx, rhs, LLVMTypeOf (lhs));
3010                                 else if (LLVMGetTypeKind (LLVMTypeOf (rhs)) == LLVMPointerTypeKind)
3011                                         lhs = convert (ctx, lhs, LLVMTypeOf (rhs));
3012                         }
3013
3014                         /* We use COMPARE+SETcc/Bcc, llvm uses SETcc+br cond */
3015                         if (ins->opcode == OP_FCOMPARE) {
3016                                 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
3017                         } else if (ins->opcode == OP_RCOMPARE) {
3018                                 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMFloatType ()), convert (ctx, rhs, LLVMFloatType ()), "");
3019                         } else if (ins->opcode == OP_COMPARE_IMM) {
3020                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && ins->inst_imm == 0)
3021                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, LLVMConstNull (LLVMTypeOf (lhs)), "");
3022                                 else
3023                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), "");
3024                         } else if (ins->opcode == OP_LCOMPARE_IMM) {
3025                                 if (SIZEOF_REGISTER == 4 && COMPILE_LLVM (cfg))  {
3026                                         /* The immediate is encoded in two fields */
3027                                         guint64 l = ((guint64)(guint32)ins->inst_offset << 32) | ((guint32)ins->inst_imm);
3028                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), l, FALSE), "");
3029                                 } else {
3030                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), ins->inst_imm, FALSE), "");
3031                                 }
3032                         }
3033                         else if (ins->opcode == OP_COMPARE) {
3034                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && LLVMTypeOf (lhs) == LLVMTypeOf (rhs))
3035                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
3036                                 else
3037                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), convert (ctx, rhs, IntPtrType ()), "");
3038                         } else
3039                                 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
3040
3041                         if (MONO_IS_COND_BRANCH_OP (ins->next)) {
3042                                 if (ins->next->inst_true_bb == ins->next->inst_false_bb) {
3043                                         /*
3044                                          * If the target bb contains PHI instructions, LLVM requires
3045                                          * two PHI entries for this bblock, while we only generate one.
3046                                          * So convert this to an unconditional bblock. (bxc #171).
3047                                          */
3048                                         LLVMBuildBr (builder, get_bb (ctx, ins->next->inst_true_bb));
3049                                 } else {
3050                                         LLVMBuildCondBr (builder, cmp, get_bb (ctx, ins->next->inst_true_bb), get_bb (ctx, ins->next->inst_false_bb));
3051                                 }
3052                                 has_terminator = TRUE;
3053                         } else if (MONO_IS_SETCC (ins->next)) {
3054                                 sprintf (dname_buf, "t%d", ins->next->dreg);
3055                                 dname = dname_buf;
3056                                 values [ins->next->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
3057
3058                                 /* Add stores for volatile variables */
3059                                 emit_volatile_store (ctx, ins->next->dreg);
3060                         } else if (MONO_IS_COND_EXC (ins->next)) {
3061                                 emit_cond_system_exception (ctx, bb, ins->next->inst_p1, cmp);
3062                                 CHECK_FAILURE (ctx);
3063                                 builder = ctx->builder;
3064                         } else {
3065                                 LLVM_FAILURE (ctx, "next");
3066                         }
3067
3068                         ins = ins->next;
3069                         break;
3070                 }
3071                 case OP_FCEQ:
3072                 case OP_FCLT:
3073                 case OP_FCLT_UN:
3074                 case OP_FCGT:
3075                 case OP_FCGT_UN: {
3076                         CompRelation rel;
3077                         LLVMValueRef cmp;
3078
3079                         rel = mono_opcode_to_cond (ins->opcode);
3080
3081                         cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
3082                         values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
3083                         break;
3084                 }
3085                 case OP_RCEQ:
3086                 case OP_RCLT:
3087                 case OP_RCLT_UN:
3088                 case OP_RCGT:
3089                 case OP_RCGT_UN: {
3090                         CompRelation rel;
3091                         LLVMValueRef cmp;
3092
3093                         rel = mono_opcode_to_cond (ins->opcode);
3094
3095                         cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMFloatType ()), convert (ctx, rhs, LLVMFloatType ()), "");
3096                         values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
3097                         break;
3098                 }
3099                 case OP_PHI:
3100                 case OP_FPHI:
3101                 case OP_VPHI:
3102                 case OP_XPHI: {
3103                         int i;
3104                         gboolean empty = TRUE;
3105
3106                         /* Check that all input bblocks really branch to us */
3107                         for (i = 0; i < bb->in_count; ++i) {
3108                                 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_NOT_REACHED)
3109                                         ins->inst_phi_args [i + 1] = -1;
3110                                 else
3111                                         empty = FALSE;
3112                         }
3113
3114                         if (empty) {
3115                                 /* LLVM doesn't like phi instructions with zero operands */
3116                                 ctx->is_dead [ins->dreg] = TRUE;
3117                                 break;
3118                         }                                       
3119
3120                         /* Created earlier, insert it now */
3121                         LLVMInsertIntoBuilder (builder, values [ins->dreg]);
3122
3123                         for (i = 0; i < ins->inst_phi_args [0]; i++) {
3124                                 int sreg1 = ins->inst_phi_args [i + 1];
3125                                 int count, j;
3126
3127                                 /* 
3128                                  * Count the number of times the incoming bblock branches to us,
3129                                  * since llvm requires a separate entry for each.
3130                                  */
3131                                 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_SWITCH) {
3132                                         MonoInst *switch_ins = bb->in_bb [i]->last_ins;
3133
3134                                         count = 0;
3135                                         for (j = 0; j < GPOINTER_TO_UINT (switch_ins->klass); ++j) {
3136                                                 if (switch_ins->inst_many_bb [j] == bb)
3137                                                         count ++;
3138                                         }
3139                                 } else {
3140                                         count = 1;
3141                                 }
3142
3143                                 /* Remember for later */
3144                                 for (j = 0; j < count; ++j) {
3145                                         PhiNode *node = mono_mempool_alloc0 (ctx->mempool, sizeof (PhiNode));
3146                                         node->bb = bb;
3147                                         node->phi = ins;
3148                                         node->in_bb = bb->in_bb [i];
3149                                         node->sreg = sreg1;
3150                                         bblocks [bb->in_bb [i]->block_num].phi_nodes = g_slist_prepend_mempool (ctx->mempool, bblocks [bb->in_bb [i]->block_num].phi_nodes, node);
3151                                 }
3152                         }
3153                         break;
3154                 }
3155                 case OP_MOVE:
3156                 case OP_LMOVE:
3157                 case OP_XMOVE:
3158                 case OP_SETFRET:
3159                         g_assert (lhs);
3160                         values [ins->dreg] = lhs;
3161                         break;
3162                 case OP_FMOVE:
3163                 case OP_RMOVE: {
3164                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
3165                                 
3166                         g_assert (lhs);
3167                         values [ins->dreg] = lhs;
3168
3169                         if (var && var->klass->byval_arg.type == MONO_TYPE_R4) {
3170                                 /* 
3171                                  * This is added by the spilling pass in case of the JIT,
3172                                  * but we have to do it ourselves.
3173                                  */
3174                                 values [ins->dreg] = convert (ctx, values [ins->dreg], LLVMFloatType ());
3175                         }
3176                         break;
3177                 }
3178                 case OP_MOVE_F_TO_I4: {
3179                         values [ins->dreg] = LLVMBuildBitCast (builder, LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), ""), LLVMInt32Type (), "");
3180                         break;
3181                 }
3182                 case OP_MOVE_I4_TO_F: {
3183                         values [ins->dreg] = LLVMBuildFPExt (builder, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType (), "");
3184                         break;
3185                 }
3186                 case OP_MOVE_F_TO_I8: {
3187                         values [ins->dreg] = LLVMBuildBitCast (builder, lhs, LLVMInt64Type (), "");
3188                         break;
3189                 }
3190                 case OP_MOVE_I8_TO_F: {
3191                         values [ins->dreg] = LLVMBuildBitCast (builder, lhs, LLVMDoubleType (), "");
3192                         break;
3193                 }
3194                 case OP_IADD:
3195                 case OP_ISUB:
3196                 case OP_IAND:
3197                 case OP_IMUL:
3198                 case OP_IDIV:
3199                 case OP_IDIV_UN:
3200                 case OP_IREM:
3201                 case OP_IREM_UN:
3202                 case OP_IOR:
3203                 case OP_IXOR:
3204                 case OP_ISHL:
3205                 case OP_ISHR:
3206                 case OP_ISHR_UN:
3207                 case OP_FADD:
3208                 case OP_FSUB:
3209                 case OP_FMUL:
3210                 case OP_FDIV:
3211                 case OP_LADD:
3212                 case OP_LSUB:
3213                 case OP_LMUL:
3214                 case OP_LDIV:
3215                 case OP_LDIV_UN:
3216                 case OP_LREM:
3217                 case OP_LREM_UN:
3218                 case OP_LAND:
3219                 case OP_LOR:
3220                 case OP_LXOR:
3221                 case OP_LSHL:
3222                 case OP_LSHR:
3223                 case OP_LSHR_UN:
3224                         lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3225                         rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3226
3227                         emit_div_check (ctx, builder, bb, ins, lhs, rhs);
3228                         CHECK_FAILURE (ctx);
3229                         builder = ctx->builder;
3230
3231                         switch (ins->opcode) {
3232                         case OP_IADD:
3233                         case OP_LADD:
3234                                 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, dname);
3235                                 break;
3236                         case OP_ISUB:
3237                         case OP_LSUB:
3238                                 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, dname);
3239                                 break;
3240                         case OP_IMUL:
3241                         case OP_LMUL:
3242                                 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, dname);
3243                                 break;
3244                         case OP_IREM:
3245                         case OP_LREM:
3246                                 values [ins->dreg] = LLVMBuildSRem (builder, lhs, rhs, dname);
3247                                 break;
3248                         case OP_IREM_UN:
3249                         case OP_LREM_UN:
3250                                 values [ins->dreg] = LLVMBuildURem (builder, lhs, rhs, dname);
3251                                 break;
3252                         case OP_IDIV:
3253                         case OP_LDIV:
3254                                 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, rhs, dname);
3255                                 break;
3256                         case OP_IDIV_UN:
3257                         case OP_LDIV_UN:
3258                                 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, rhs, dname);
3259                                 break;
3260                         case OP_FDIV:
3261                         case OP_RDIV:
3262                                 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
3263                                 break;
3264                         case OP_IAND:
3265                         case OP_LAND:
3266                                 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, dname);
3267                                 break;
3268                         case OP_IOR:
3269                         case OP_LOR:
3270                                 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, dname);
3271                                 break;
3272                         case OP_IXOR:
3273                         case OP_LXOR:
3274                                 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, dname);
3275                                 break;
3276                         case OP_ISHL:
3277                         case OP_LSHL:
3278                                 values [ins->dreg] = LLVMBuildShl (builder, lhs, rhs, dname);
3279                                 break;
3280                         case OP_ISHR:
3281                         case OP_LSHR:
3282                                 values [ins->dreg] = LLVMBuildAShr (builder, lhs, rhs, dname);
3283                                 break;
3284                         case OP_ISHR_UN:
3285                         case OP_LSHR_UN:
3286                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, rhs, dname);
3287                                 break;
3288
3289                         case OP_FADD:
3290                                 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
3291                                 break;
3292                         case OP_FSUB:
3293                                 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
3294                                 break;
3295                         case OP_FMUL:
3296                                 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
3297                                 break;
3298
3299                         default:
3300                                 g_assert_not_reached ();
3301                         }
3302                         break;
3303                 case OP_RADD:
3304                 case OP_RSUB:
3305                 case OP_RMUL:
3306                 case OP_RDIV: {
3307                         lhs = convert (ctx, lhs, LLVMFloatType ());
3308                         rhs = convert (ctx, rhs, LLVMFloatType ());
3309                         switch (ins->opcode) {
3310                         case OP_RADD:
3311                                 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
3312                                 break;
3313                         case OP_RSUB:
3314                                 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
3315                                 break;
3316                         case OP_RMUL:
3317                                 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
3318                                 break;
3319                         case OP_RDIV:
3320                                 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
3321                                 break;
3322                         default:
3323                                 g_assert_not_reached ();
3324                                 break;
3325                         }
3326                         break;
3327                 }
3328                 case OP_IADD_IMM:
3329                 case OP_ISUB_IMM:
3330                 case OP_IMUL_IMM:
3331                 case OP_IREM_IMM:
3332                 case OP_IREM_UN_IMM:
3333                 case OP_IDIV_IMM:
3334                 case OP_IDIV_UN_IMM:
3335                 case OP_IAND_IMM:
3336                 case OP_IOR_IMM:
3337                 case OP_IXOR_IMM:
3338                 case OP_ISHL_IMM:
3339                 case OP_ISHR_IMM:
3340                 case OP_ISHR_UN_IMM:
3341                 case OP_LADD_IMM:
3342                 case OP_LSUB_IMM:
3343                 case OP_LREM_IMM:
3344                 case OP_LAND_IMM:
3345                 case OP_LOR_IMM:
3346                 case OP_LXOR_IMM:
3347                 case OP_LSHL_IMM:
3348                 case OP_LSHR_IMM:
3349                 case OP_LSHR_UN_IMM:
3350                 case OP_ADD_IMM:
3351                 case OP_AND_IMM:
3352                 case OP_MUL_IMM:
3353                 case OP_SHL_IMM:
3354                 case OP_SHR_IMM:
3355                 case OP_SHR_UN_IMM: {
3356                         LLVMValueRef imm;
3357
3358                         if (spec [MONO_INST_SRC1] == 'l') {
3359                                 imm = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
3360                         } else {
3361                                 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3362                         }
3363
3364                         emit_div_check (ctx, builder, bb, ins, lhs, imm);
3365                         CHECK_FAILURE (ctx);
3366                         builder = ctx->builder;
3367
3368 #if SIZEOF_VOID_P == 4
3369                         if (ins->opcode == OP_LSHL_IMM || ins->opcode == OP_LSHR_IMM || ins->opcode == OP_LSHR_UN_IMM)
3370                                 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3371 #endif
3372
3373                         if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
3374                                 lhs = convert (ctx, lhs, IntPtrType ());
3375                         imm = convert (ctx, imm, LLVMTypeOf (lhs));
3376                         switch (ins->opcode) {
3377                         case OP_IADD_IMM:
3378                         case OP_LADD_IMM:
3379                         case OP_ADD_IMM:
3380                                 values [ins->dreg] = LLVMBuildAdd (builder, lhs, imm, dname);
3381                                 break;
3382                         case OP_ISUB_IMM:
3383                         case OP_LSUB_IMM:
3384                                 values [ins->dreg] = LLVMBuildSub (builder, lhs, imm, dname);
3385                                 break;
3386                         case OP_IMUL_IMM:
3387                         case OP_MUL_IMM:
3388                                 values [ins->dreg] = LLVMBuildMul (builder, lhs, imm, dname);
3389                                 break;
3390                         case OP_IDIV_IMM:
3391                         case OP_LDIV_IMM:
3392                                 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, imm, dname);
3393                                 break;
3394                         case OP_IDIV_UN_IMM:
3395                         case OP_LDIV_UN_IMM:
3396                                 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, imm, dname);
3397                                 break;
3398                         case OP_IREM_IMM:
3399                         case OP_LREM_IMM:
3400                                 values [ins->dreg] = LLVMBuildSRem (builder, lhs, imm, dname);
3401                                 break;
3402                         case OP_IREM_UN_IMM:
3403                                 values [ins->dreg] = LLVMBuildURem (builder, lhs, imm, dname);
3404                                 break;
3405                         case OP_IAND_IMM:
3406                         case OP_LAND_IMM:
3407                         case OP_AND_IMM:
3408                                 values [ins->dreg] = LLVMBuildAnd (builder, lhs, imm, dname);
3409                                 break;
3410                         case OP_IOR_IMM:
3411                         case OP_LOR_IMM:
3412                                 values [ins->dreg] = LLVMBuildOr (builder, lhs, imm, dname);
3413                                 break;
3414                         case OP_IXOR_IMM:
3415                         case OP_LXOR_IMM:
3416                                 values [ins->dreg] = LLVMBuildXor (builder, lhs, imm, dname);
3417                                 break;
3418                         case OP_ISHL_IMM:
3419                         case OP_LSHL_IMM:
3420                         case OP_SHL_IMM:
3421                                 values [ins->dreg] = LLVMBuildShl (builder, lhs, imm, dname);
3422                                 break;
3423                         case OP_ISHR_IMM:
3424                         case OP_LSHR_IMM:
3425                         case OP_SHR_IMM:
3426                                 values [ins->dreg] = LLVMBuildAShr (builder, lhs, imm, dname);
3427                                 break;
3428                         case OP_ISHR_UN_IMM:
3429                                 /* This is used to implement conv.u4, so the lhs could be an i8 */
3430                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
3431                                 imm = convert (ctx, imm, LLVMInt32Type ());
3432                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
3433                                 break;
3434                         case OP_LSHR_UN_IMM:
3435                         case OP_SHR_UN_IMM:
3436                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
3437                                 break;
3438                         default:
3439                                 g_assert_not_reached ();
3440                         }
3441                         break;
3442                 }
3443                 case OP_INEG:
3444                         values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
3445                         break;
3446                 case OP_LNEG:
3447                         values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt64Type (), 0, FALSE), lhs, dname);
3448                         break;
3449                 case OP_FNEG:
3450                         lhs = convert (ctx, lhs, LLVMDoubleType ());
3451                         values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMDoubleType (), 0.0), lhs, dname);
3452                         break;
3453                 case OP_RNEG:
3454                         lhs = convert (ctx, lhs, LLVMFloatType ());
3455                         values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMFloatType (), 0.0), lhs, dname);
3456                         break;
3457                 case OP_INOT: {
3458                         guint32 v = 0xffffffff;
3459                         values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt32Type (), v, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
3460                         break;
3461                 }
3462                 case OP_LNOT: {
3463                         guint64 v = 0xffffffffffffffffLL;
3464                         values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt64Type (), v, FALSE), lhs, dname);
3465                         break;
3466                 }
3467 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3468                 case OP_X86_LEA: {
3469                         LLVMValueRef v1, v2;
3470
3471                         v1 = LLVMBuildMul (builder, convert (ctx, rhs, IntPtrType ()), LLVMConstInt (IntPtrType (), (1 << ins->backend.shift_amount), FALSE), "");
3472                         v2 = LLVMBuildAdd (builder, convert (ctx, lhs, IntPtrType ()), v1, "");
3473                         values [ins->dreg] = LLVMBuildAdd (builder, v2, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), dname);
3474                         break;
3475                 }
3476 #endif
3477
3478                 case OP_ICONV_TO_I1:
3479                 case OP_ICONV_TO_I2:
3480                 case OP_ICONV_TO_I4:
3481                 case OP_ICONV_TO_U1:
3482                 case OP_ICONV_TO_U2:
3483                 case OP_ICONV_TO_U4:
3484                 case OP_LCONV_TO_I1:
3485                 case OP_LCONV_TO_I2:
3486                 case OP_LCONV_TO_U1:
3487                 case OP_LCONV_TO_U2:
3488                 case OP_LCONV_TO_U4: {
3489                         gboolean sign;
3490
3491                         sign = (ins->opcode == OP_ICONV_TO_I1) || (ins->opcode == OP_ICONV_TO_I2) || (ins->opcode == OP_ICONV_TO_I4) || (ins->opcode == OP_LCONV_TO_I1) || (ins->opcode == OP_LCONV_TO_I2);
3492
3493                         /* Have to do two casts since our vregs have type int */
3494                         v = LLVMBuildTrunc (builder, lhs, op_to_llvm_type (ins->opcode), "");
3495                         if (sign)
3496                                 values [ins->dreg] = LLVMBuildSExt (builder, v, LLVMInt32Type (), dname);
3497                         else
3498                                 values [ins->dreg] = LLVMBuildZExt (builder, v, LLVMInt32Type (), dname);
3499                         break;
3500                 }
3501                 case OP_ICONV_TO_I8:
3502                         values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
3503                         break;
3504                 case OP_ICONV_TO_U8:
3505                         values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
3506                         break;
3507                 case OP_FCONV_TO_I4:
3508                 case OP_RCONV_TO_I4:
3509                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt32Type (), dname);
3510                         break;
3511                 case OP_FCONV_TO_I1:
3512                 case OP_RCONV_TO_I1:
3513                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
3514                         break;
3515                 case OP_FCONV_TO_U1:
3516                 case OP_RCONV_TO_U1:
3517                         values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
3518                         break;
3519                 case OP_FCONV_TO_I2:
3520                 case OP_RCONV_TO_I2:
3521                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
3522                         break;
3523                 case OP_FCONV_TO_U2:
3524                 case OP_RCONV_TO_U2:
3525                         values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
3526                         break;
3527                 case OP_FCONV_TO_I8:
3528                 case OP_RCONV_TO_I8:
3529                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt64Type (), dname);
3530                         break;
3531                 case OP_FCONV_TO_I:
3532                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, IntPtrType (), dname);
3533                         break;
3534                 case OP_ICONV_TO_R8:
3535                 case OP_LCONV_TO_R8:
3536                         values [ins->dreg] = LLVMBuildSIToFP (builder, lhs, LLVMDoubleType (), dname);
3537                         break;
3538                 case OP_ICONV_TO_R_UN:
3539                 case OP_LCONV_TO_R_UN:
3540                         values [ins->dreg] = LLVMBuildUIToFP (builder, lhs, LLVMDoubleType (), dname);
3541                         break;
3542 #if SIZEOF_VOID_P == 4
3543                 case OP_LCONV_TO_U:
3544 #endif
3545                 case OP_LCONV_TO_I4:
3546                         values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3547                         break;
3548                 case OP_ICONV_TO_R4:
3549                 case OP_LCONV_TO_R4:
3550                         v = LLVMBuildSIToFP (builder, lhs, LLVMFloatType (), "");
3551                         if (cfg->r4fp)
3552                                 values [ins->dreg] = v;
3553                         else
3554                                 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3555                         break;
3556                 case OP_FCONV_TO_R4:
3557                         v = LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), "");
3558                         if (cfg->r4fp)
3559                                 values [ins->dreg] = v;
3560                         else
3561                                 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3562                         break;
3563                 case OP_RCONV_TO_R8:
3564                         values [ins->dreg] = LLVMBuildFPExt (builder, lhs, LLVMDoubleType (), dname);
3565                         break;
3566                 case OP_RCONV_TO_R4:
3567                         values [ins->dreg] = lhs;
3568                         break;
3569                 case OP_SEXT_I4:
3570                         values [ins->dreg] = LLVMBuildSExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3571                         break;
3572                 case OP_ZEXT_I4:
3573                         values [ins->dreg] = LLVMBuildZExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3574                         break;
3575                 case OP_TRUNC_I4:
3576                         values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3577                         break;
3578                 case OP_LOCALLOC_IMM: {
3579                         LLVMValueRef v;
3580
3581                         guint32 size = ins->inst_imm;
3582                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
3583
3584                         v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
3585
3586                         if (ins->flags & MONO_INST_INIT) {
3587                                 LLVMValueRef args [5];
3588
3589                                 args [0] = v;
3590                                 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3591                                 args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
3592                                 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3593                                 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3594                                 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3595                         }
3596
3597                         values [ins->dreg] = v;
3598                         break;
3599                 }
3600                 case OP_LOCALLOC: {
3601                         LLVMValueRef v, size;
3602                                 
3603                         size = LLVMBuildAnd (builder, LLVMBuildAdd (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT - 1, FALSE), ""), LLVMConstInt (LLVMInt32Type (), ~ (MONO_ARCH_FRAME_ALIGNMENT - 1), FALSE), "");
3604
3605                         v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
3606
3607                         if (ins->flags & MONO_INST_INIT) {
3608                                 LLVMValueRef args [5];
3609
3610                                 args [0] = v;
3611                                 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3612                                 args [2] = size;
3613                                 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3614                                 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3615                                 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3616                         }
3617                         values [ins->dreg] = v;
3618                         break;
3619                 }
3620
3621                 case OP_LOADI1_MEMBASE:
3622                 case OP_LOADU1_MEMBASE:
3623                 case OP_LOADI2_MEMBASE:
3624                 case OP_LOADU2_MEMBASE:
3625                 case OP_LOADI4_MEMBASE:
3626                 case OP_LOADU4_MEMBASE:
3627                 case OP_LOADI8_MEMBASE:
3628                 case OP_LOADR4_MEMBASE:
3629                 case OP_LOADR8_MEMBASE:
3630                 case OP_LOAD_MEMBASE:
3631                 case OP_LOADI8_MEM:
3632                 case OP_LOADU1_MEM:
3633                 case OP_LOADU2_MEM:
3634                 case OP_LOADI4_MEM:
3635                 case OP_LOADU4_MEM:
3636                 case OP_LOAD_MEM: {
3637                         int size = 8;
3638                         LLVMValueRef base, index, addr;
3639                         LLVMTypeRef t;
3640                         gboolean sext = FALSE, zext = FALSE;
3641                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3642
3643                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3644
3645                         if (sext || zext)
3646                                 dname = (char*)"";
3647
3648                         if ((ins->opcode == OP_LOADI8_MEM) || (ins->opcode == OP_LOAD_MEM) || (ins->opcode == OP_LOADI4_MEM) || (ins->opcode == OP_LOADU4_MEM) || (ins->opcode == OP_LOADU1_MEM) || (ins->opcode == OP_LOADU2_MEM)) {
3649                                 addr = LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE);
3650                         } else {
3651                                 /* _MEMBASE */
3652                                 base = lhs;
3653
3654                                 if (ins->inst_offset == 0) {
3655                                         addr = base;
3656                                 } else if (ins->inst_offset % size != 0) {
3657                                         /* Unaligned load */
3658                                         index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3659                                         addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3660                                 } else {
3661                                         index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3662                                         addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (t, 0)), &index, 1, "");
3663                                 }
3664                         }
3665
3666                         addr = convert (ctx, addr, LLVMPointerType (t, 0));
3667
3668                         values [ins->dreg] = emit_load (ctx, bb, &builder, size, addr, dname, is_volatile);
3669
3670                         if (!is_volatile && (ins->flags & MONO_INST_INVARIANT_LOAD)) {
3671                                 /*
3672                                  * These will signal LLVM that these loads do not alias any stores, and
3673                                  * they can't fail, allowing them to be hoisted out of loops.
3674                                  */
3675                                 set_invariant_load_flag (values [ins->dreg]);
3676                                 set_metadata_flag (values [ins->dreg], "mono.nofail.load");
3677                         }
3678
3679                         if (sext)
3680                                 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3681                         else if (zext)
3682                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3683                         else if (!cfg->r4fp && ins->opcode == OP_LOADR4_MEMBASE)
3684                                 values [ins->dreg] = LLVMBuildFPExt (builder, values [ins->dreg], LLVMDoubleType (), dname);
3685                         break;
3686                 }
3687                                 
3688                 case OP_STOREI1_MEMBASE_REG:
3689                 case OP_STOREI2_MEMBASE_REG:
3690                 case OP_STOREI4_MEMBASE_REG:
3691                 case OP_STOREI8_MEMBASE_REG:
3692                 case OP_STORER4_MEMBASE_REG:
3693                 case OP_STORER8_MEMBASE_REG:
3694                 case OP_STORE_MEMBASE_REG: {
3695                         int size = 8;
3696                         LLVMValueRef index, addr;
3697                         LLVMTypeRef t;
3698                         gboolean sext = FALSE, zext = FALSE;
3699                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3700
3701                         if (!values [ins->inst_destbasereg])
3702                                 LLVM_FAILURE (ctx, "inst_destbasereg");
3703
3704                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3705
3706                         if (ins->inst_offset % size != 0) {
3707                                 /* Unaligned store */
3708                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3709                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3710                         } else {
3711                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
3712                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3713                         }
3714                         emit_store (ctx, bb, &builder, size, convert (ctx, values [ins->sreg1], t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3715                         break;
3716                 }
3717
3718                 case OP_STOREI1_MEMBASE_IMM:
3719                 case OP_STOREI2_MEMBASE_IMM:
3720                 case OP_STOREI4_MEMBASE_IMM:
3721                 case OP_STOREI8_MEMBASE_IMM:
3722                 case OP_STORE_MEMBASE_IMM: {
3723                         int size = 8;
3724                         LLVMValueRef index, addr;
3725                         LLVMTypeRef t;
3726                         gboolean sext = FALSE, zext = FALSE;
3727                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3728
3729                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3730
3731                         if (ins->inst_offset % size != 0) {
3732                                 /* Unaligned store */
3733                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3734                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3735                         } else {
3736                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
3737                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3738                         }
3739                         emit_store (ctx, bb, &builder, size, convert (ctx, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3740                         break;
3741                 }
3742
3743                 case OP_CHECK_THIS:
3744                         emit_load (ctx, bb, &builder, sizeof (gpointer), convert (ctx, lhs, LLVMPointerType (IntPtrType (), 0)), "", TRUE);
3745                         break;
3746                 case OP_OUTARG_VTRETADDR:
3747                         break;
3748                 case OP_VOIDCALL:
3749                 case OP_CALL:
3750                 case OP_LCALL:
3751                 case OP_FCALL:
3752                 case OP_RCALL:
3753                 case OP_VCALL:
3754                 case OP_VOIDCALL_MEMBASE:
3755                 case OP_CALL_MEMBASE:
3756                 case OP_LCALL_MEMBASE:
3757                 case OP_FCALL_MEMBASE:
3758                 case OP_RCALL_MEMBASE:
3759                 case OP_VCALL_MEMBASE:
3760                 case OP_VOIDCALL_REG:
3761                 case OP_CALL_REG:
3762                 case OP_LCALL_REG:
3763                 case OP_FCALL_REG:
3764                 case OP_RCALL_REG:
3765                 case OP_VCALL_REG: {
3766                         process_call (ctx, bb, &builder, ins);
3767                         CHECK_FAILURE (ctx);
3768                         break;
3769                 }
3770                 case OP_AOTCONST: {
3771                         guint32 got_offset;
3772                         LLVMValueRef indexes [2];
3773                         MonoJumpInfo *ji;
3774                         LLVMValueRef got_entry_addr;
3775
3776                         /* 
3777                          * FIXME: Can't allocate from the cfg mempool since that is freed if
3778                          * the LLVM compile fails.
3779                          */
3780                         ji = g_new0 (MonoJumpInfo, 1);
3781                         ji->type = (MonoJumpInfoType)ins->inst_i1;
3782                         ji->data.target = ins->inst_p0;
3783
3784                         ji = mono_aot_patch_info_dup (ji);
3785
3786                         ji->next = cfg->patch_info;
3787                         cfg->patch_info = ji;
3788                                    
3789                         //mono_add_patch_info (cfg, 0, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3790                         got_offset = mono_aot_get_got_offset (cfg->patch_info);
3791                         ctx->lmodule->max_got_offset = MAX (ctx->lmodule->max_got_offset, got_offset);
3792  
3793                         indexes [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3794                         indexes [1] = LLVMConstInt (LLVMInt32Type (), (gssize)got_offset, FALSE);
3795                         got_entry_addr = LLVMBuildGEP (builder, ctx->lmodule->got_var, indexes, 2, "");
3796
3797                         values [ins->dreg] = LLVMBuildLoad (builder, got_entry_addr, dname);
3798                         set_invariant_load_flag (values [ins->dreg]);
3799                         break;
3800                 }
3801                 case OP_NOT_REACHED:
3802                         LLVMBuildUnreachable (builder);
3803                         has_terminator = TRUE;
3804                         g_assert (bb->block_num < cfg->max_block_num);
3805                         ctx->unreachable [bb->block_num] = TRUE;
3806                         /* Might have instructions after this */
3807                         while (ins->next) {
3808                                 MonoInst *next = ins->next;
3809                                 /* 
3810                                  * FIXME: If later code uses the regs defined by these instructions,
3811                                  * compilation will fail.
3812                                  */
3813                                 MONO_DELETE_INS (bb, next);
3814                         }                               
3815                         break;
3816                 case OP_LDADDR: {
3817                         MonoInst *var = ins->inst_p0;
3818
3819                         if (var->opcode == OP_VTARG_ADDR) {
3820                                 /* The variable contains the vtype address */
3821                                 values [ins->dreg] = values [var->dreg];
3822                         } else {
3823                                 values [ins->dreg] = addresses [var->dreg];
3824                         }
3825                         break;
3826                 }
3827                 case OP_SIN: {
3828                         LLVMValueRef args [1];
3829
3830                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3831                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sin.f64"), args, 1, dname);
3832                         break;
3833                 }
3834                 case OP_COS: {
3835                         LLVMValueRef args [1];
3836
3837                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3838                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.cos.f64"), args, 1, dname);
3839                         break;
3840                 }
3841                 case OP_SQRT: {
3842                         LLVMValueRef args [1];
3843
3844 #if 0
3845                         /* This no longer seems to happen */
3846                         /*
3847                          * LLVM optimizes sqrt(nan) into undefined in
3848                          * lib/Analysis/ConstantFolding.cpp
3849                          * Also, sqrt(NegativeInfinity) is optimized into 0.
3850                          */
3851                         LLVM_FAILURE (ctx, "sqrt");
3852 #endif
3853                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3854                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sqrt.f64"), args, 1, dname);
3855                         break;
3856                 }
3857                 case OP_ABS: {
3858                         LLVMValueRef args [1];
3859
3860                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3861                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "fabs"), args, 1, dname);
3862                         break;
3863                 }
3864
3865                 case OP_IMIN:
3866                 case OP_LMIN:
3867                 case OP_IMAX:
3868                 case OP_LMAX:
3869                 case OP_IMIN_UN:
3870                 case OP_LMIN_UN:
3871                 case OP_IMAX_UN:
3872                 case OP_LMAX_UN: {
3873                         LLVMValueRef v;
3874
3875                         lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3876                         rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3877
3878                         switch (ins->opcode) {
3879                         case OP_IMIN:
3880                         case OP_LMIN:
3881                                 v = LLVMBuildICmp (builder, LLVMIntSLE, lhs, rhs, "");
3882                                 break;
3883                         case OP_IMAX:
3884                         case OP_LMAX:
3885                                 v = LLVMBuildICmp (builder, LLVMIntSGE, lhs, rhs, "");
3886                                 break;
3887                         case OP_IMIN_UN:
3888                         case OP_LMIN_UN:
3889                                 v = LLVMBuildICmp (builder, LLVMIntULE, lhs, rhs, "");
3890                                 break;
3891                         case OP_IMAX_UN:
3892                         case OP_LMAX_UN:
3893                                 v = LLVMBuildICmp (builder, LLVMIntUGE, lhs, rhs, "");
3894                                 break;
3895                         default:
3896                                 g_assert_not_reached ();
3897                                 break;
3898                         }
3899                         values [ins->dreg] = LLVMBuildSelect (builder, v, lhs, rhs, dname);
3900                         break;
3901                 }
3902                 case OP_ATOMIC_EXCHANGE_I4:
3903                 case OP_ATOMIC_EXCHANGE_I8: {
3904                         LLVMValueRef args [2];
3905                         LLVMTypeRef t;
3906                                 
3907                         if (ins->opcode == OP_ATOMIC_EXCHANGE_I4)
3908                                 t = LLVMInt32Type ();
3909                         else
3910                                 t = LLVMInt64Type ();
3911
3912                         g_assert (ins->inst_offset == 0);
3913
3914                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3915                         args [1] = convert (ctx, rhs, t);
3916
3917                         values [ins->dreg] = mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_XCHG, args [0], args [1]);
3918                         break;
3919                 }
3920                 case OP_ATOMIC_ADD_I4:
3921                 case OP_ATOMIC_ADD_I8: {
3922                         LLVMValueRef args [2];
3923                         LLVMTypeRef t;
3924                                 
3925                         if (ins->opcode == OP_ATOMIC_ADD_I4)
3926                                 t = LLVMInt32Type ();
3927                         else
3928                                 t = LLVMInt64Type ();
3929
3930                         g_assert (ins->inst_offset == 0);
3931
3932                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3933                         args [1] = convert (ctx, rhs, t);
3934                         values [ins->dreg] = LLVMBuildAdd (builder, mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_ADD, args [0], args [1]), args [1], dname);
3935                         break;
3936                 }
3937                 case OP_ATOMIC_CAS_I4:
3938                 case OP_ATOMIC_CAS_I8: {
3939                         LLVMValueRef args [3], val;
3940                         LLVMTypeRef t;
3941                                 
3942                         if (ins->opcode == OP_ATOMIC_CAS_I4)
3943                                 t = LLVMInt32Type ();
3944                         else
3945                                 t = LLVMInt64Type ();
3946
3947                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3948                         /* comparand */
3949                         args [1] = convert (ctx, values [ins->sreg3], t);
3950                         /* new value */
3951                         args [2] = convert (ctx, values [ins->sreg2], t);
3952                         val = mono_llvm_build_cmpxchg (builder, args [0], args [1], args [2]);
3953                         /* cmpxchg returns a pair */
3954                         values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, "");
3955                         break;
3956                 }
3957                 case OP_MEMORY_BARRIER: {
3958                         mono_llvm_build_fence (builder, (BarrierKind) ins->backend.memory_barrier_kind);
3959                         break;
3960                 }
3961                 case OP_ATOMIC_LOAD_I1:
3962                 case OP_ATOMIC_LOAD_I2:
3963                 case OP_ATOMIC_LOAD_I4:
3964                 case OP_ATOMIC_LOAD_I8:
3965                 case OP_ATOMIC_LOAD_U1:
3966                 case OP_ATOMIC_LOAD_U2:
3967                 case OP_ATOMIC_LOAD_U4:
3968                 case OP_ATOMIC_LOAD_U8:
3969                 case OP_ATOMIC_LOAD_R4:
3970                 case OP_ATOMIC_LOAD_R8: {
3971                         LLVM_FAILURE (ctx, "atomic mono.load intrinsic");
3972
3973                         int size;
3974                         gboolean sext, zext;
3975                         LLVMTypeRef t;
3976                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3977                         BarrierKind barrier = (BarrierKind) ins->backend.memory_barrier_kind;
3978                         LLVMValueRef index, addr;
3979
3980                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3981
3982                         if (sext || zext)
3983                                 dname = (char *)"";
3984
3985                         if (ins->inst_offset != 0) {
3986                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3987                                 addr = LLVMBuildGEP (builder, convert (ctx, lhs, LLVMPointerType (t, 0)), &index, 1, "");
3988                         } else {
3989                                 addr = lhs;
3990                         }
3991
3992                         addr = convert (ctx, addr, LLVMPointerType (t, 0));
3993
3994                         values [ins->dreg] = emit_load_general (ctx, bb, &builder, size, addr, dname, is_volatile, barrier);
3995
3996                         if (sext)
3997                                 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3998                         else if (zext)
3999                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
4000                         break;
4001                 }
4002                 case OP_ATOMIC_STORE_I1:
4003                 case OP_ATOMIC_STORE_I2:
4004                 case OP_ATOMIC_STORE_I4:
4005                 case OP_ATOMIC_STORE_I8:
4006                 case OP_ATOMIC_STORE_U1:
4007                 case OP_ATOMIC_STORE_U2:
4008                 case OP_ATOMIC_STORE_U4:
4009                 case OP_ATOMIC_STORE_U8:
4010                 case OP_ATOMIC_STORE_R4:
4011                 case OP_ATOMIC_STORE_R8: {
4012                         LLVM_FAILURE (ctx, "atomic mono.load intrinsic");
4013
4014                         int size;
4015                         gboolean sext, zext;
4016                         LLVMTypeRef t;
4017                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
4018                         BarrierKind barrier = (BarrierKind) ins->backend.memory_barrier_kind;
4019                         LLVMValueRef index, addr, value;
4020
4021                         if (!values [ins->inst_destbasereg])
4022                                 LLVM_FAILURE (ctx, "inst_destbasereg");
4023
4024                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
4025
4026                         index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
4027                         addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
4028                         value = convert (ctx, values [ins->sreg1], t);
4029
4030                         emit_store_general (ctx, bb, &builder, size, value, addr, is_volatile, barrier);
4031                         break;
4032                 }
4033                 case OP_RELAXED_NOP: {
4034 #if defined(TARGET_AMD64) || defined(TARGET_X86)
4035                         emit_call (ctx, bb, &builder, LLVMGetNamedFunction (ctx->module, "llvm.x86.sse2.pause"), NULL, 0);
4036                         break;
4037 #else
4038                         break;
4039 #endif
4040                 }
4041                 case OP_TLS_GET: {
4042 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(__linux__)
4043 #ifdef TARGET_AMD64
4044                         // 257 == FS segment register
4045                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 257);
4046 #else
4047                         // 256 == GS segment register
4048                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
4049 #endif
4050                         // FIXME: XEN
4051                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), ins->inst_offset, TRUE), ptrtype, ""), "");
4052 #elif defined(TARGET_AMD64) && defined(TARGET_OSX)
4053                         /* See mono_amd64_emit_tls_get () */
4054                         int offset = mono_amd64_get_tls_gs_offset () + (ins->inst_offset * 8);
4055
4056                         // 256 == GS segment register
4057                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
4058                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), offset, TRUE), ptrtype, ""), "");
4059 #else
4060                         LLVM_FAILURE (ctx, "opcode tls-get");
4061 #endif
4062
4063                         break;
4064                 }
4065                 case OP_TLS_GET_REG: {
4066 #if defined(TARGET_AMD64) && defined(TARGET_OSX)
4067                         /* See emit_tls_get_reg () */
4068                         // 256 == GS segment register
4069                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
4070                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, convert (ctx, lhs, LLVMInt32Type ()), ptrtype, ""), "");
4071 #else
4072                         LLVM_FAILURE (ctx, "opcode tls-get");
4073 #endif
4074                         break;
4075                 }
4076
4077                         /*
4078                          * Overflow opcodes.
4079                          */
4080                 case OP_IADD_OVF:
4081                 case OP_IADD_OVF_UN:
4082                 case OP_ISUB_OVF:
4083                 case OP_ISUB_OVF_UN:
4084                 case OP_IMUL_OVF:
4085                 case OP_IMUL_OVF_UN:
4086 #if SIZEOF_VOID_P == 8
4087                 case OP_LADD_OVF:
4088                 case OP_LADD_OVF_UN:
4089                 case OP_LSUB_OVF:
4090                 case OP_LSUB_OVF_UN:
4091                 case OP_LMUL_OVF:
4092                 case OP_LMUL_OVF_UN:
4093 #endif
4094                         {
4095                                 LLVMValueRef args [2], val, ovf, func;
4096
4097                                 args [0] = convert (ctx, lhs, op_to_llvm_type (ins->opcode));
4098                                 args [1] = convert (ctx, rhs, op_to_llvm_type (ins->opcode));
4099                                 func = LLVMGetNamedFunction (module, ovf_op_to_intrins (ins->opcode));
4100                                 g_assert (func);
4101                                 val = LLVMBuildCall (builder, func, args, 2, "");
4102                                 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, dname);
4103                                 ovf = LLVMBuildExtractValue (builder, val, 1, "");
4104                                 emit_cond_system_exception (ctx, bb, "OverflowException", ovf);
4105                                 CHECK_FAILURE (ctx);
4106                                 builder = ctx->builder;
4107                                 break;
4108                         }
4109
4110                         /* 
4111                          * Valuetypes.
4112                          *   We currently model them using arrays. Promotion to local vregs is 
4113                          * disabled for them in mono_handle_global_vregs () in the LLVM case, 
4114                          * so we always have an entry in cfg->varinfo for them.
4115                          * FIXME: Is this needed ?
4116                          */
4117                 case OP_VZERO: {
4118                         MonoClass *klass = ins->klass;
4119                         LLVMValueRef args [5];
4120
4121                         if (!klass) {
4122                                 // FIXME:
4123                                 LLVM_FAILURE (ctx, "!klass");
4124                                 break;
4125                         }
4126
4127                         if (!addresses [ins->dreg])
4128                                 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
4129                         args [0] = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
4130                         args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
4131                         args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
4132                         // FIXME: Alignment
4133                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
4134                         args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
4135                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
4136                         break;
4137                 }
4138                 case OP_DUMMY_VZERO:
4139                         break;
4140
4141                 case OP_STOREV_MEMBASE:
4142                 case OP_LOADV_MEMBASE:
4143                 case OP_VMOVE: {
4144                         MonoClass *klass = ins->klass;
4145                         LLVMValueRef src = NULL, dst, args [5];
4146                         gboolean done = FALSE;
4147
4148                         if (!klass) {
4149                                 // FIXME:
4150                                 LLVM_FAILURE (ctx, "!klass");
4151                                 break;
4152                         }
4153
4154                         if (mini_is_gsharedvt_klass (klass)) {
4155                                 // FIXME:
4156                                 LLVM_FAILURE (ctx, "gsharedvt");
4157                                 break;
4158                         }
4159
4160                         switch (ins->opcode) {
4161                         case OP_STOREV_MEMBASE:
4162                                 if (cfg->gen_write_barriers && klass->has_references && ins->inst_destbasereg != cfg->frame_reg &&
4163                                         LLVMGetInstructionOpcode (values [ins->inst_destbasereg]) != LLVMAlloca) {
4164                                         /* Decomposed earlier */
4165                                         g_assert_not_reached ();
4166                                         break;
4167                                 }
4168                                 if (!addresses [ins->sreg1]) {
4169                                         /* SIMD */
4170                                         g_assert (values [ins->sreg1]);
4171                                         dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (type_to_llvm_type (ctx, &klass->byval_arg), 0));
4172                                         LLVMBuildStore (builder, values [ins->sreg1], dst);
4173                                         done = TRUE;
4174                                 } else {
4175                                         src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
4176                                         dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
4177                                 }
4178                                 break;
4179                         case OP_LOADV_MEMBASE:
4180                                 if (!addresses [ins->dreg])
4181                                         addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
4182                                 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
4183                                 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
4184                                 break;
4185                         case OP_VMOVE:
4186                                 if (!addresses [ins->sreg1])
4187                                         addresses [ins->sreg1] = build_alloca (ctx, &klass->byval_arg);
4188                                 if (!addresses [ins->dreg])
4189                                         addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
4190                                 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
4191                                 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
4192                                 break;
4193                         default:
4194                                 g_assert_not_reached ();
4195                         }
4196                         CHECK_FAILURE (ctx);
4197
4198                         if (done)
4199                                 break;
4200
4201                         args [0] = dst;
4202                         args [1] = src;
4203                         args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
4204                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
4205                         // FIXME: Alignment
4206                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
4207                         args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
4208                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
4209                         break;
4210                 }
4211                 case OP_LLVM_OUTARG_VT:
4212                         if (!addresses [ins->sreg1]) {
4213                                 addresses [ins->sreg1] = build_alloca (ctx, &ins->klass->byval_arg);
4214                                 g_assert (values [ins->sreg1]);
4215                                 LLVMBuildStore (builder, values [ins->sreg1], addresses [ins->sreg1]);
4216                         }
4217                         addresses [ins->dreg] = addresses [ins->sreg1];
4218                         break;
4219
4220                         /* 
4221                          * SIMD
4222                          */
4223 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4224                 case OP_XZERO: {
4225                         values [ins->dreg] = LLVMConstNull (type_to_llvm_type (ctx, &ins->klass->byval_arg));
4226                         break;
4227                 }
4228                 case OP_LOADX_MEMBASE: {
4229                         LLVMTypeRef t = type_to_llvm_type (ctx, &ins->klass->byval_arg);
4230                         LLVMValueRef src;
4231
4232                         src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
4233                         values [ins->dreg] = mono_llvm_build_aligned_load (builder, src, "", FALSE, 1);
4234                         break;
4235                 }
4236                 case OP_STOREX_MEMBASE: {
4237                         LLVMTypeRef t = LLVMTypeOf (values [ins->sreg1]);
4238                         LLVMValueRef dest;
4239
4240                         dest = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
4241                         mono_llvm_build_aligned_store (builder, values [ins->sreg1], dest, FALSE, 1);
4242                         break;
4243                 }
4244                 case OP_PADDB:
4245                 case OP_PADDW:
4246                 case OP_PADDD:
4247                 case OP_PADDQ:
4248                         values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, "");
4249                         break;
4250                 case OP_ADDPD:
4251                 case OP_ADDPS:
4252                         values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, "");
4253                         break;
4254                 case OP_PSUBB:
4255                 case OP_PSUBW:
4256                 case OP_PSUBD:
4257                 case OP_PSUBQ:
4258                         values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, "");
4259                         break;
4260                 case OP_SUBPD:
4261                 case OP_SUBPS:
4262                         values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, "");
4263                         break;
4264                 case OP_MULPD:
4265                 case OP_MULPS:
4266                         values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, "");
4267                         break;
4268                 case OP_DIVPD:
4269                 case OP_DIVPS:
4270                         values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, "");
4271                         break;
4272                 case OP_PAND:
4273                         values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, "");
4274                         break;
4275                 case OP_POR:
4276                         values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, "");
4277                         break;
4278                 case OP_PXOR:
4279                         values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, "");
4280                         break;
4281                 case OP_PMULW:
4282                 case OP_PMULD:
4283                         values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, "");
4284                         break;
4285                 case OP_ANDPS:
4286                 case OP_ANDNPS:
4287                 case OP_ORPS:
4288                 case OP_XORPS:
4289                 case OP_ANDPD:
4290                 case OP_ANDNPD:
4291                 case OP_ORPD:
4292                 case OP_XORPD: {
4293                         LLVMTypeRef t, rt;
4294                         LLVMValueRef v = NULL;
4295
4296                         switch (ins->opcode) {
4297                         case OP_ANDPS:
4298                         case OP_ANDNPS:
4299                         case OP_ORPS:
4300                         case OP_XORPS:
4301                                 t = LLVMVectorType (LLVMInt32Type (), 4);
4302                                 rt = LLVMVectorType (LLVMFloatType (), 4);
4303                                 break;
4304                         case OP_ANDPD:
4305                         case OP_ANDNPD:
4306                         case OP_ORPD:
4307                         case OP_XORPD:
4308                                 t = LLVMVectorType (LLVMInt64Type (), 2);
4309                                 rt = LLVMVectorType (LLVMDoubleType (), 2);
4310                                 break;
4311                         default:
4312                                 t = LLVMInt32Type ();
4313                                 rt = LLVMInt32Type ();
4314                                 g_assert_not_reached ();
4315                         }
4316
4317                         lhs = LLVMBuildBitCast (builder, lhs, t, "");
4318                         rhs = LLVMBuildBitCast (builder, rhs, t, "");
4319                         switch (ins->opcode) {
4320                         case OP_ANDPS:
4321                         case OP_ANDPD:
4322                                 v = LLVMBuildAnd (builder, lhs, rhs, "");
4323                                 break;
4324                         case OP_ORPS:
4325                         case OP_ORPD:
4326                                 v = LLVMBuildOr (builder, lhs, rhs, "");
4327                                 break;
4328                         case OP_XORPS:
4329                         case OP_XORPD:
4330                                 v = LLVMBuildXor (builder, lhs, rhs, "");
4331                                 break;
4332                         case OP_ANDNPS:
4333                         case OP_ANDNPD:
4334                                 v = LLVMBuildAnd (builder, rhs, LLVMBuildNot (builder, lhs, ""), "");
4335                                 break;
4336                         }
4337                         values [ins->dreg] = LLVMBuildBitCast (builder, v, rt, "");
4338                         break;
4339                 }
4340                 case OP_MINPD:
4341                 case OP_MINPS:
4342                 case OP_MAXPD:
4343                 case OP_MAXPS:
4344                 case OP_ADDSUBPD:
4345                 case OP_ADDSUBPS:
4346                 case OP_PMIND_UN:
4347                 case OP_PMINW_UN:
4348                 case OP_PMINB_UN:
4349                 case OP_PMINW:
4350                 case OP_PMAXD_UN:
4351                 case OP_PMAXW_UN:
4352                 case OP_PMAXB_UN:
4353                 case OP_HADDPD:
4354                 case OP_HADDPS:
4355                 case OP_HSUBPD:
4356                 case OP_HSUBPS:
4357                 case OP_PADDB_SAT:
4358                 case OP_PADDW_SAT:
4359                 case OP_PSUBB_SAT:
4360                 case OP_PSUBW_SAT:
4361                 case OP_PADDB_SAT_UN:
4362                 case OP_PADDW_SAT_UN:
4363                 case OP_PSUBB_SAT_UN:
4364                 case OP_PSUBW_SAT_UN:
4365                 case OP_PAVGB_UN:
4366                 case OP_PAVGW_UN:
4367                 case OP_PACKW:
4368                 case OP_PACKD:
4369                 case OP_PACKW_UN:
4370                 case OP_PACKD_UN:
4371                 case OP_PMULW_HIGH:
4372                 case OP_PMULW_HIGH_UN: {
4373                         LLVMValueRef args [2];
4374
4375                         args [0] = lhs;
4376                         args [1] = rhs;
4377
4378                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4379                         break;
4380                 }
4381                 case OP_PCMPEQB:
4382                 case OP_PCMPEQW:
4383                 case OP_PCMPEQD:
4384                 case OP_PCMPEQQ: {
4385                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntEQ, lhs, rhs, ""), LLVMTypeOf (lhs), "");
4386                         break;
4387                 }
4388                 case OP_PCMPGTB: {
4389                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntSGT, lhs, rhs, ""), LLVMTypeOf (lhs), "");
4390                         break;
4391                 }
4392                 case OP_EXTRACT_R8:
4393                 case OP_EXTRACT_I8:
4394                 case OP_EXTRACT_I4:
4395                 case OP_EXTRACT_I2:
4396                 case OP_EXTRACT_U2:
4397                 case OP_EXTRACTX_U2:
4398                 case OP_EXTRACT_I1:
4399                 case OP_EXTRACT_U1: {
4400                         LLVMTypeRef t;
4401                         gboolean zext = FALSE;
4402
4403                         t = simd_op_to_llvm_type (ins->opcode);
4404
4405                         switch (ins->opcode) {
4406                         case OP_EXTRACT_R8:
4407                         case OP_EXTRACT_I8:
4408                         case OP_EXTRACT_I4:
4409                         case OP_EXTRACT_I2:
4410                         case OP_EXTRACT_I1:
4411                                 break;
4412                         case OP_EXTRACT_U2:
4413                         case OP_EXTRACTX_U2:
4414                         case OP_EXTRACT_U1:
4415                                 zext = TRUE;
4416                                 break;
4417                         default:
4418                                 t = LLVMInt32Type ();
4419                                 g_assert_not_reached ();
4420                         }
4421
4422                         lhs = LLVMBuildBitCast (builder, lhs, t, "");
4423                         values [ins->dreg] = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), "");
4424                         if (zext)
4425                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), "");
4426                         break;
4427                 }
4428
4429                 case OP_EXPAND_I1:
4430                 case OP_EXPAND_I2:
4431                 case OP_EXPAND_I4:
4432                 case OP_EXPAND_I8:
4433                 case OP_EXPAND_R4:
4434                 case OP_EXPAND_R8: {
4435                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4436                         LLVMValueRef mask [16], v;
4437                         int i;
4438
4439                         for (i = 0; i < 16; ++i)
4440                                 mask [i] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
4441
4442                         v = convert (ctx, values [ins->sreg1], LLVMGetElementType (t));
4443
4444                         values [ins->dreg] = LLVMBuildInsertElement (builder, LLVMConstNull (t), v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4445                         values [ins->dreg] = LLVMBuildShuffleVector (builder, values [ins->dreg], LLVMGetUndef (t), LLVMConstVector (mask, LLVMGetVectorSize (t)), "");
4446                         break;
4447                 }
4448
4449                 case OP_INSERT_I1:
4450                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt8Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4451                         break;
4452                 case OP_INSERT_I2:
4453                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt16Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4454                         break;
4455                 case OP_INSERT_I4:
4456                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4457                         break;
4458                 case OP_INSERT_I8:
4459                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt64Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4460                         break;
4461                 case OP_INSERT_R4:
4462                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMFloatType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4463                         break;
4464                 case OP_INSERT_R8:
4465                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMDoubleType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
4466                         break;
4467
4468                 case OP_CVTDQ2PD:
4469                 case OP_CVTDQ2PS:
4470                 case OP_CVTPD2DQ:
4471                 case OP_CVTPS2DQ:
4472                 case OP_CVTPD2PS:
4473                 case OP_CVTPS2PD:
4474                 case OP_CVTTPD2DQ:
4475                 case OP_CVTTPS2DQ:
4476                 case OP_EXTRACT_MASK:
4477                 case OP_SQRTPS:
4478                 case OP_SQRTPD:
4479                 case OP_RSQRTPS:
4480                 case OP_RCPPS: {
4481                         LLVMValueRef v;
4482
4483                         v = convert (ctx, values [ins->sreg1], simd_op_to_llvm_type (ins->opcode));
4484
4485                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), &v, 1, dname);
4486                         break;
4487                 }
4488
4489                 case OP_COMPPS:
4490                 case OP_COMPPD: {
4491                         LLVMValueRef args [3];
4492
4493                         args [0] = lhs;
4494                         args [1] = rhs;
4495                         args [2] = LLVMConstInt (LLVMInt8Type (), ins->inst_c0, FALSE);
4496
4497                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 3, dname);
4498                         break;
4499                 }
4500
4501                 case OP_ICONV_TO_X:
4502                         /* This is only used for implementing shifts by non-immediate */
4503                         values [ins->dreg] = lhs;
4504                         break;
4505
4506                 case OP_PSHRW:
4507                 case OP_PSHRD:
4508                 case OP_PSHRQ:
4509                 case OP_PSARW:
4510                 case OP_PSARD:
4511                 case OP_PSHLW:
4512                 case OP_PSHLD:
4513                 case OP_PSHLQ: {
4514                         LLVMValueRef args [3];
4515
4516                         args [0] = lhs;
4517                         args [1] = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
4518
4519                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4520                         break;
4521                 }
4522
4523                 case OP_PSHRW_REG:
4524                 case OP_PSHRD_REG:
4525                 case OP_PSHRQ_REG:
4526                 case OP_PSARW_REG:
4527                 case OP_PSARD_REG:
4528                 case OP_PSHLW_REG:
4529                 case OP_PSHLD_REG:
4530                 case OP_PSHLQ_REG: {
4531                         LLVMValueRef args [3];
4532
4533                         args [0] = lhs;
4534                         args [1] = values [ins->sreg2];
4535
4536                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
4537                         break;
4538                 }
4539
4540                 case OP_SHUFPS:
4541                 case OP_SHUFPD:
4542                 case OP_PSHUFLED:
4543                 case OP_PSHUFLEW_LOW:
4544                 case OP_PSHUFLEW_HIGH: {
4545                         int mask [16];
4546                         LLVMValueRef v1 = NULL, v2 = NULL, mask_values [16];
4547                         int i, mask_size = 0;
4548                         int imask = ins->inst_c0;
4549         
4550                         /* Convert the x86 shuffle mask to LLVM's */
4551                         switch (ins->opcode) {
4552                         case OP_SHUFPS:
4553                                 mask_size = 4;
4554                                 mask [0] = ((imask >> 0) & 3);
4555                                 mask [1] = ((imask >> 2) & 3);
4556                                 mask [2] = ((imask >> 4) & 3) + 4;
4557                                 mask [3] = ((imask >> 6) & 3) + 4;
4558                                 v1 = values [ins->sreg1];
4559                                 v2 = values [ins->sreg2];
4560                                 break;
4561                         case OP_SHUFPD:
4562                                 mask_size = 2;
4563                                 mask [0] = ((imask >> 0) & 1);
4564                                 mask [1] = ((imask >> 1) & 1) + 2;
4565                                 v1 = values [ins->sreg1];
4566                                 v2 = values [ins->sreg2];
4567                                 break;
4568                         case OP_PSHUFLEW_LOW:
4569                                 mask_size = 8;
4570                                 mask [0] = ((imask >> 0) & 3);
4571                                 mask [1] = ((imask >> 2) & 3);
4572                                 mask [2] = ((imask >> 4) & 3);
4573                                 mask [3] = ((imask >> 6) & 3);
4574                                 mask [4] = 4 + 0;
4575                                 mask [5] = 4 + 1;
4576                                 mask [6] = 4 + 2;
4577                                 mask [7] = 4 + 3;
4578                                 v1 = values [ins->sreg1];
4579                                 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4580                                 break;
4581                         case OP_PSHUFLEW_HIGH:
4582                                 mask_size = 8;
4583                                 mask [0] = 0;
4584                                 mask [1] = 1;
4585                                 mask [2] = 2;
4586                                 mask [3] = 3;
4587                                 mask [4] = 4 + ((imask >> 0) & 3);
4588                                 mask [5] = 4 + ((imask >> 2) & 3);
4589                                 mask [6] = 4 + ((imask >> 4) & 3);
4590                                 mask [7] = 4 + ((imask >> 6) & 3);
4591                                 v1 = values [ins->sreg1];
4592                                 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4593                                 break;
4594                         case OP_PSHUFLED:
4595                                 mask_size = 4;
4596                                 mask [0] = ((imask >> 0) & 3);
4597                                 mask [1] = ((imask >> 2) & 3);
4598                                 mask [2] = ((imask >> 4) & 3);
4599                                 mask [3] = ((imask >> 6) & 3);
4600                                 v1 = values [ins->sreg1];
4601                                 v2 = LLVMGetUndef (LLVMTypeOf (v1));
4602                                 break;
4603                         default:
4604                                 g_assert_not_reached ();
4605                         }
4606                         for (i = 0; i < mask_size; ++i)
4607                                 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4608
4609                         values [ins->dreg] =
4610                                 LLVMBuildShuffleVector (builder, v1, v2,
4611                                                                                 LLVMConstVector (mask_values, mask_size), dname);
4612                         break;
4613                 }
4614
4615                 case OP_UNPACK_LOWB:
4616                 case OP_UNPACK_LOWW:
4617                 case OP_UNPACK_LOWD:
4618                 case OP_UNPACK_LOWQ:
4619                 case OP_UNPACK_LOWPS:
4620                 case OP_UNPACK_LOWPD:
4621                 case OP_UNPACK_HIGHB:
4622                 case OP_UNPACK_HIGHW:
4623                 case OP_UNPACK_HIGHD:
4624                 case OP_UNPACK_HIGHQ:
4625                 case OP_UNPACK_HIGHPS:
4626                 case OP_UNPACK_HIGHPD: {
4627                         int mask [16];
4628                         LLVMValueRef mask_values [16];
4629                         int i, mask_size = 0;
4630                         gboolean low = FALSE;
4631
4632                         switch (ins->opcode) {
4633                         case OP_UNPACK_LOWB:
4634                                 mask_size = 16;
4635                                 low = TRUE;
4636                                 break;
4637                         case OP_UNPACK_LOWW:
4638                                 mask_size = 8;
4639                                 low = TRUE;
4640                                 break;
4641                         case OP_UNPACK_LOWD:
4642                         case OP_UNPACK_LOWPS:
4643                                 mask_size = 4;
4644                                 low = TRUE;
4645                                 break;
4646                         case OP_UNPACK_LOWQ:
4647                         case OP_UNPACK_LOWPD:
4648                                 mask_size = 2;
4649                                 low = TRUE;
4650                                 break;
4651                         case OP_UNPACK_HIGHB:
4652                                 mask_size = 16;
4653                                 break;
4654                         case OP_UNPACK_HIGHW:
4655                                 mask_size = 8;
4656                                 break;
4657                         case OP_UNPACK_HIGHD:
4658                         case OP_UNPACK_HIGHPS:
4659                                 mask_size = 4;
4660                                 break;
4661                         case OP_UNPACK_HIGHQ:
4662                         case OP_UNPACK_HIGHPD:
4663                                 mask_size = 2;
4664                                 break;
4665                         default:
4666                                 g_assert_not_reached ();
4667                         }
4668
4669                         if (low) {
4670                                 for (i = 0; i < (mask_size / 2); ++i) {
4671                                         mask [(i * 2)] = i;
4672                                         mask [(i * 2) + 1] = mask_size + i;
4673                                 }
4674                         } else {
4675                                 for (i = 0; i < (mask_size / 2); ++i) {
4676                                         mask [(i * 2)] = (mask_size / 2) + i;
4677                                         mask [(i * 2) + 1] = mask_size + (mask_size / 2) + i;
4678                                 }
4679                         }
4680
4681                         for (i = 0; i < mask_size; ++i)
4682                                 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4683                         
4684                         values [ins->dreg] =
4685                                 LLVMBuildShuffleVector (builder, values [ins->sreg1], values [ins->sreg2],
4686                                                                                 LLVMConstVector (mask_values, mask_size), dname);
4687                         break;
4688                 }
4689
4690                 case OP_DUPPD: {
4691                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4692                         LLVMValueRef v, val;
4693
4694                         v = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4695                         val = LLVMConstNull (t);
4696                         val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4697                         val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 1, FALSE), dname);
4698
4699                         values [ins->dreg] = val;
4700                         break;
4701                 }
4702                 case OP_DUPPS_LOW:
4703                 case OP_DUPPS_HIGH: {
4704                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4705                         LLVMValueRef v1, v2, val;
4706                         
4707
4708                         if (ins->opcode == OP_DUPPS_LOW) {
4709                                 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4710                                 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4711                         } else {
4712                                 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4713                                 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4714                         }
4715                         val = LLVMConstNull (t);
4716                         val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4717                         val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4718                         val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4719                         val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4720                         
4721                         values [ins->dreg] = val;
4722                         break;
4723                 }
4724
4725 #endif /* SIMD */
4726
4727                 case OP_DUMMY_USE:
4728                         break;
4729
4730                         /*
4731                          * EXCEPTION HANDLING
4732                          */
4733                 case OP_IMPLICIT_EXCEPTION:
4734                         /* This marks a place where an implicit exception can happen */
4735                         if (bb->region != -1)
4736                                 LLVM_FAILURE (ctx, "implicit-exception");
4737                         break;
4738                 case OP_THROW:
4739                 case OP_RETHROW: {
4740                         MonoMethodSignature *throw_sig;
4741                         LLVMValueRef callee, arg;
4742                         gboolean rethrow = (ins->opcode == OP_RETHROW);
4743                         const char *icall_name;
4744                                 
4745                         callee = rethrow ? ctx->lmodule->rethrow : ctx->lmodule->throw;
4746                         icall_name = rethrow ? "mono_arch_rethrow_exception" : "mono_arch_throw_exception";
4747
4748                         if (!callee) {
4749                                 throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 1);
4750                                 throw_sig->ret = &mono_get_void_class ()->byval_arg;
4751                                 throw_sig->params [0] = &mono_get_object_class ()->byval_arg;
4752                                 if (cfg->compile_aot) {
4753                                         callee = get_plt_entry (ctx, sig_to_llvm_sig (ctx, throw_sig), MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
4754                                 } else {
4755                                         callee = LLVMAddFunction (module, icall_name, sig_to_llvm_sig (ctx, throw_sig));
4756
4757 #ifdef TARGET_X86
4758                                         /* 
4759                                          * LLVM doesn't push the exception argument, so we need a different
4760                                          * trampoline.
4761                                          */
4762                                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, rethrow ? "llvm_rethrow_exception_trampoline" : "llvm_throw_exception_trampoline"));
4763 #else
4764                                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
4765 #endif
4766                                 }
4767
4768                                 mono_memory_barrier ();
4769                                 if (rethrow)
4770                                         ctx->lmodule->rethrow = callee;
4771                                 else
4772                                         ctx->lmodule->throw = callee;
4773                         }
4774                         arg = convert (ctx, lhs, type_to_llvm_type (ctx, &mono_get_object_class ()->byval_arg));
4775                         emit_call (ctx, bb, &builder, callee, &arg, 1);
4776                         break;
4777                 }
4778                 case OP_CALL_HANDLER: {
4779                         /* 
4780                          * We don't 'call' handlers, but instead simply branch to them.
4781                          * The code generated by ENDFINALLY will branch back to us.
4782                          */
4783                         LLVMBasicBlockRef noex_bb;
4784                         GSList *bb_list;
4785                         BBInfo *info = &bblocks [ins->inst_target_bb->block_num];
4786
4787                         bb_list = info->call_handler_return_bbs;
4788
4789                         /* 
4790                          * Set the indicator variable for the finally clause.
4791                          */
4792                         lhs = info->finally_ind;
4793                         g_assert (lhs);
4794                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), g_slist_length (bb_list) + 1, FALSE), lhs);
4795                                 
4796                         /* Branch to the finally clause */
4797                         LLVMBuildBr (builder, info->call_handler_target_bb);
4798
4799                         noex_bb = gen_bb (ctx, "CALL_HANDLER_CONT_BB");
4800                         info->call_handler_return_bbs = g_slist_append_mempool (cfg->mempool, info->call_handler_return_bbs, noex_bb);
4801
4802                         builder = ctx->builder = create_builder (ctx);
4803                         LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
4804
4805                         bblocks [bb->block_num].end_bblock = noex_bb;
4806                         break;
4807                 }
4808                 case OP_START_HANDLER: {
4809                         break;
4810                 }
4811                 case OP_ENDFINALLY: {
4812                         LLVMBasicBlockRef resume_bb;
4813                         MonoBasicBlock *handler_bb;
4814                         LLVMValueRef val, switch_ins, callee;
4815                         GSList *bb_list;
4816                         BBInfo *info;
4817
4818                         handler_bb = g_hash_table_lookup (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)));
4819                         g_assert (handler_bb);
4820                         info = &bblocks [handler_bb->block_num];
4821                         lhs = info->finally_ind;
4822                         g_assert (lhs);
4823
4824                         bb_list = info->call_handler_return_bbs;
4825
4826                         resume_bb = gen_bb (ctx, "ENDFINALLY_RESUME_BB");
4827
4828                         /* Load the finally variable */
4829                         val = LLVMBuildLoad (builder, lhs, "");
4830
4831                         /* Reset the variable */
4832                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), lhs);
4833
4834                         /* Branch to either resume_bb, or to the bblocks in bb_list */
4835                         switch_ins = LLVMBuildSwitch (builder, val, resume_bb, g_slist_length (bb_list));
4836                         /* 
4837                          * The other targets are added at the end to handle OP_CALL_HANDLER
4838                          * opcodes processed later.
4839                          */
4840                         info->endfinally_switch_ins_list = g_slist_append_mempool (cfg->mempool, info->endfinally_switch_ins_list, switch_ins);
4841
4842                         builder = ctx->builder = create_builder (ctx);
4843                         LLVMPositionBuilderAtEnd (ctx->builder, resume_bb);
4844
4845                         if (ctx->cfg->compile_aot) {
4846                                 callee = get_plt_entry (ctx, LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE), MONO_PATCH_INFO_INTERNAL_METHOD, "llvm_resume_unwind_trampoline");
4847                         } else {
4848                                 callee = LLVMGetNamedFunction (module, "llvm_resume_unwind_trampoline");
4849                         }
4850                         LLVMBuildCall (builder, callee, NULL, 0, "");
4851
4852                         LLVMBuildUnreachable (builder);
4853                         has_terminator = TRUE;
4854                         break;
4855                 }
4856                 default: {
4857                         char reason [128];
4858
4859                         sprintf (reason, "opcode %s", mono_inst_name (ins->opcode));
4860                         LLVM_FAILURE (ctx, reason);
4861                         break;
4862                 }
4863                 }
4864
4865                 /* Convert the value to the type required by phi nodes */
4866                 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
4867                         if (!values [ins->dreg])
4868                                 /* vtypes */
4869                                 values [ins->dreg] = addresses [ins->dreg];
4870                         else
4871                                 values [ins->dreg] = convert (ctx, values [ins->dreg], ctx->vreg_types [ins->dreg]);
4872                 }
4873
4874                 /* Add stores for volatile variables */
4875                 if (spec [MONO_INST_DEST] != ' ' && spec [MONO_INST_DEST] != 'v' && !MONO_IS_STORE_MEMBASE (ins))
4876                         emit_volatile_store (ctx, ins->dreg);
4877         }
4878
4879         if (!has_terminator && bb->next_bb && (bb == cfg->bb_entry || bb->in_count > 0))
4880                 LLVMBuildBr (builder, get_bb (ctx, bb->next_bb));
4881
4882         if (bb == cfg->bb_exit && sig->ret->type == MONO_TYPE_VOID) {
4883                 emit_dbg_loc (ctx, builder, cfg->header->code + cfg->header->code_size - 1);
4884                 LLVMBuildRetVoid (builder);
4885         }
4886
4887         if (bb == cfg->bb_entry)
4888                 ctx->last_alloca = LLVMGetLastInstruction (get_bb (ctx, cfg->bb_entry));
4889
4890         return;
4891
4892  FAILURE:
4893         return;
4894 }
4895
4896 /*
4897  * mono_llvm_check_method_supported:
4898  *
4899  *   Do some quick checks to decide whenever cfg->method can be compiled by LLVM, to avoid
4900  * compiling a method twice.
4901  */
4902 void
4903 mono_llvm_check_method_supported (MonoCompile *cfg)
4904 {
4905         int i, j;
4906
4907         if (cfg->method->save_lmf) {
4908                 cfg->exception_message = g_strdup ("lmf");
4909                 cfg->disable_llvm = TRUE;
4910         }
4911         if (cfg->disable_llvm)
4912                 return;
4913
4914         /*
4915          * Nested clauses where one of the clauses is a finally clause is
4916          * not supported, because LLVM can't figure out the control flow,
4917          * probably because we resume exception handling by calling our
4918          * own function instead of using the 'resume' llvm instruction.
4919          */
4920         for (i = 0; i < cfg->header->num_clauses; ++i) {
4921                 for (j = 0; j < cfg->header->num_clauses; ++j) {
4922                         MonoExceptionClause *clause1 = &cfg->header->clauses [i];
4923                         MonoExceptionClause *clause2 = &cfg->header->clauses [j];
4924
4925                         if (i != j && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset &&
4926                                 (clause1->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause2->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
4927                                 cfg->exception_message = g_strdup ("nested clauses");
4928                                 cfg->disable_llvm = TRUE;
4929                                 break;
4930                         }
4931                 }
4932         }
4933         if (cfg->disable_llvm)
4934                 return;
4935
4936         /* FIXME: */
4937         if (cfg->method->dynamic) {
4938                 cfg->exception_message = g_strdup ("dynamic.");
4939                 cfg->disable_llvm = TRUE;
4940         }
4941         if (cfg->disable_llvm)
4942                 return;
4943 }
4944
4945 /*
4946  * mono_llvm_emit_method:
4947  *
4948  *   Emit LLVM IL from the mono IL, and compile it to native code using LLVM.
4949  */
4950 void
4951 mono_llvm_emit_method (MonoCompile *cfg)
4952 {
4953         EmitContext *ctx;
4954         MonoMethodSignature *sig;
4955         MonoBasicBlock *bb;
4956         LLVMTypeRef method_type;
4957         LLVMValueRef method = NULL;
4958         char *method_name;
4959         LLVMValueRef *values;
4960         int i, max_block_num, bb_index;
4961         gboolean last = FALSE;
4962         GPtrArray *phi_values;
4963         LLVMCallInfo *linfo;
4964         GSList *l;
4965         LLVMModuleRef module;
4966         BBInfo *bblocks;
4967         GPtrArray *bblock_list;
4968         MonoMethodHeader *header;
4969         MonoExceptionClause *clause;
4970         LLVMSigInfo sinfo;
4971         char **names;
4972
4973         /* The code below might acquire the loader lock, so use it for global locking */
4974         mono_loader_lock ();
4975
4976         /* Used to communicate with the callbacks */
4977         mono_native_tls_set_value (current_cfg_tls_id, cfg);
4978
4979         ctx = g_new0 (EmitContext, 1);
4980         ctx->cfg = cfg;
4981         ctx->mempool = cfg->mempool;
4982
4983         /*
4984          * This maps vregs to the LLVM instruction defining them
4985          */
4986         values = g_new0 (LLVMValueRef, cfg->next_vreg);
4987         /*
4988          * This maps vregs for volatile variables to the LLVM instruction defining their
4989          * address.
4990          */
4991         ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
4992         ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
4993         ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
4994         phi_values = g_ptr_array_sized_new (256);
4995         /* 
4996          * This signals whenever the vreg was defined by a phi node with no input vars
4997          * (i.e. all its input bblocks end with NOT_REACHABLE).
4998          */
4999         ctx->is_dead = g_new0 (gboolean, cfg->next_vreg);
5000         /* Whenever the bblock is unreachable */
5001         ctx->unreachable = g_new0 (gboolean, cfg->max_block_num);
5002
5003         bblock_list = g_ptr_array_sized_new (256);
5004
5005         ctx->values = values;
5006         ctx->region_to_handler = g_hash_table_new (NULL, NULL);
5007         ctx->clause_to_handler = g_hash_table_new (NULL, NULL);
5008  
5009         if (cfg->compile_aot) {
5010                 ctx->lmodule = &aot_module;
5011                 method_name = mono_aot_get_method_name (cfg);
5012                 cfg->llvm_method_name = g_strdup (method_name);
5013         } else {
5014                 init_jit_module (cfg->domain);
5015                 ctx->lmodule = domain_jit_info (cfg->domain)->llvm_module;
5016                 method_name = mono_method_full_name (cfg->method, TRUE);
5017         }
5018
5019         module = ctx->module = ctx->lmodule->module;
5020
5021         if (cfg->gsharedvt)
5022                 LLVM_FAILURE (ctx, "gsharedvt");
5023
5024 #if 1
5025         {
5026                 static int count = 0;
5027                 count ++;
5028
5029                 if (g_getenv ("LLVM_COUNT")) {
5030                         if (count == atoi (g_getenv ("LLVM_COUNT"))) {
5031                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
5032                                 fflush (stdout);
5033                                 last = TRUE;
5034                         }
5035                         if (count > atoi (g_getenv ("LLVM_COUNT")))
5036                                 LLVM_FAILURE (ctx, "");
5037                 }
5038         }
5039 #endif
5040
5041         sig = mono_method_signature (cfg->method);
5042         ctx->sig = sig;
5043
5044         linfo = mono_arch_get_llvm_call_info (cfg, sig);
5045         ctx->linfo = linfo;
5046         CHECK_FAILURE (ctx);
5047
5048         if (cfg->rgctx_var)
5049                 linfo->rgctx_arg = TRUE;
5050         method_type = sig_to_llvm_sig_full (ctx, sig, linfo, &sinfo);
5051         CHECK_FAILURE (ctx);
5052
5053         /* 
5054          * This maps parameter indexes in the original signature to the indexes in
5055          * the LLVM signature.
5056          */
5057         ctx->pindexes = sinfo.pindexes;
5058
5059         method = LLVMAddFunction (module, method_name, method_type);
5060         ctx->lmethod = method;
5061
5062         LLVMSetFunctionCallConv (method, LLVMMono1CallConv);
5063         LLVMSetLinkage (method, LLVMPrivateLinkage);
5064
5065         LLVMAddFunctionAttr (method, LLVMUWTable);
5066
5067         if (cfg->compile_aot) {
5068                 LLVMSetLinkage (method, LLVMInternalLinkage);
5069                 if (ctx->lmodule->external_symbols) {
5070                         LLVMSetLinkage (method, LLVMExternalLinkage);
5071                         LLVMSetVisibility (method, LLVMHiddenVisibility);
5072                 }
5073         } else {
5074                 LLVMSetLinkage (method, LLVMPrivateLinkage);
5075         }
5076
5077         if (cfg->method->save_lmf)
5078                 LLVM_FAILURE (ctx, "lmf");
5079
5080         if (sig->pinvoke && cfg->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
5081                 LLVM_FAILURE (ctx, "pinvoke signature");
5082
5083         header = cfg->header;
5084         for (i = 0; i < header->num_clauses; ++i) {
5085                 clause = &header->clauses [i];
5086                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
5087                         LLVM_FAILURE (ctx, "non-finally/catch clause.");
5088         }
5089         if (header->num_clauses || (cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING))
5090                 /* We can't handle inlined methods with clauses */
5091                 LLVMAddFunctionAttr (method, LLVMNoInlineAttribute);
5092
5093         if (linfo->rgctx_arg) {
5094                 ctx->rgctx_arg = LLVMGetParam (method, sinfo.rgctx_arg_pindex);
5095                 /*
5096                  * We mark the rgctx parameter with the inreg attribute, which is mapped to
5097                  * MONO_ARCH_RGCTX_REG in the Mono calling convention in llvm, i.e.
5098                  * CC_X86_64_Mono in X86CallingConv.td.
5099                  */
5100                 LLVMAddAttribute (ctx->rgctx_arg, LLVMInRegAttribute);
5101                 LLVMSetValueName (ctx->rgctx_arg, "rgctx");
5102         }
5103         if (cfg->vret_addr) {
5104                 values [cfg->vret_addr->dreg] = LLVMGetParam (method, sinfo.vret_arg_pindex);
5105                 LLVMSetValueName (values [cfg->vret_addr->dreg], "vret");
5106                 if (linfo->ret.storage == LLVMArgVtypeByRef) {
5107                         LLVMAddAttribute (LLVMGetParam (method, sinfo.vret_arg_pindex), LLVMStructRetAttribute);
5108                         LLVMAddAttribute (LLVMGetParam (method, sinfo.vret_arg_pindex), LLVMNoAliasAttribute);
5109                 }
5110         }
5111         if (sig->hasthis) {
5112                 values [cfg->args [0]->dreg] = LLVMGetParam (method, sinfo.this_arg_pindex);
5113                 LLVMSetValueName (values [cfg->args [0]->dreg], "this");
5114         }
5115
5116         names = g_new (char *, sig->param_count);
5117         mono_method_get_param_names (cfg->method, (const char **) names);
5118
5119         for (i = 0; i < sig->param_count; ++i) {
5120                 char *name;
5121
5122                 values [cfg->args [i + sig->hasthis]->dreg] = LLVMGetParam (method, sinfo.pindexes [i]);
5123                 if (names [i] && names [i][0] != '\0')
5124                         name = g_strdup_printf ("arg_%s", names [i]);
5125                 else
5126                         name = g_strdup_printf ("arg_%d", i);
5127                 LLVMSetValueName (values [cfg->args [i + sig->hasthis]->dreg], name);
5128                 g_free (name);
5129                 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal)
5130                         LLVMAddAttribute (LLVMGetParam (method, sinfo.pindexes [i]), LLVMByValAttribute);
5131
5132                 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByRef) {
5133                         /* For OP_LDADDR */
5134                         cfg->args [i + sig->hasthis]->opcode = OP_VTARG_ADDR;
5135                 }
5136         }
5137         g_free (names);
5138
5139         if (ctx->lmodule->emit_dwarf && cfg->compile_aot && mono_debug_enabled ()) {
5140                 ctx->minfo = mono_debug_lookup_method (cfg->method);
5141                 ctx->dbg_md = emit_dbg_subprogram (ctx, cfg, method, method_name);
5142         }
5143
5144         max_block_num = 0;
5145         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
5146                 max_block_num = MAX (max_block_num, bb->block_num);
5147         ctx->bblocks = bblocks = g_new0 (BBInfo, max_block_num + 1);
5148
5149         /* Add branches between non-consecutive bblocks */
5150         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5151                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
5152                         bb->next_bb != bb->last_ins->inst_false_bb) {
5153                         
5154                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
5155                         inst->opcode = OP_BR;
5156                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
5157                         mono_bblock_add_inst (bb, inst);
5158                 }
5159         }
5160
5161         /*
5162          * The INDIRECT flag added by OP_LDADDR inhibits optimizations, even if the LDADDR
5163          * was later optimized away, so clear these flags, and add them back for the still
5164          * present OP_LDADDR instructions.
5165          */
5166         for (i = 0; i < cfg->next_vreg; ++i) {
5167                 MonoInst *ins;
5168
5169                 ins = get_vreg_to_inst (cfg, i);
5170                 if (ins && ins != cfg->rgctx_var)
5171                         ins->flags &= ~MONO_INST_INDIRECT;
5172         }
5173
5174         /*
5175          * Make a first pass over the code to precreate PHI nodes/set INDIRECT flags.
5176          */
5177         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5178                 MonoInst *ins;
5179                 LLVMBuilderRef builder;
5180                 char *dname;
5181                 char dname_buf[128];
5182
5183                 builder = create_builder (ctx);
5184
5185                 for (ins = bb->code; ins; ins = ins->next) {
5186                         switch (ins->opcode) {
5187                         case OP_PHI:
5188                         case OP_FPHI:
5189                         case OP_VPHI:
5190                         case OP_XPHI: {
5191                                 LLVMTypeRef phi_type = llvm_type_to_stack_type (cfg, type_to_llvm_type (ctx, &ins->klass->byval_arg));
5192
5193                                 CHECK_FAILURE (ctx);
5194
5195                                 if (ins->opcode == OP_VPHI) {
5196                                         /* Treat valuetype PHI nodes as operating on the address itself */
5197                                         g_assert (ins->klass);
5198                                         phi_type = LLVMPointerType (type_to_llvm_type (ctx, &ins->klass->byval_arg), 0);
5199                                 }
5200
5201                                 /* 
5202                                  * Have to precreate these, as they can be referenced by
5203                                  * earlier instructions.
5204                                  */
5205                                 sprintf (dname_buf, "t%d", ins->dreg);
5206                                 dname = dname_buf;
5207                                 values [ins->dreg] = LLVMBuildPhi (builder, phi_type, dname);
5208
5209                                 if (ins->opcode == OP_VPHI)
5210                                         ctx->addresses [ins->dreg] = values [ins->dreg];
5211
5212                                 g_ptr_array_add (phi_values, values [ins->dreg]);
5213
5214                                 /* 
5215                                  * Set the expected type of the incoming arguments since these have
5216                                  * to have the same type.
5217                                  */
5218                                 for (i = 0; i < ins->inst_phi_args [0]; i++) {
5219                                         int sreg1 = ins->inst_phi_args [i + 1];
5220                                         
5221                                         if (sreg1 != -1)
5222                                                 ctx->vreg_types [sreg1] = phi_type;
5223                                 }
5224                                 break;
5225                                 }
5226                         case OP_LDADDR:
5227                                 ((MonoInst*)ins->inst_p0)->flags |= MONO_INST_INDIRECT;
5228                                 break;
5229                         default:
5230                                 break;
5231                         }
5232                 }
5233         }
5234
5235         /* 
5236          * Create an ordering for bblocks, use the depth first order first, then
5237          * put the exception handling bblocks last.
5238          */
5239         for (bb_index = 0; bb_index < cfg->num_bblocks; ++bb_index) {
5240                 bb = cfg->bblocks [bb_index];
5241                 if (!(bb->region != -1 && !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))) {
5242                         g_ptr_array_add (bblock_list, bb);
5243                         bblocks [bb->block_num].added = TRUE;
5244                 }
5245         }
5246
5247         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5248                 if (!bblocks [bb->block_num].added)
5249                         g_ptr_array_add (bblock_list, bb);
5250         }
5251
5252         /*
5253          * Second pass: generate code.
5254          */
5255         for (bb_index = 0; bb_index < bblock_list->len; ++bb_index) {
5256                 bb = g_ptr_array_index (bblock_list, bb_index);
5257
5258                 if (!(bb == cfg->bb_entry || bb->in_count > 0))
5259                         continue;
5260
5261                 process_bb (ctx, bb);
5262                 CHECK_FAILURE (ctx);
5263         }
5264
5265         /* Add incoming phi values */
5266         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5267                 GSList *l, *ins_list;
5268
5269                 ins_list = bblocks [bb->block_num].phi_nodes;
5270
5271                 for (l = ins_list; l; l = l->next) {
5272                         PhiNode *node = l->data;
5273                         MonoInst *phi = node->phi;
5274                         int sreg1 = node->sreg;
5275                         LLVMBasicBlockRef in_bb;
5276
5277                         if (sreg1 == -1)
5278                                 continue;
5279
5280                         in_bb = get_end_bb (ctx, node->in_bb);
5281
5282                         if (ctx->unreachable [node->in_bb->block_num])
5283                                 continue;
5284
5285                         if (!values [sreg1])
5286                                 /* Can happen with values in EH clauses */
5287                                 LLVM_FAILURE (ctx, "incoming phi sreg1");
5288
5289                         if (phi->opcode == OP_VPHI) {
5290                                 g_assert (LLVMTypeOf (ctx->addresses [sreg1]) == LLVMTypeOf (values [phi->dreg]));
5291                                 LLVMAddIncoming (values [phi->dreg], &ctx->addresses [sreg1], &in_bb, 1);
5292                         } else {
5293                                 if (LLVMTypeOf (values [sreg1]) != LLVMTypeOf (values [phi->dreg]))
5294                                         // FIXME:
5295                                         LLVM_FAILURE (ctx, "incoming phi arg type mismatch");
5296                                 g_assert (LLVMTypeOf (values [sreg1]) == LLVMTypeOf (values [phi->dreg]));
5297                                 LLVMAddIncoming (values [phi->dreg], &values [sreg1], &in_bb, 1);
5298                         }
5299                 }
5300         }
5301
5302         /* Create the SWITCH statements for ENDFINALLY instructions */
5303         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5304                 BBInfo *info = &bblocks [bb->block_num];
5305                 GSList *l;
5306                 for (l = info->endfinally_switch_ins_list; l; l = l->next) {
5307                         LLVMValueRef switch_ins = l->data;
5308                         GSList *bb_list = info->call_handler_return_bbs;
5309
5310                         for (i = 0; i < g_slist_length (bb_list); ++i)
5311                                 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), i + 1, FALSE), g_slist_nth (bb_list, i)->data);
5312                 }
5313         }
5314
5315         if (cfg->verbose_level > 1)
5316                 mono_llvm_dump_value (method);
5317
5318         if (cfg->compile_aot)
5319                 mark_as_used (ctx->lmodule, method);
5320
5321         if (cfg->compile_aot) {
5322                 LLVMValueRef md_args [16];
5323                 LLVMValueRef md_node;
5324                 int method_index;
5325
5326                 method_index = mono_aot_get_method_index (cfg->orig_method);
5327                 md_args [0] = LLVMMDString (method_name, strlen (method_name));
5328                 md_args [1] = LLVMConstInt (LLVMInt32Type (), method_index, FALSE);
5329                 md_node = LLVMMDNode (md_args, 2);
5330                 LLVMAddNamedMetadataOperand (module, "mono.function_indexes", md_node);
5331                 //LLVMSetMetadata (method, md_kind, LLVMMDNode (&md_arg, 1));
5332         }
5333
5334         if (cfg->compile_aot) {
5335                 /* Don't generate native code, keep the LLVM IR */
5336                 if (cfg->compile_aot && cfg->verbose_level)
5337                         printf ("%s emitted as %s\n", mono_method_full_name (cfg->method, TRUE), method_name);
5338
5339                 //LLVMVerifyFunction(method, 0);
5340         } else {
5341                 //LLVMVerifyFunction(method, 0);
5342                 mono_llvm_optimize_method (ctx->lmodule->mono_ee, method);
5343
5344                 if (cfg->verbose_level > 1)
5345                         mono_llvm_dump_value (method);
5346
5347                 cfg->native_code = LLVMGetPointerToGlobal (ctx->lmodule->ee, method);
5348
5349                 /* Set by emit_cb */
5350                 g_assert (cfg->code_len);
5351
5352                 /* FIXME: Free the LLVM IL for the function */
5353         }
5354
5355         if (ctx->lmodule->method_to_lmethod)
5356                 g_hash_table_insert (ctx->lmodule->method_to_lmethod, cfg->method, method);
5357
5358         goto CLEANUP;
5359
5360  FAILURE:
5361
5362         if (method) {
5363                 /* Need to add unused phi nodes as they can be referenced by other values */
5364                 LLVMBasicBlockRef phi_bb = LLVMAppendBasicBlock (method, "PHI_BB");
5365                 LLVMBuilderRef builder;
5366
5367                 builder = create_builder (ctx);
5368                 LLVMPositionBuilderAtEnd (builder, phi_bb);
5369
5370                 for (i = 0; i < phi_values->len; ++i) {
5371                         LLVMValueRef v = g_ptr_array_index (phi_values, i);
5372                         if (LLVMGetInstructionParent (v) == NULL)
5373                                 LLVMInsertIntoBuilder (builder, v);
5374                 }
5375                 
5376                 LLVMDeleteFunction (method);
5377         }
5378
5379  CLEANUP:
5380         g_free (values);
5381         g_free (ctx->addresses);
5382         g_free (ctx->vreg_types);
5383         g_free (ctx->vreg_cli_types);
5384         g_free (ctx->pindexes);
5385         g_free (ctx->is_dead);
5386         g_free (ctx->unreachable);
5387         g_ptr_array_free (phi_values, TRUE);
5388         g_free (ctx->bblocks);
5389         g_hash_table_destroy (ctx->region_to_handler);
5390         g_hash_table_destroy (ctx->clause_to_handler);
5391         g_free (method_name);
5392         g_ptr_array_free (bblock_list, TRUE);
5393
5394         for (l = ctx->builders; l; l = l->next) {
5395                 LLVMBuilderRef builder = l->data;
5396                 LLVMDisposeBuilder (builder);
5397         }
5398
5399         g_free (ctx);
5400
5401         mono_native_tls_set_value (current_cfg_tls_id, NULL);
5402
5403         mono_loader_unlock ();
5404 }
5405
5406 /*
5407  * mono_llvm_emit_call:
5408  *
5409  *   Same as mono_arch_emit_call () for LLVM.
5410  */
5411 void
5412 mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
5413 {
5414         MonoInst *in;
5415         MonoMethodSignature *sig;
5416         int i, n, stack_size;
5417         LLVMArgInfo *ainfo;
5418
5419         stack_size = 0;
5420
5421         sig = call->signature;
5422         n = sig->param_count + sig->hasthis;
5423
5424         call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
5425
5426         if (cfg->disable_llvm)
5427                 return;
5428
5429         if (sig->call_convention == MONO_CALL_VARARG) {
5430                 cfg->exception_message = g_strdup ("varargs");
5431                 cfg->disable_llvm = TRUE;
5432         }
5433
5434         for (i = 0; i < n; ++i) {
5435                 MonoInst *ins;
5436
5437                 ainfo = call->cinfo->args + i;
5438
5439                 in = call->args [i];
5440                         
5441                 /* Simply remember the arguments */
5442                 switch (ainfo->storage) {
5443                 case LLVMArgInIReg:
5444                 case LLVMArgInFPReg: {
5445                         MonoType *t = (sig->hasthis && i == 0) ? &mono_get_intptr_class ()->byval_arg : sig->params [i - sig->hasthis];
5446                         int opcode;
5447
5448                         opcode = mono_type_to_regmove (cfg, t);
5449                         if (opcode == OP_FMOVE) {
5450                                 MONO_INST_NEW (cfg, ins, OP_FMOVE);
5451                                 ins->dreg = mono_alloc_freg (cfg);
5452                         } else if (opcode == OP_LMOVE) {
5453                                 MONO_INST_NEW (cfg, ins, OP_LMOVE);
5454                                 ins->dreg = mono_alloc_lreg (cfg);
5455                         } else {
5456                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
5457                                 ins->dreg = mono_alloc_ireg (cfg);
5458                         }
5459                         ins->sreg1 = in->dreg;
5460                         break;
5461                 }
5462                 case LLVMArgVtypeByVal:
5463                 case LLVMArgVtypeByRef:
5464                 case LLVMArgVtypeInReg:
5465                 case LLVMArgVtypeAsScalar:
5466                 case LLVMArgAsIArgs:
5467                 case LLVMArgAsFpArgs:
5468                         MONO_INST_NEW (cfg, ins, OP_LLVM_OUTARG_VT);
5469                         ins->dreg = mono_alloc_ireg (cfg);
5470                         ins->sreg1 = in->dreg;
5471                         ins->klass = mono_class_from_mono_type (sig->params [i - sig->hasthis]);
5472                         break;
5473                 default:
5474                         call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
5475                         cfg->exception_message = g_strdup ("ainfo->storage");
5476                         cfg->disable_llvm = TRUE;
5477                         return;
5478                 }
5479
5480                 if (!cfg->disable_llvm) {
5481                         MONO_ADD_INS (cfg->cbb, ins);
5482                         mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, 0, FALSE);
5483                 }
5484         }
5485 }
5486
5487 static unsigned char*
5488 alloc_cb (LLVMValueRef function, int size)
5489 {
5490         MonoCompile *cfg;
5491
5492         cfg = mono_native_tls_get_value (current_cfg_tls_id);
5493
5494         if (cfg) {
5495                 // FIXME: dynamic
5496                 return mono_domain_code_reserve (cfg->domain, size);
5497         } else {
5498                 return mono_domain_code_reserve (mono_domain_get (), size);
5499         }
5500 }
5501
5502 static void
5503 emitted_cb (LLVMValueRef function, void *start, void *end)
5504 {
5505         MonoCompile *cfg;
5506
5507         cfg = mono_native_tls_get_value (current_cfg_tls_id);
5508         g_assert (cfg);
5509         cfg->code_len = (guint8*)end - (guint8*)start;
5510 }
5511
5512 static void
5513 exception_cb (void *data)
5514 {
5515         MonoCompile *cfg;
5516         MonoJitExceptionInfo *ei;
5517         guint32 ei_len, i, j, nested_len, nindex;
5518         gpointer *type_info;
5519         int this_reg, this_offset;
5520
5521         cfg = mono_native_tls_get_value (current_cfg_tls_id);
5522         g_assert (cfg);
5523
5524         /*
5525          * data points to a DWARF FDE structure, convert it to our unwind format and
5526          * save it.
5527          * An alternative would be to save it directly, and modify our unwinder to work
5528          * with it.
5529          */
5530         cfg->encoded_unwind_ops = mono_unwind_decode_fde ((guint8*)data, &cfg->encoded_unwind_ops_len, NULL, &ei, &ei_len, &type_info, &this_reg, &this_offset);
5531         if (cfg->verbose_level > 1)
5532                 mono_print_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
5533
5534         /* Count nested clauses */
5535         nested_len = 0;
5536         for (i = 0; i < ei_len; ++i) {
5537                 gint32 cindex1 = *(gint32*)type_info [i];
5538                 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
5539
5540                 for (j = 0; j < cfg->header->num_clauses; ++j) {
5541                         int cindex2 = j;
5542                         MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
5543
5544                         if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
5545                                 nested_len ++;
5546                         }
5547                 }
5548         }
5549
5550         cfg->llvm_ex_info = mono_mempool_alloc0 (cfg->mempool, (ei_len + nested_len) * sizeof (MonoJitExceptionInfo));
5551         cfg->llvm_ex_info_len = ei_len + nested_len;
5552         memcpy (cfg->llvm_ex_info, ei, ei_len * sizeof (MonoJitExceptionInfo));
5553         /* Fill the rest of the information from the type info */
5554         for (i = 0; i < ei_len; ++i) {
5555                 gint32 clause_index = *(gint32*)type_info [i];
5556                 MonoExceptionClause *clause = &cfg->header->clauses [clause_index];
5557
5558                 cfg->llvm_ex_info [i].flags = clause->flags;
5559                 cfg->llvm_ex_info [i].data.catch_class = clause->data.catch_class;
5560                 cfg->llvm_ex_info [i].clause_index = clause_index;
5561         }
5562
5563         /*
5564          * For nested clauses, the LLVM produced exception info associates the try interval with
5565          * the innermost handler, while mono expects it to be associated with all nesting clauses.
5566          * So add new clauses which use the IL info (catch class etc.) from the nesting clause,
5567          * and everything else from the nested clause.
5568          */
5569         nindex = ei_len;
5570         for (i = 0; i < ei_len; ++i) {
5571                 gint32 cindex1 = *(gint32*)type_info [i];
5572                 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
5573
5574                 for (j = 0; j < cfg->header->num_clauses; ++j) {
5575                         int cindex2 = j;
5576                         MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
5577                         MonoJitExceptionInfo *nesting_ei, *nested_ei;
5578
5579                         if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
5580                                 /* clause1 is the nested clause */
5581                                 nested_ei = &cfg->llvm_ex_info [i];
5582                                 nesting_ei = &cfg->llvm_ex_info [nindex];
5583                                 nindex ++;
5584
5585                                 memcpy (nesting_ei, nested_ei, sizeof (MonoJitExceptionInfo));
5586
5587                                 nesting_ei->flags = clause2->flags;
5588                                 nesting_ei->data.catch_class = clause2->data.catch_class;
5589                                 nesting_ei->clause_index = cindex2;
5590                         }
5591                 }
5592         }
5593         g_assert (nindex == ei_len + nested_len);
5594         cfg->llvm_this_reg = this_reg;
5595         cfg->llvm_this_offset = this_offset;
5596
5597         /* type_info [i] is cfg mempool allocated, no need to free it */
5598
5599         g_free (ei);
5600         g_free (type_info);
5601 }
5602
5603 static char*
5604 dlsym_cb (const char *name, void **symbol)
5605 {
5606         MonoDl *current;
5607         char *err;
5608
5609         err = NULL;
5610         if (!strcmp (name, "__bzero")) {
5611                 *symbol = (void*)bzero;
5612         } else {
5613                 current = mono_dl_open (NULL, 0, NULL);
5614                 g_assert (current);
5615
5616                 err = mono_dl_symbol (current, name, symbol);
5617
5618                 mono_dl_close (current);
5619         }
5620 #ifdef MONO_ARCH_HAVE_CREATE_LLVM_NATIVE_THUNK
5621         *symbol = (char*)mono_arch_create_llvm_native_thunk (mono_domain_get (), (guint8*)(*symbol));
5622 #endif
5623         return err;
5624 }
5625
5626 static inline void
5627 AddFunc (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef *param_types, int nparams)
5628 {
5629         LLVMAddFunction (module, name, LLVMFunctionType (ret_type, param_types, nparams, FALSE));
5630 }
5631
5632 static inline void
5633 AddFunc2 (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef param_type1, LLVMTypeRef param_type2)
5634 {
5635         LLVMTypeRef param_types [4];
5636
5637         param_types [0] = param_type1;
5638         param_types [1] = param_type2;
5639
5640         AddFunc (module, name, ret_type, param_types, 2);
5641 }
5642
5643 static void
5644 add_intrinsics (LLVMModuleRef module)
5645 {
5646         /* Emit declarations of instrinsics */
5647         /*
5648          * It would be nicer to emit only the intrinsics actually used, but LLVM's Module
5649          * type doesn't seem to do any locking.
5650          */
5651         {
5652                 LLVMTypeRef params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5653
5654                 memset_param_count = 5;
5655                 memset_func_name = "llvm.memset.p0i8.i32";
5656
5657                 AddFunc (module, memset_func_name, LLVMVoidType (), params, memset_param_count);
5658         }
5659
5660         {
5661                 LLVMTypeRef params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5662
5663                 memcpy_param_count = 5;
5664                 memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
5665
5666                 AddFunc (module, memcpy_func_name, LLVMVoidType (), params, memcpy_param_count);
5667         }
5668
5669         {
5670                 LLVMTypeRef params [] = { LLVMDoubleType () };
5671
5672                 AddFunc (module, "llvm.sin.f64", LLVMDoubleType (), params, 1);
5673                 AddFunc (module, "llvm.cos.f64", LLVMDoubleType (), params, 1);
5674                 AddFunc (module, "llvm.sqrt.f64", LLVMDoubleType (), params, 1);
5675
5676                 /* This isn't an intrinsic, instead llvm seems to special case it by name */
5677                 AddFunc (module, "fabs", LLVMDoubleType (), params, 1);
5678         }
5679
5680         {
5681                 LLVMTypeRef ovf_res_i32 [] = { LLVMInt32Type (), LLVMInt1Type () };
5682                 LLVMTypeRef params [] = { LLVMInt32Type (), LLVMInt32Type () };
5683                 LLVMTypeRef ret_type = LLVMStructType (ovf_res_i32, 2, FALSE);
5684
5685                 AddFunc (module, "llvm.sadd.with.overflow.i32", ret_type, params, 2);
5686                 AddFunc (module, "llvm.sadd.with.overflow.i32", ret_type, params, 2);
5687                 AddFunc (module, "llvm.uadd.with.overflow.i32", ret_type, params, 2);
5688                 AddFunc (module, "llvm.ssub.with.overflow.i32", ret_type, params, 2);
5689                 AddFunc (module, "llvm.usub.with.overflow.i32", ret_type, params, 2);
5690                 AddFunc (module, "llvm.smul.with.overflow.i32", ret_type, params, 2);
5691                 AddFunc (module, "llvm.umul.with.overflow.i32", ret_type, params, 2);
5692         }
5693
5694         {
5695                 LLVMTypeRef ovf_res_i64 [] = { LLVMInt64Type (), LLVMInt1Type () };
5696                 LLVMTypeRef params [] = { LLVMInt64Type (), LLVMInt64Type () };
5697                 LLVMTypeRef ret_type = LLVMStructType (ovf_res_i64, 2, FALSE);
5698
5699                 AddFunc (module, "llvm.sadd.with.overflow.i64", ret_type, params, 2);
5700                 AddFunc (module, "llvm.uadd.with.overflow.i64", ret_type, params, 2);
5701                 AddFunc (module, "llvm.ssub.with.overflow.i64", ret_type, params, 2);
5702                 AddFunc (module, "llvm.usub.with.overflow.i64", ret_type, params, 2);
5703                 AddFunc (module, "llvm.smul.with.overflow.i64", ret_type, params, 2);
5704                 AddFunc (module, "llvm.umul.with.overflow.i64", ret_type, params, 2);
5705         }
5706
5707         /* EH intrinsics */
5708         {
5709                 AddFunc (module, "mono_personality", LLVMVoidType (), NULL, 0);
5710
5711                 AddFunc (module, "llvm_resume_unwind_trampoline", LLVMVoidType (), NULL, 0);
5712         }
5713
5714         /* SSE intrinsics */
5715 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5716         {
5717                 LLVMTypeRef ret_type, arg_types [16];
5718
5719                 /* Binary ops */
5720                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5721                 arg_types [0] = ret_type;
5722                 arg_types [1] = ret_type;
5723                 AddFunc (module, "llvm.x86.sse41.pminud", ret_type, arg_types, 2);
5724                 AddFunc (module, "llvm.x86.sse41.pmaxud", ret_type, arg_types, 2);
5725
5726                 ret_type = type_to_simd_type (MONO_TYPE_I2);
5727                 arg_types [0] = ret_type;
5728                 arg_types [1] = ret_type;
5729                 AddFunc (module, "llvm.x86.sse41.pminuw", ret_type, arg_types, 2);
5730                 AddFunc (module, "llvm.x86.sse2.pmins.w", ret_type, arg_types, 2);
5731                 AddFunc (module, "llvm.x86.sse41.pmaxuw", ret_type, arg_types, 2);
5732                 AddFunc (module, "llvm.x86.sse2.padds.w", ret_type, arg_types, 2);
5733                 AddFunc (module, "llvm.x86.sse2.psubs.w", ret_type, arg_types, 2);
5734                 AddFunc (module, "llvm.x86.sse2.paddus.w", ret_type, arg_types, 2);
5735                 AddFunc (module, "llvm.x86.sse2.psubus.w", ret_type, arg_types, 2);
5736                 AddFunc (module, "llvm.x86.sse2.pavg.w", ret_type, arg_types, 2);
5737                 AddFunc (module, "llvm.x86.sse2.pmulh.w", ret_type, arg_types, 2);
5738                 AddFunc (module, "llvm.x86.sse2.pmulhu.w", ret_type, arg_types, 2);
5739
5740                 ret_type = type_to_simd_type (MONO_TYPE_I1);
5741                 arg_types [0] = ret_type;
5742                 arg_types [1] = ret_type;
5743                 AddFunc (module, "llvm.x86.sse2.pminu.b", ret_type, arg_types, 2);
5744                 AddFunc (module, "llvm.x86.sse2.pmaxu.b", ret_type, arg_types, 2);
5745                 AddFunc (module, "llvm.x86.sse2.padds.b", ret_type, arg_types, 2);
5746                 AddFunc (module, "llvm.x86.sse2.psubs.b", ret_type, arg_types, 2);
5747                 AddFunc (module, "llvm.x86.sse2.paddus.b", ret_type, arg_types, 2);
5748                 AddFunc (module, "llvm.x86.sse2.psubus.b", ret_type, arg_types, 2);
5749                 AddFunc (module, "llvm.x86.sse2.pavg.b", ret_type, arg_types, 2);
5750
5751                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5752                 arg_types [0] = ret_type;
5753                 arg_types [1] = ret_type;
5754                 AddFunc (module, "llvm.x86.sse2.min.pd", ret_type, arg_types, 2);
5755                 AddFunc (module, "llvm.x86.sse2.max.pd", ret_type, arg_types, 2);
5756                 AddFunc (module, "llvm.x86.sse3.hadd.pd", ret_type, arg_types, 2);
5757                 AddFunc (module, "llvm.x86.sse3.hsub.pd", ret_type, arg_types, 2);
5758                 AddFunc (module, "llvm.x86.sse3.addsub.pd", ret_type, arg_types, 2);
5759
5760                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5761                 arg_types [0] = ret_type;
5762                 arg_types [1] = ret_type;
5763                 AddFunc (module, "llvm.x86.sse.min.ps", ret_type, arg_types, 2);
5764                 AddFunc (module, "llvm.x86.sse.max.ps", ret_type, arg_types, 2);
5765                 AddFunc (module, "llvm.x86.sse3.hadd.ps", ret_type, arg_types, 2);
5766                 AddFunc (module, "llvm.x86.sse3.hsub.ps", ret_type, arg_types, 2);
5767                 AddFunc (module, "llvm.x86.sse3.addsub.ps", ret_type, arg_types, 2);
5768
5769                 /* pack */
5770                 ret_type = type_to_simd_type (MONO_TYPE_I1);
5771                 arg_types [0] = type_to_simd_type (MONO_TYPE_I2);
5772                 arg_types [1] = type_to_simd_type (MONO_TYPE_I2);
5773                 AddFunc (module, "llvm.x86.sse2.packsswb.128", ret_type, arg_types, 2);
5774                 AddFunc (module, "llvm.x86.sse2.packuswb.128", ret_type, arg_types, 2);
5775                 ret_type = type_to_simd_type (MONO_TYPE_I2);
5776                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5777                 arg_types [1] = type_to_simd_type (MONO_TYPE_I4);
5778                 AddFunc (module, "llvm.x86.sse2.packssdw.128", ret_type, arg_types, 2);
5779                 AddFunc (module, "llvm.x86.sse41.packusdw", ret_type, arg_types, 2);
5780
5781                 /* cmp pd/ps */
5782                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5783                 arg_types [0] = ret_type;
5784                 arg_types [1] = ret_type;
5785                 arg_types [2] = LLVMInt8Type ();
5786                 AddFunc (module, "llvm.x86.sse2.cmp.pd", ret_type, arg_types, 3);
5787                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5788                 arg_types [0] = ret_type;
5789                 arg_types [1] = ret_type;
5790                 arg_types [2] = LLVMInt8Type ();
5791                 AddFunc (module, "llvm.x86.sse.cmp.ps", ret_type, arg_types, 3);
5792
5793                 /* Conversion ops */
5794                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5795                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5796                 AddFunc (module, "llvm.x86.sse2.cvtdq2pd", ret_type, arg_types, 1);
5797                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5798                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5799                 AddFunc (module, "llvm.x86.sse2.cvtdq2ps", ret_type, arg_types, 1);
5800                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5801                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5802                 AddFunc (module, "llvm.x86.sse2.cvtpd2dq", ret_type, arg_types, 1);
5803                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5804                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5805                 AddFunc (module, "llvm.x86.sse2.cvtps2dq", ret_type, arg_types, 1);
5806                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5807                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5808                 AddFunc (module, "llvm.x86.sse2.cvtpd2ps", ret_type, arg_types, 1);
5809                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5810                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5811                 AddFunc (module, "llvm.x86.sse2.cvtps2pd", ret_type, arg_types, 1);
5812
5813                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5814                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5815                 AddFunc (module, "llvm.x86.sse2.cvttpd2dq", ret_type, arg_types, 1);
5816                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5817                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5818                 AddFunc (module, "llvm.x86.sse2.cvttps2dq", ret_type, arg_types, 1);
5819
5820                 /* Unary ops */
5821                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5822                 arg_types [0] = ret_type;
5823                 AddFunc (module, "llvm.x86.sse2.sqrt.pd", ret_type, arg_types, 1);
5824                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5825                 arg_types [0] = ret_type;
5826                 AddFunc (module, "llvm.x86.sse.sqrt.ps", ret_type, arg_types, 1);
5827                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5828                 arg_types [0] = ret_type;
5829                 AddFunc (module, "llvm.x86.sse.rsqrt.ps", ret_type, arg_types, 1);
5830                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5831                 arg_types [0] = ret_type;
5832                 AddFunc (module, "llvm.x86.sse.rcp.ps", ret_type, arg_types, 1);
5833
5834                 /* shifts */
5835                 ret_type = type_to_simd_type (MONO_TYPE_I2);
5836                 arg_types [0] = ret_type;
5837                 arg_types [1] = LLVMInt32Type ();
5838                 AddFunc (module, "llvm.x86.sse2.psrli.w", ret_type, arg_types, 2);
5839                 AddFunc (module, "llvm.x86.sse2.psrai.w", ret_type, arg_types, 2);
5840                 AddFunc (module, "llvm.x86.sse2.pslli.w", ret_type, arg_types, 2);
5841                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5842                 arg_types [0] = ret_type;
5843                 arg_types [1] = LLVMInt32Type ();
5844                 AddFunc (module, "llvm.x86.sse2.psrli.d", ret_type, arg_types, 2);
5845                 AddFunc (module, "llvm.x86.sse2.psrai.d", ret_type, arg_types, 2);
5846                 AddFunc (module, "llvm.x86.sse2.pslli.d", ret_type, arg_types, 2);
5847                 ret_type = type_to_simd_type (MONO_TYPE_I8);
5848                 arg_types [0] = ret_type;
5849                 arg_types [1] = LLVMInt32Type ();
5850                 AddFunc (module, "llvm.x86.sse2.psrli.q", ret_type, arg_types, 2);
5851                 AddFunc (module, "llvm.x86.sse2.pslli.q", ret_type, arg_types, 2);
5852
5853                 /* pmovmskb */
5854                 ret_type = LLVMInt32Type ();
5855                 arg_types [0] = type_to_simd_type (MONO_TYPE_I1);
5856                 AddFunc (module, "llvm.x86.sse2.pmovmskb.128", ret_type, arg_types, 1);
5857         }
5858
5859         AddFunc (module, "llvm.x86.sse2.pause", LLVMVoidType (), NULL, 0);
5860 #endif
5861
5862         /* Load/Store intrinsics */
5863         {
5864                 LLVMTypeRef arg_types [5];
5865                 int i;
5866                 char name [128];
5867
5868                 for (i = 1; i <= 8; i *= 2) {
5869                         arg_types [0] = LLVMPointerType (LLVMIntType (i * 8), 0);
5870                         arg_types [1] = LLVMInt32Type ();
5871                         arg_types [2] = LLVMInt1Type ();
5872                         arg_types [3] = LLVMInt32Type ();
5873                         sprintf (name, "llvm.mono.load.i%d.p0i%d", i * 8, i * 8);
5874                         AddFunc (module, name, LLVMIntType (i * 8), arg_types, 4);
5875
5876                         arg_types [0] = LLVMIntType (i * 8);
5877                         arg_types [1] = LLVMPointerType (LLVMIntType (i * 8), 0);
5878                         arg_types [2] = LLVMInt32Type ();
5879                         arg_types [3] = LLVMInt1Type ();
5880                         arg_types [4] = LLVMInt32Type ();
5881                         sprintf (name, "llvm.mono.store.i%d.p0i%d", i * 8, i * 8);
5882                         AddFunc (module, name, LLVMVoidType (), arg_types, 5);
5883                 }
5884         }
5885 }
5886
5887 static void
5888 add_types (MonoLLVMModule *lmodule)
5889 {
5890         lmodule->ptr_type = LLVMPointerType (sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type (), 0);
5891 }
5892
5893 void
5894 mono_llvm_init (void)
5895 {
5896         mono_native_tls_alloc (&current_cfg_tls_id, NULL);
5897 }
5898
5899 static void
5900 init_jit_module (MonoDomain *domain)
5901 {
5902         MonoJitICallInfo *info;
5903         MonoJitDomainInfo *dinfo;
5904         MonoLLVMModule *module;
5905         char *name;
5906
5907         dinfo = domain_jit_info (domain);
5908         if (dinfo->llvm_module)
5909                 return;
5910
5911         mono_loader_lock ();
5912
5913         if (dinfo->llvm_module) {
5914                 mono_loader_unlock ();
5915                 return;
5916         }
5917
5918         module = g_new0 (MonoLLVMModule, 1);
5919
5920         name = g_strdup_printf ("mono-%s", domain->friendly_name);
5921         module->module = LLVMModuleCreateWithName (name);
5922
5923         module->mono_ee = mono_llvm_create_ee (LLVMCreateModuleProviderForExistingModule (module->module), alloc_cb, emitted_cb, exception_cb, dlsym_cb, &module->ee);
5924
5925         add_intrinsics (module->module);
5926         add_types (module);
5927
5928         module->llvm_types = g_hash_table_new (NULL, NULL);
5929
5930         info = mono_find_jit_icall_by_name ("llvm_resume_unwind_trampoline");
5931         g_assert (info);
5932         LLVMAddGlobalMapping (module->ee, LLVMGetNamedFunction (module->module, "llvm_resume_unwind_trampoline"), (void*)info->func);
5933
5934         mono_memory_barrier ();
5935
5936         dinfo->llvm_module = module;
5937
5938         mono_loader_unlock ();
5939 }
5940
5941 void
5942 mono_llvm_cleanup (void)
5943 {
5944         if (aot_module.module)
5945                 LLVMDisposeModule (aot_module.module);
5946
5947         LLVMContextDispose (LLVMGetGlobalContext ());
5948 }
5949
5950 void
5951 mono_llvm_free_domain_info (MonoDomain *domain)
5952 {
5953         MonoJitDomainInfo *info = domain_jit_info (domain);
5954         MonoLLVMModule *module = info->llvm_module;
5955         int i;
5956
5957         if (!module)
5958                 return;
5959
5960         if (module->llvm_types)
5961                 g_hash_table_destroy (module->llvm_types);
5962
5963         mono_llvm_dispose_ee (module->mono_ee);
5964
5965         if (module->bb_names) {
5966                 for (i = 0; i < module->bb_names_len; ++i)
5967                         g_free (module->bb_names [i]);
5968                 g_free (module->bb_names);
5969         }
5970         //LLVMDisposeModule (module->module);
5971
5972         g_free (module);
5973
5974         info->llvm_module = NULL;
5975 }
5976
5977 void
5978 mono_llvm_create_aot_module (MonoAssembly *assembly, const char *global_prefix, gboolean emit_dwarf, gboolean static_link)
5979 {
5980         MonoLLVMModule *lmodule = &aot_module;
5981
5982         /* Delete previous module */
5983         if (lmodule->plt_entries)
5984                 g_hash_table_destroy (lmodule->plt_entries);
5985         if (lmodule->module)
5986                 LLVMDisposeModule (lmodule->module);
5987
5988         memset (lmodule, 0, sizeof (aot_module));
5989
5990         lmodule->module = LLVMModuleCreateWithName ("aot");
5991         lmodule->assembly = assembly;
5992         lmodule->global_prefix = g_strdup (global_prefix);
5993         lmodule->got_symbol = g_strdup_printf ("%s_llvm_got", global_prefix);
5994         lmodule->eh_frame_symbol = g_strdup_printf ("%s_eh_frame", global_prefix);
5995         lmodule->external_symbols = TRUE;
5996         lmodule->emit_dwarf = emit_dwarf;
5997         lmodule->static_link = static_link;
5998         /* The first few entries are reserved */
5999         lmodule->max_got_offset = 16;
6000
6001         add_intrinsics (lmodule->module);
6002         add_types (lmodule);
6003
6004         /* Add GOT */
6005         /*
6006          * We couldn't compute the type of the LLVM global representing the got because
6007          * its size is only known after all the methods have been emitted. So create
6008          * a dummy variable, and replace all uses it with the real got variable when
6009          * its size is known in mono_llvm_emit_aot_module ().
6010          */
6011         {
6012                 LLVMTypeRef got_type = LLVMArrayType (lmodule->ptr_type, 0);
6013
6014                 aot_module.got_var = LLVMAddGlobal (lmodule->module, got_type, "mono_dummy_got");
6015                 LLVMSetInitializer (lmodule->got_var, LLVMConstNull (got_type));
6016         }
6017
6018         /* Add a dummy personality function */
6019         {
6020                 LLVMBasicBlockRef lbb;
6021                 LLVMBuilderRef lbuilder;
6022                 LLVMValueRef personality;
6023
6024                 personality = LLVMAddFunction (lmodule->module, "mono_aot_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
6025                 LLVMSetLinkage (personality, LLVMInternalLinkage);
6026                 lbb = LLVMAppendBasicBlock (personality, "BB0");
6027                 lbuilder = LLVMCreateBuilder ();
6028                 LLVMPositionBuilderAtEnd (lbuilder, lbb);
6029                 LLVMBuildRetVoid (lbuilder);
6030                 mark_as_used (lmodule, personality);
6031         }
6032
6033         lmodule->llvm_types = g_hash_table_new (NULL, NULL);
6034         lmodule->plt_entries = g_hash_table_new (g_str_hash, g_str_equal);
6035         lmodule->plt_entries_ji = g_hash_table_new (NULL, NULL);
6036         lmodule->method_to_lmethod = g_hash_table_new (NULL, NULL);
6037 }
6038
6039 static LLVMValueRef
6040 llvm_array_from_uints (LLVMTypeRef el_type, guint32 *values, int nvalues)
6041 {
6042         int i;
6043         LLVMValueRef res, *vals;
6044
6045         vals = g_new0 (LLVMValueRef, nvalues);
6046         for (i = 0; i < nvalues; ++i)
6047                 vals [i] = LLVMConstInt (LLVMInt32Type (), values [i], FALSE);
6048         res = LLVMConstArray (LLVMInt32Type (), vals, nvalues);
6049         g_free (vals);
6050         return res;
6051 }
6052
6053 /*
6054  * mono_llvm_emit_aot_file_info:
6055  *
6056  *   Emit the MonoAotFileInfo structure.
6057  * Same as emit_aot_file_info () in aot-compiler.c.
6058  */
6059 void
6060 mono_llvm_emit_aot_file_info (MonoAotFileInfo *info, gboolean has_jitted_code)
6061 {
6062         MonoLLVMModule *lmodule = &aot_module;
6063
6064         /* Save these for later */
6065         memcpy (&lmodule->aot_info, info, sizeof (MonoAotFileInfo));
6066         lmodule->has_jitted_code = has_jitted_code;
6067 }
6068
6069 /*
6070  * mono_llvm_emit_aot_data:
6071  *
6072  *   Emit the binary data DATA pointed to by symbol SYMBOL.
6073  */
6074 void
6075 mono_llvm_emit_aot_data (const char *symbol, guint8 *data, int data_len)
6076 {
6077         MonoLLVMModule *lmodule = &aot_module;
6078         LLVMTypeRef type;
6079         LLVMValueRef d;
6080
6081         type = LLVMArrayType (LLVMInt8Type (), data_len);
6082         d = LLVMAddGlobal (lmodule->module, type, symbol);
6083         LLVMSetVisibility (d, LLVMHiddenVisibility);
6084         LLVMSetLinkage (d, LLVMInternalLinkage);
6085         LLVMSetInitializer (d, mono_llvm_create_constant_data_array (data, data_len));
6086         mono_llvm_set_is_constant (d);
6087 }
6088
6089 /* Add a reference to a global defined in JITted code */
6090 static LLVMValueRef
6091 AddJitGlobal (MonoLLVMModule *lmodule, LLVMTypeRef type, const char *name)
6092 {
6093         char *s;
6094         LLVMValueRef v;
6095
6096         s = g_strdup_printf ("%s%s", lmodule->global_prefix, name);
6097         v = LLVMAddGlobal (lmodule->module, type, s);
6098         g_free (s);
6099         return v;
6100 }
6101
6102 static void
6103 emit_aot_file_info (MonoLLVMModule *lmodule)
6104 {
6105         LLVMTypeRef file_info_type;
6106         LLVMTypeRef *eltypes, eltype;
6107         LLVMValueRef info_var;
6108         LLVMValueRef *fields;
6109         int i, nfields, tindex;
6110         MonoAotFileInfo *info;
6111
6112         info = &lmodule->aot_info;
6113
6114         /* Create an LLVM type to represent MonoAotFileInfo */
6115         nfields = 50;
6116         eltypes = g_new (LLVMTypeRef, nfields);
6117         tindex = 0;
6118         eltypes [tindex ++] = LLVMInt32Type ();
6119         eltypes [tindex ++] = LLVMInt32Type ();
6120         /* Symbols */
6121         for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
6122                 eltypes [tindex ++] = LLVMPointerType (LLVMInt8Type (), 0);
6123         /* Scalars */
6124         for (i = 0; i < 13; ++i)
6125                 eltypes [tindex ++] = LLVMInt32Type ();
6126         /* Arrays */
6127         for (i = 0; i < 4; ++i)
6128                 eltypes [tindex ++] = LLVMArrayType (LLVMInt32Type (), MONO_AOT_TRAMP_NUM);
6129         g_assert (tindex == nfields);
6130         file_info_type = LLVMStructCreateNamed (LLVMGetGlobalContext (), "MonoAotFileInfo");
6131         LLVMStructSetBody (file_info_type, eltypes, nfields, FALSE);
6132
6133         info_var = LLVMAddGlobal (lmodule->module, file_info_type, "mono_aot_file_info");
6134         if (lmodule->static_link) {
6135                 LLVMSetVisibility (info_var, LLVMHiddenVisibility);
6136                 LLVMSetLinkage (info_var, LLVMInternalLinkage);
6137         }
6138         fields = g_new (LLVMValueRef, nfields);
6139         tindex = 0;
6140         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->version, FALSE);
6141         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->dummy, FALSE);
6142
6143         /* Symbols */
6144         /*
6145          * We use LLVMGetNamedGlobal () for symbol which are defined in LLVM code, and LLVMAddGlobal ()
6146          * for symbols defined in the .s file emitted by the aot compiler.
6147          */
6148         eltype = eltypes [tindex];
6149         fields [tindex ++] = AddJitGlobal (lmodule, eltype, "jit_got");
6150         fields [tindex ++] = lmodule->got_var;
6151         /* llc defines this directly */
6152         fields [tindex ++] = LLVMAddGlobal (lmodule->module, eltype, lmodule->eh_frame_symbol);
6153         if (TRUE || lmodule->has_jitted_code) {
6154                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "jit_code_start");
6155                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "jit_code_end");
6156                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "method_addresses");
6157         } else {
6158                 fields [tindex ++] = LLVMConstNull (eltype);
6159                 fields [tindex ++] = LLVMConstNull (eltype);
6160                 fields [tindex ++] = LLVMConstNull (eltype);
6161         }
6162         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "blob");
6163         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "class_name_table");
6164         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "class_info_offsets");
6165         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "method_info_offsets");
6166         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "ex_info_offsets");
6167         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "extra_method_info_offsets");
6168         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "extra_method_table");
6169         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "got_info_offsets");
6170         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "llvm_got_info_offsets");
6171         /* Not needed (mem_end) */
6172         fields [tindex ++] = LLVMConstNull (eltype);
6173         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "image_table");
6174         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "assembly_guid");
6175         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "runtime_version");
6176         if (info->trampoline_size [0]) {
6177                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "specific_trampolines");
6178                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "static_rgctx_trampolines");
6179                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "imt_thunks");
6180                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "gsharedvt_arg_trampolines");
6181         } else {
6182                 fields [tindex ++] = LLVMConstNull (eltype);
6183                 fields [tindex ++] = LLVMConstNull (eltype);
6184                 fields [tindex ++] = LLVMConstNull (eltype);
6185                 fields [tindex ++] = LLVMConstNull (eltype);
6186         }
6187         if (lmodule->static_link)
6188                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "globals");
6189         else
6190                 fields [tindex ++] = LLVMConstNull (eltype);
6191         fields [tindex ++] = LLVMGetNamedGlobal (lmodule->module, "assembly_name");
6192         if (TRUE || lmodule->has_jitted_code) {
6193                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "plt");
6194                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "plt_end");
6195                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "unwind_info");
6196                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "unbox_trampolines");
6197                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "unbox_trampolines_end");
6198                 fields [tindex ++] = AddJitGlobal (lmodule, eltype, "unbox_trampoline_addresses");
6199         } else {
6200                 fields [tindex ++] = LLVMConstNull (eltype);
6201                 fields [tindex ++] = LLVMConstNull (eltype);
6202                 fields [tindex ++] = LLVMConstNull (eltype);
6203                 fields [tindex ++] = LLVMConstNull (eltype);
6204                 fields [tindex ++] = LLVMConstNull (eltype);
6205                 fields [tindex ++] = LLVMConstNull (eltype);
6206         }
6207
6208         /* Scalars */
6209         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->plt_got_offset_base, FALSE);
6210         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->got_size, FALSE);
6211         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->plt_size, FALSE);
6212         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->nmethods, FALSE);
6213         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->flags, FALSE);
6214         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->opts, FALSE);
6215         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->simd_opts, FALSE);
6216         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->gc_name_index, FALSE);
6217         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->num_rgctx_fetch_trampolines, FALSE);
6218         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->double_align, FALSE);
6219         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->long_align, FALSE);
6220         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->generic_tramp_num, FALSE);
6221         fields [tindex ++] = LLVMConstInt (LLVMInt32Type (), info->tramp_page_size, FALSE);
6222         /* Arrays */
6223         fields [tindex ++] = llvm_array_from_uints (LLVMInt32Type (), info->num_trampolines, MONO_AOT_TRAMP_NUM);
6224         fields [tindex ++] = llvm_array_from_uints (LLVMInt32Type (), info->trampoline_got_offset_base, MONO_AOT_TRAMP_NUM);
6225         fields [tindex ++] = llvm_array_from_uints (LLVMInt32Type (), info->trampoline_size, MONO_AOT_TRAMP_NUM);
6226         fields [tindex ++] = llvm_array_from_uints (LLVMInt32Type (), info->tramp_page_code_offsets, MONO_AOT_TRAMP_NUM);
6227         g_assert (tindex == nfields);
6228
6229         LLVMSetInitializer (info_var, LLVMConstNamedStruct (file_info_type, fields, nfields));
6230
6231         if (lmodule->static_link) {
6232                 char *s, *p;
6233                 LLVMValueRef var;
6234
6235                 s = g_strdup_printf ("mono_aot_module_%s_info", lmodule->assembly->aname.name);
6236                 /* Get rid of characters which cannot occur in symbols */
6237                 p = s;
6238                 for (p = s; *p; ++p) {
6239                         if (!(isalnum (*p) || *p == '_'))
6240                                 *p = '_';
6241                 }
6242                 var = LLVMAddGlobal (lmodule->module, LLVMPointerType (LLVMInt8Type (), 0), s);
6243                 g_free (s);
6244                 LLVMSetInitializer (var, LLVMConstBitCast (LLVMGetNamedGlobal (lmodule->module, "mono_aot_file_info"), LLVMPointerType (LLVMInt8Type (), 0)));
6245                 LLVMSetLinkage (var, LLVMExternalLinkage);
6246         }
6247 }
6248
6249 /*
6250  * Emit the aot module into the LLVM bitcode file FILENAME.
6251  */
6252 void
6253 mono_llvm_emit_aot_module (const char *filename, const char *cu_name)
6254 {
6255         LLVMTypeRef got_type;
6256         LLVMValueRef real_got;
6257         MonoLLVMModule *module = &aot_module;
6258
6259         /* 
6260          * Create the real got variable and replace all uses of the dummy variable with
6261          * the real one.
6262          */
6263         got_type = LLVMArrayType (aot_module.ptr_type, module->max_got_offset + 1);
6264         real_got = LLVMAddGlobal (aot_module.module, got_type, aot_module.got_symbol);
6265         LLVMSetInitializer (real_got, LLVMConstNull (got_type));
6266         if (module->external_symbols) {
6267                 LLVMSetLinkage (real_got, LLVMExternalLinkage);
6268                 LLVMSetVisibility (real_got, LLVMHiddenVisibility);
6269         } else {
6270                 LLVMSetLinkage (real_got, LLVMInternalLinkage);
6271         }
6272         mono_llvm_replace_uses_of (aot_module.got_var, real_got);
6273
6274         mark_as_used (&aot_module, real_got);
6275
6276         /* Delete the dummy got so it doesn't become a global */
6277         LLVMDeleteGlobal (aot_module.got_var);
6278         aot_module.got_var = real_got;
6279
6280         emit_llvm_used (&aot_module);
6281         emit_dbg_info (&aot_module, filename, cu_name);
6282         emit_aot_file_info (&aot_module);
6283
6284         /* Replace PLT entries for directly callable methods with the methods themselves */
6285         {
6286                 GHashTableIter iter;
6287                 MonoJumpInfo *ji;
6288                 LLVMValueRef callee;
6289
6290                 g_hash_table_iter_init (&iter, aot_module.plt_entries_ji);
6291                 while (g_hash_table_iter_next (&iter, (void**)&ji, (void**)&callee)) {
6292                         if (mono_aot_is_direct_callable (ji)) {
6293                                 LLVMValueRef lmethod;
6294
6295                                 lmethod = g_hash_table_lookup (module->method_to_lmethod, ji->data.method);
6296                                 /* The types might not match because the caller might pass an rgctx */
6297                                 if (lmethod && LLVMTypeOf (callee) == LLVMTypeOf (lmethod)) {
6298                                         mono_llvm_replace_uses_of (callee, lmethod);
6299                                         mono_aot_mark_unused_llvm_plt_entry (ji);
6300                                 }
6301                         }
6302                 }
6303         }
6304
6305 #if 0
6306         {
6307                 char *verifier_err;
6308
6309                 if (LLVMVerifyModule (aot_module.module, LLVMReturnStatusAction, &verifier_err)) {
6310                         g_assert_not_reached ();
6311                 }
6312         }
6313 #endif
6314
6315         LLVMWriteBitcodeToFile (aot_module.module, filename);
6316 }
6317
6318
6319 static LLVMValueRef
6320 md_string (const char *s)
6321 {
6322         return LLVMMDString (s, strlen (s));
6323 }
6324
6325 /* Debugging support */
6326
6327 static void
6328 emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name)
6329 {
6330         LLVMModuleRef module = lmodule->module;
6331         LLVMValueRef args [16], cu_args [16], cu, ver;
6332         int n_cuargs;
6333         char *build_info, *s, *dir;
6334
6335         /*
6336          * This can only be enabled when LLVM code is emitted into a separate object
6337          * file, since the AOT compiler also emits dwarf info,
6338          * and the abbrev indexes will not be correct since llvm has added its own
6339          * abbrevs.
6340          */
6341         if (!lmodule->emit_dwarf)
6342                 return;
6343
6344         /*
6345          * Emit dwarf info in the form of LLVM metadata. There is some
6346          * out-of-date documentation at:
6347          * http://llvm.org/docs/SourceLevelDebugging.html
6348          * but most of this was gathered from the llvm and
6349          * clang sources.
6350          */
6351
6352         n_cuargs = 0;
6353         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_TAG_compile_unit, FALSE);
6354         /* CU name/compilation dir */
6355         dir = g_path_get_dirname (filename);
6356         args [0] = LLVMMDString (cu_name, strlen (cu_name));
6357         args [1] = LLVMMDString (dir, strlen (dir));
6358         cu_args [n_cuargs ++] = LLVMMDNode (args, 2);
6359         g_free (dir);
6360         /* Language */
6361         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_LANG_C99, FALSE);
6362         /* Producer */
6363         build_info = mono_get_runtime_build_info ();
6364         s = g_strdup_printf ("Mono AOT Compiler %s (LLVM)", build_info);
6365         cu_args [n_cuargs ++] = LLVMMDString (s, strlen (s));
6366         g_free (build_info);
6367         /* Optimized */
6368         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6369         /* Flags */
6370         cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
6371         /* Runtime version */
6372         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
6373         /* Enums */
6374         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
6375         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
6376         /* Subprograms */
6377         if (lmodule->subprogram_mds) {
6378                 LLVMValueRef *mds;
6379                 int i;
6380
6381                 mds = g_new0 (LLVMValueRef, lmodule->subprogram_mds->len);
6382                 for (i = 0; i < lmodule->subprogram_mds->len; ++i)
6383                         mds [i] = g_ptr_array_index (lmodule->subprogram_mds, i);
6384                 cu_args [n_cuargs ++] = LLVMMDNode (mds, lmodule->subprogram_mds->len);
6385         } else {
6386                 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
6387         }
6388         /* GVs */
6389         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
6390         /* Imported modules */
6391         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
6392         /* SplitName */
6393         cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
6394         /* DebugEmissionKind = FullDebug */
6395         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6396         cu = LLVMMDNode (cu_args, n_cuargs);
6397         LLVMAddNamedMetadataOperand (module, "llvm.dbg.cu", cu);
6398
6399         args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6400         args [1] = LLVMMDString ("Dwarf Version", strlen ("Dwarf Version"));
6401         args [2] = LLVMConstInt (LLVMInt32Type (), 2, FALSE);
6402         ver = LLVMMDNode (args, 3);
6403         LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
6404
6405         args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6406         args [1] = LLVMMDString ("Debug Info Version", strlen ("Debug Info Version"));
6407         args [2] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6408         ver = LLVMMDNode (args, 3);
6409         LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
6410 }
6411
6412 static LLVMValueRef
6413 emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name)
6414 {
6415         MonoLLVMModule *module = ctx->lmodule;
6416         MonoDebugMethodInfo *minfo = ctx->minfo;
6417         char *source_file, *dir, *filename;
6418         LLVMValueRef md, args [16], ctx_args [16], md_args [64], type_args [16], ctx_md, type_md;
6419         MonoSymSeqPoint *sym_seq_points;
6420         int n_seq_points;
6421
6422         if (!minfo)
6423                 return NULL;
6424
6425         mono_debug_symfile_get_seq_points (minfo, &source_file, NULL, NULL, &sym_seq_points, &n_seq_points);
6426         if (!source_file)
6427                 source_file = g_strdup ("<unknown>");
6428         dir = g_path_get_dirname (source_file);
6429         filename = g_path_get_basename (source_file);
6430
6431         ctx_args [0] = LLVMConstInt (LLVMInt32Type (), 0x29, FALSE);
6432         args [0] = md_string (filename);
6433         args [1] = md_string (dir);
6434         ctx_args [1] = LLVMMDNode (args, 2);
6435         ctx_md = LLVMMDNode (ctx_args, 2);
6436
6437         type_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subroutine_type, FALSE);
6438         type_args [1] = NULL;
6439         type_args [2] = NULL;
6440         type_args [3] = LLVMMDString ("", 0);
6441         type_args [4] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
6442         type_args [5] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
6443         type_args [6] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
6444         type_args [7] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
6445         type_args [8] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
6446         type_args [9] = NULL;
6447         type_args [10] = NULL;
6448         type_args [11] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
6449         type_args [12] = NULL;
6450         type_args [13] = NULL;
6451         type_args [14] = NULL;
6452         type_md = LLVMMDNode (type_args, 14);
6453
6454         /* http://llvm.org/docs/SourceLevelDebugging.html#subprogram-descriptors */
6455         md_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subprogram, FALSE);
6456         /* Source directory + file pair */
6457         args [0] = md_string (filename);
6458         args [1] = md_string (dir);
6459         md_args [1] = LLVMMDNode (args ,2);
6460         md_args [2] = ctx_md;
6461         md_args [3] = md_string (cfg->method->name);
6462         md_args [4] = md_string (name);
6463         md_args [5] = md_string (name);
6464         /* Line number */
6465         if (n_seq_points)
6466                 md_args [6] = LLVMConstInt (LLVMInt32Type (), sym_seq_points [0].line, FALSE);
6467         else
6468                 md_args [6] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6469         /* Type */
6470         md_args [7] = type_md;
6471         /* static */
6472         md_args [8] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
6473         /* not extern */
6474         md_args [9] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
6475         /* Virtuality */
6476         md_args [10] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
6477         /* Index into a virtual function */
6478         md_args [11] = NULL;
6479         md_args [12] = NULL;
6480         /* Flags */
6481         md_args [13] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
6482         /* isOptimized */
6483         md_args [14] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
6484         /* Pointer to LLVM function */
6485         md_args [15] = method;
6486         /* Function template parameter */
6487         md_args [16] = NULL;
6488         /* Function declaration descriptor */
6489         md_args [17] = NULL;
6490         /* List of function variables */
6491         md_args [18] = LLVMMDNode (args, 0);
6492         /* Line number */
6493         md_args [19] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
6494         md = LLVMMDNode (md_args, 20);
6495
6496         if (!module->subprogram_mds)
6497                 module->subprogram_mds = g_ptr_array_new ();
6498         g_ptr_array_add (module->subprogram_mds, md);
6499
6500         g_free (dir);
6501         g_free (filename);
6502         g_free (source_file);
6503         g_free (sym_seq_points);
6504
6505         return md;
6506 }
6507
6508 static void
6509 emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code)
6510 {
6511         MonoCompile *cfg = ctx->cfg;
6512
6513         if (ctx->minfo && cil_code && cil_code >= cfg->header->code && cil_code < cfg->header->code + cfg->header->code_size) {
6514                 MonoDebugSourceLocation *loc;
6515                 LLVMValueRef loc_md, md_args [16];
6516                 int nmd_args;
6517
6518                 loc = mono_debug_symfile_lookup_location (ctx->minfo, cil_code - cfg->header->code);
6519
6520                 if (loc) {
6521                         nmd_args = 0;
6522                         md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->row, FALSE);
6523                         md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->column, FALSE);
6524                         md_args [nmd_args ++] = ctx->dbg_md;
6525                         md_args [nmd_args ++] = NULL;
6526                         loc_md = LLVMMDNode (md_args, nmd_args);
6527                         LLVMSetCurrentDebugLocation (builder, loc_md);
6528                         mono_debug_symfile_free_location (loc);
6529                 }
6530         }
6531 }
6532
6533 /*
6534   DESIGN:
6535   - Emit LLVM IR from the mono IR using the LLVM C API.
6536   - The original arch specific code remains, so we can fall back to it if we run
6537     into something we can't handle.
6538 */
6539
6540 /*  
6541   A partial list of issues:
6542   - Handling of opcodes which can throw exceptions.
6543
6544       In the mono JIT, these are implemented using code like this:
6545           method:
6546       <compare>
6547           throw_pos:
6548           b<cond> ex_label
6549           <rest of code>
6550       ex_label:
6551           push throw_pos - method
6552           call <exception trampoline>
6553
6554           The problematic part is push throw_pos - method, which cannot be represented
6555       in the LLVM IR, since it does not support label values.
6556           -> this can be implemented in AOT mode using inline asm + labels, but cannot
6557           be implemented in JIT mode ?
6558           -> a possible but slower implementation would use the normal exception 
6559       throwing code but it would need to control the placement of the throw code
6560       (it needs to be exactly after the compare+branch).
6561           -> perhaps add a PC offset intrinsics ?
6562
6563   - efficient implementation of .ovf opcodes.
6564
6565           These are currently implemented as:
6566           <ins which sets the condition codes>
6567           b<cond> ex_label
6568
6569           Some overflow opcodes are now supported by LLVM SVN.
6570
6571   - exception handling, unwinding.
6572     - SSA is disabled for methods with exception handlers    
6573         - How to obtain unwind info for LLVM compiled methods ?
6574           -> this is now solved by converting the unwind info generated by LLVM
6575              into our format.
6576         - LLVM uses the c++ exception handling framework, while we use our home grown
6577       code, and couldn't use the c++ one:
6578       - its not supported under VC++, other exotic platforms.
6579           - it might be impossible to support filter clauses with it.
6580
6581   - trampolines.
6582   
6583     The trampolines need a predictable call sequence, since they need to disasm
6584     the calling code to obtain register numbers / offsets.
6585
6586     LLVM currently generates this code in non-JIT mode:
6587            mov    -0x98(%rax),%eax
6588            callq  *%rax
6589     Here, the vtable pointer is lost. 
6590     -> solution: use one vtable trampoline per class.
6591
6592   - passing/receiving the IMT pointer/RGCTX.
6593     -> solution: pass them as normal arguments ?
6594
6595   - argument passing.
6596   
6597           LLVM does not allow the specification of argument registers etc. This means
6598       that all calls are made according to the platform ABI.
6599
6600   - passing/receiving vtypes.
6601
6602       Vtypes passed/received in registers are handled by the front end by using
6603           a signature with scalar arguments, and loading the parts of the vtype into those
6604           arguments.
6605
6606           Vtypes passed on the stack are handled using the 'byval' attribute.
6607
6608   - ldaddr.
6609
6610     Supported though alloca, we need to emit the load/store code.
6611
6612   - types.
6613
6614     The mono JIT uses pointer sized iregs/double fregs, while LLVM uses precisely
6615     typed registers, so we have to keep track of the precise LLVM type of each vreg.
6616     This is made easier because the IR is already in SSA form.
6617     An additional problem is that our IR is not consistent with types, i.e. i32/ia64 
6618         types are frequently used incorrectly.
6619 */
6620
6621 /*
6622   AOT SUPPORT:
6623   Emit LLVM bytecode into a .bc file, compile it using llc into a .s file, then link
6624   it with the file containing the methods emitted by the JIT and the AOT data
6625   structures.
6626 */
6627
6628 /* FIXME: Normalize some aspects of the mono IR to allow easier translation, like:
6629  *   - each bblock should end with a branch
6630  *   - setting the return value, making cfg->ret non-volatile
6631  * - avoid some transformations in the JIT which make it harder for us to generate
6632  *   code.
6633  * - use pointer types to help optimizations.
6634  */