Add another bunch of SIMD intrinsics to the LLVM backend.
[mono.git] / mono / mini / mini-llvm.c
1 /*
2  * mini-llvm.c: llvm "Backend" for the mono JIT
3  *
4  * (C) 2009 Novell, Inc.
5  */
6
7 #include "mini.h"
8 #include <mono/metadata/debug-helpers.h>
9 #include <mono/metadata/mempool-internals.h>
10
11 #ifndef __STDC_LIMIT_MACROS
12 #define __STDC_LIMIT_MACROS
13 #endif
14 #ifndef __STDC_CONSTANT_MACROS
15 #define __STDC_CONSTANT_MACROS
16 #endif
17
18 #include "llvm-c/Core.h"
19 #include "llvm-c/ExecutionEngine.h"
20 #include "llvm-c/BitWriter.h"
21 #include "llvm-c/Analysis.h"
22
23 #include "mini-llvm-cpp.h"
24
25  /*
26   * Information associated by mono with LLVM modules.
27   */
28 typedef struct {
29         LLVMModuleRef module;
30         LLVMValueRef throw, rethrow, throw_corlib_exception;
31         GHashTable *llvm_types;
32         LLVMValueRef got_var;
33         const char *got_symbol;
34         GHashTable *plt_entries;
35 } MonoLLVMModule;
36
37 /*
38  * Information associated by the backend with mono basic blocks.
39  */
40 typedef struct {
41         LLVMBasicBlockRef bblock, end_bblock;
42         LLVMValueRef finally_ind;
43         gboolean added, invoke_target;
44         /* 
45          * If this bblock is the start of a finally clause, this is a list of bblocks it
46          * needs to branch to in ENDFINALLY.
47          */
48         GSList *call_handler_return_bbs;
49         /*
50          * If this bblock is the start of a finally clause, this is the bblock that
51          * CALL_HANDLER needs to branch to.
52          */
53         LLVMBasicBlockRef call_handler_target_bb;
54         /* The list of switch statements generated by ENDFINALLY instructions */
55         GSList *endfinally_switch_ins_list;
56         GSList *phi_nodes;
57 } BBInfo;
58
59 /*
60  * Structure containing emit state
61  */
62 typedef struct {
63         MonoMemPool *mempool;
64
65         /* Maps method names to the corresponding LLVMValueRef */
66         GHashTable *emitted_method_decls;
67
68         MonoCompile *cfg;
69         LLVMValueRef lmethod;
70         MonoLLVMModule *lmodule;
71         LLVMModuleRef module;
72         BBInfo *bblocks;
73         int sindex, default_index, ex_index;
74         LLVMBuilderRef builder;
75         LLVMValueRef *values, *addresses;
76         MonoType **vreg_cli_types;
77         LLVMCallInfo *linfo;
78         MonoMethodSignature *sig;
79         GSList *builders;
80         GHashTable *region_to_handler;
81         LLVMBuilderRef alloca_builder;
82         LLVMValueRef last_alloca;
83         LLVMValueRef rgctx_arg;
84         LLVMTypeRef *vreg_types;
85         gboolean *is_dead;
86         gboolean *unreachable;
87         int *pindexes;
88
89         char temp_name [32];
90 } EmitContext;
91
92 typedef struct {
93         MonoBasicBlock *bb;
94         MonoInst *phi;
95         MonoBasicBlock *in_bb;
96         int sreg;
97 } PhiNode;
98
99 /*
100  * Instruction metadata
101  * This is the same as ins_info, but LREG != IREG.
102  */
103 #ifdef MINI_OP
104 #undef MINI_OP
105 #endif
106 #ifdef MINI_OP3
107 #undef MINI_OP3
108 #endif
109 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
110 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
111 #define NONE ' '
112 #define IREG 'i'
113 #define FREG 'f'
114 #define VREG 'v'
115 #define XREG 'x'
116 #define LREG 'l'
117 /* keep in sync with the enum in mini.h */
118 const char
119 llvm_ins_info[] = {
120 #include "mini-ops.h"
121 };
122 #undef MINI_OP
123 #undef MINI_OP3
124
125 #if SIZEOF_VOID_P == 4
126 #define GET_LONG_IMM(ins) (((guint64)(ins)->inst_ms_word << 32) | (guint64)(guint32)(ins)->inst_ls_word)
127 #else
128 #define GET_LONG_IMM(ins) ((ins)->inst_imm)
129 #endif
130
131 #define LLVM_INS_INFO(opcode) (&llvm_ins_info [((opcode) - OP_START - 1) * 4])
132
133 #if 0
134 #define TRACE_FAILURE(msg) do { printf ("%s\n", msg); } while (0)
135 #else
136 #define TRACE_FAILURE(msg)
137 #endif
138
139 #ifdef TARGET_X86
140 #define IS_TARGET_X86 1
141 #else
142 #define IS_TARGET_X86 0
143 #endif
144
145 #define LLVM_FAILURE(ctx, reason) do { \
146         TRACE_FAILURE (reason); \
147         (ctx)->cfg->exception_message = g_strdup (reason); \
148         (ctx)->cfg->disable_llvm = TRUE; \
149         goto FAILURE; \
150 } while (0)
151
152 #define CHECK_FAILURE(ctx) do { \
153     if ((ctx)->cfg->disable_llvm) \
154                 goto FAILURE; \
155 } while (0)
156
157 static LLVMIntPredicate cond_to_llvm_cond [] = {
158         LLVMIntEQ,
159         LLVMIntNE,
160         LLVMIntSLE,
161         LLVMIntSGE,
162         LLVMIntSLT,
163         LLVMIntSGT,
164         LLVMIntULE,
165         LLVMIntUGE,
166         LLVMIntULT,
167         LLVMIntUGT,
168 };
169
170 static LLVMRealPredicate fpcond_to_llvm_cond [] = {
171         LLVMRealOEQ,
172         LLVMRealUNE,
173         LLVMRealOLE,
174         LLVMRealOGE,
175         LLVMRealOLT,
176         LLVMRealOGT,
177         LLVMRealULE,
178         LLVMRealUGE,
179         LLVMRealULT,
180         LLVMRealUGT,
181 };
182
183 static LLVMExecutionEngineRef ee;
184 static guint32 current_cfg_tls_id;
185
186 static MonoLLVMModule jit_module, aot_module;
187 static gboolean jit_module_inited;
188 static int memset_param_count, memcpy_param_count;
189 static const char *memset_func_name;
190 static const char *memcpy_func_name;
191 static const char *eh_selector_name;
192
193 static void init_jit_module (void);
194
195 /*
196  * IntPtrType:
197  *
198  *   The LLVM type with width == sizeof (gpointer)
199  */
200 static LLVMTypeRef
201 IntPtrType (void)
202 {
203         return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
204 }
205
206 /*
207  * get_vtype_size:
208  *
209  *   Return the size of the LLVM representation of the vtype T.
210  */
211 static guint32
212 get_vtype_size (MonoType *t)
213 {
214         int size;
215
216         size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
217
218         while (size < sizeof (gpointer) && mono_is_power_of_two (size) == -1)
219                 size ++;
220
221         return size;
222 }
223
224 /*
225  * simd_class_to_llvm_type:
226  *
227  *   Return the LLVM type corresponding to the Mono.SIMD class KLASS
228  */
229 static LLVMTypeRef
230 simd_class_to_llvm_type (EmitContext *ctx, MonoClass *klass)
231 {
232         if (!strcmp (klass->name, "Vector2d")) {
233                 return LLVMVectorType (LLVMDoubleType (), 2);
234         } else if (!strcmp (klass->name, "Vector2l")) {
235                 return LLVMVectorType (LLVMInt64Type (), 2);
236         } else if (!strcmp (klass->name, "Vector2ul")) {
237                 return LLVMVectorType (LLVMInt64Type (), 2);
238         } else if (!strcmp (klass->name, "Vector4i")) {
239                 return LLVMVectorType (LLVMInt32Type (), 4);
240         } else if (!strcmp (klass->name, "Vector4ui")) {
241                 return LLVMVectorType (LLVMInt32Type (), 4);
242         } else if (!strcmp (klass->name, "Vector4f")) {
243                 return LLVMVectorType (LLVMFloatType (), 4);
244         } else if (!strcmp (klass->name, "Vector8s")) {
245                 return LLVMVectorType (LLVMInt16Type (), 8);
246         } else if (!strcmp (klass->name, "Vector8us")) {
247                 return LLVMVectorType (LLVMInt16Type (), 8);
248         } else if (!strcmp (klass->name, "Vector16sb")) {
249                 return LLVMVectorType (LLVMInt8Type (), 16);
250         } else if (!strcmp (klass->name, "Vector16b")) {
251                 return LLVMVectorType (LLVMInt8Type (), 16);
252         } else {
253                 printf ("%s\n", klass->name);
254                 NOT_IMPLEMENTED;
255                 return NULL;
256         }
257 }
258
259 /* Return the 128 bit SIMD type corresponding to the mono type TYPE */
260 static inline G_GNUC_UNUSED LLVMTypeRef
261 type_to_simd_type (int type)
262 {
263         switch (type) {
264         case MONO_TYPE_I1:
265                 return LLVMVectorType (LLVMInt8Type (), 16);
266         case MONO_TYPE_I2:
267                 return LLVMVectorType (LLVMInt16Type (), 8);
268         case MONO_TYPE_I4:
269                 return LLVMVectorType (LLVMInt32Type (), 4);
270         case MONO_TYPE_I8:
271                 return LLVMVectorType (LLVMInt64Type (), 2);
272         case MONO_TYPE_R8:
273                 return LLVMVectorType (LLVMDoubleType (), 2);
274         case MONO_TYPE_R4:
275                 return LLVMVectorType (LLVMFloatType (), 4);
276         default:
277                 g_assert_not_reached ();
278                 return NULL;
279         }
280 }
281
282 /*
283  * type_to_llvm_type:
284  *
285  *   Return the LLVM type corresponding to T.
286  */
287 static LLVMTypeRef
288 type_to_llvm_type (EmitContext *ctx, MonoType *t)
289 {
290         if (t->byref)
291                 return LLVMPointerType (LLVMInt8Type (), 0);
292         switch (t->type) {
293         case MONO_TYPE_VOID:
294                 return LLVMVoidType ();
295         case MONO_TYPE_I1:
296                 return LLVMInt8Type ();
297         case MONO_TYPE_I2:
298                 return LLVMInt16Type ();
299         case MONO_TYPE_I4:
300                 return LLVMInt32Type ();
301         case MONO_TYPE_U1:
302                 return LLVMInt8Type ();
303         case MONO_TYPE_U2:
304                 return LLVMInt16Type ();
305         case MONO_TYPE_U4:
306                 return LLVMInt32Type ();
307         case MONO_TYPE_BOOLEAN:
308                 return LLVMInt8Type ();
309         case MONO_TYPE_I8:
310         case MONO_TYPE_U8:
311                 return LLVMInt64Type ();
312         case MONO_TYPE_CHAR:
313                 return LLVMInt16Type ();
314         case MONO_TYPE_R4:
315                 return LLVMFloatType ();
316         case MONO_TYPE_R8:
317                 return LLVMDoubleType ();
318         case MONO_TYPE_I:
319         case MONO_TYPE_U:
320                 return IntPtrType ();
321         case MONO_TYPE_OBJECT:
322         case MONO_TYPE_CLASS:
323         case MONO_TYPE_ARRAY:
324         case MONO_TYPE_SZARRAY:
325         case MONO_TYPE_STRING:
326         case MONO_TYPE_PTR:
327                 return LLVMPointerType (IntPtrType (), 0);
328         case MONO_TYPE_VAR:
329         case MONO_TYPE_MVAR:
330                 /* Because of generic sharing */
331                 return IntPtrType ();
332         case MONO_TYPE_GENERICINST:
333                 if (!mono_type_generic_inst_is_valuetype (t))
334                         return IntPtrType ();
335                 /* Fall through */
336         case MONO_TYPE_VALUETYPE:
337         case MONO_TYPE_TYPEDBYREF: {
338                 MonoClass *klass;
339                 LLVMTypeRef ltype;
340
341                 klass = mono_class_from_mono_type (t);
342
343                 if (MONO_CLASS_IS_SIMD (ctx->cfg, klass))
344                         return simd_class_to_llvm_type (ctx, klass);
345
346                 if (klass->enumtype)
347                         return type_to_llvm_type (ctx, mono_class_enum_basetype (klass));
348                 ltype = g_hash_table_lookup (ctx->lmodule->llvm_types, klass);
349                 if (!ltype) {
350                         int i, size;
351                         LLVMTypeRef *eltypes;
352
353                         size = get_vtype_size (t);
354
355                         eltypes = g_new (LLVMTypeRef, size);
356                         for (i = 0; i < size; ++i)
357                                 eltypes [i] = LLVMInt8Type ();
358
359                         ltype = LLVMStructType (eltypes, size, FALSE);
360                         g_hash_table_insert (ctx->lmodule->llvm_types, klass, ltype);
361                         g_free (eltypes);
362                 }
363                 return ltype;
364         }
365
366         default:
367                 printf ("X: %d\n", t->type);
368                 ctx->cfg->exception_message = g_strdup_printf ("type %s", mono_type_full_name (t));
369                 ctx->cfg->disable_llvm = TRUE;
370                 return NULL;
371         }
372 }
373
374 /*
375  * type_is_unsigned:
376  *
377  *   Return whenever T is an unsigned int type.
378  */
379 static gboolean
380 type_is_unsigned (EmitContext *ctx, MonoType *t)
381 {
382         if (t->byref)
383                 return FALSE;
384         switch (t->type) {
385         case MONO_TYPE_U1:
386         case MONO_TYPE_U2:
387         case MONO_TYPE_U4:
388         case MONO_TYPE_U8:
389                 return TRUE;
390         default:
391                 return FALSE;
392         }
393 }
394
395 /*
396  * type_to_llvm_arg_type:
397  *
398  *   Same as type_to_llvm_type, but treat i8/i16 as i32.
399  */
400 static LLVMTypeRef
401 type_to_llvm_arg_type (EmitContext *ctx, MonoType *t)
402 {
403         LLVMTypeRef ptype = type_to_llvm_type (ctx, t);
404         
405         if (ptype == LLVMInt8Type () || ptype == LLVMInt16Type ()) {
406                 /* 
407                  * LLVM generates code which only sets the lower bits, while JITted
408                  * code expects all the bits to be set.
409                  */
410                 ptype = LLVMInt32Type ();
411         }
412
413         return ptype;
414 }
415
416 /*
417  * llvm_type_to_stack_type:
418  *
419  *   Return the LLVM type which needs to be used when a value of type TYPE is pushed
420  * on the IL stack.
421  */
422 static G_GNUC_UNUSED LLVMTypeRef
423 llvm_type_to_stack_type (LLVMTypeRef type)
424 {
425         if (type == NULL)
426                 return NULL;
427         if (type == LLVMInt8Type ())
428                 return LLVMInt32Type ();
429         else if (type == LLVMInt16Type ())
430                 return LLVMInt32Type ();
431         else if (type == LLVMFloatType ())
432                 return LLVMDoubleType ();
433         else
434                 return type;
435 }
436
437 /*
438  * regtype_to_llvm_type:
439  *
440  *   Return the LLVM type corresponding to the regtype C used in instruction 
441  * descriptions.
442  */
443 static LLVMTypeRef
444 regtype_to_llvm_type (char c)
445 {
446         switch (c) {
447         case 'i':
448                 return LLVMInt32Type ();
449         case 'l':
450                 return LLVMInt64Type ();
451         case 'f':
452                 return LLVMDoubleType ();
453         default:
454                 return NULL;
455         }
456 }
457
458 /*
459  * op_to_llvm_type:
460  *
461  *   Return the LLVM type corresponding to the unary/binary opcode OPCODE.
462  */
463 static LLVMTypeRef
464 op_to_llvm_type (int opcode)
465 {
466         switch (opcode) {
467         case OP_ICONV_TO_I1:
468         case OP_LCONV_TO_I1:
469                 return LLVMInt8Type ();
470         case OP_ICONV_TO_U1:
471         case OP_LCONV_TO_U1:
472                 return LLVMInt8Type ();
473         case OP_ICONV_TO_I2:
474         case OP_LCONV_TO_I2:
475                 return LLVMInt16Type ();
476         case OP_ICONV_TO_U2:
477         case OP_LCONV_TO_U2:
478                 return LLVMInt16Type ();
479         case OP_ICONV_TO_I4:
480         case OP_LCONV_TO_I4:
481                 return LLVMInt32Type ();
482         case OP_ICONV_TO_U4:
483         case OP_LCONV_TO_U4:
484                 return LLVMInt32Type ();
485         case OP_ICONV_TO_I8:
486                 return LLVMInt64Type ();
487         case OP_ICONV_TO_R4:
488                 return LLVMFloatType ();
489         case OP_ICONV_TO_R8:
490                 return LLVMDoubleType ();
491         case OP_ICONV_TO_U8:
492                 return LLVMInt64Type ();
493         case OP_FCONV_TO_I4:
494                 return LLVMInt32Type ();
495         case OP_FCONV_TO_I8:
496                 return LLVMInt64Type ();
497         case OP_FCONV_TO_I1:
498         case OP_FCONV_TO_U1:
499                 return LLVMInt8Type ();
500         case OP_FCONV_TO_I2:
501         case OP_FCONV_TO_U2:
502                 return LLVMInt16Type ();
503         case OP_FCONV_TO_I:
504         case OP_FCONV_TO_U:
505                 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
506         case OP_IADD_OVF:
507         case OP_IADD_OVF_UN:
508         case OP_ISUB_OVF:
509         case OP_ISUB_OVF_UN:
510         case OP_IMUL_OVF:
511         case OP_IMUL_OVF_UN:
512                 return LLVMInt32Type ();
513         case OP_LADD_OVF:
514         case OP_LADD_OVF_UN:
515         case OP_LSUB_OVF:
516         case OP_LSUB_OVF_UN:
517         case OP_LMUL_OVF:
518         case OP_LMUL_OVF_UN:
519                 return LLVMInt64Type ();
520         default:
521                 printf ("%s\n", mono_inst_name (opcode));
522                 g_assert_not_reached ();
523                 return NULL;
524         }
525 }               
526
527 /*
528  * load_store_to_llvm_type:
529  *
530  *   Return the size/sign/zero extension corresponding to the load/store opcode
531  * OPCODE.
532  */
533 static LLVMTypeRef
534 load_store_to_llvm_type (int opcode, int *size, gboolean *sext, gboolean *zext)
535 {
536         *sext = FALSE;
537         *zext = FALSE;
538
539         switch (opcode) {
540         case OP_LOADI1_MEMBASE:
541         case OP_STOREI1_MEMBASE_REG:
542         case OP_STOREI1_MEMBASE_IMM:
543                 *size = 1;
544                 *sext = TRUE;
545                 return LLVMInt8Type ();
546         case OP_LOADU1_MEMBASE:
547         case OP_LOADU1_MEM:
548                 *size = 1;
549                 *zext = TRUE;
550                 return LLVMInt8Type ();
551         case OP_LOADI2_MEMBASE:
552         case OP_STOREI2_MEMBASE_REG:
553         case OP_STOREI2_MEMBASE_IMM:
554                 *size = 2;
555                 *sext = TRUE;
556                 return LLVMInt16Type ();
557         case OP_LOADU2_MEMBASE:
558         case OP_LOADU2_MEM:
559                 *size = 2;
560                 *zext = TRUE;
561                 return LLVMInt16Type ();
562         case OP_LOADI4_MEMBASE:
563         case OP_LOADU4_MEMBASE:
564         case OP_LOADI4_MEM:
565         case OP_LOADU4_MEM:
566         case OP_STOREI4_MEMBASE_REG:
567         case OP_STOREI4_MEMBASE_IMM:
568                 *size = 4;
569                 return LLVMInt32Type ();
570         case OP_LOADI8_MEMBASE:
571         case OP_LOADI8_MEM:
572         case OP_STOREI8_MEMBASE_REG:
573         case OP_STOREI8_MEMBASE_IMM:
574                 *size = 8;
575                 return LLVMInt64Type ();
576         case OP_LOADR4_MEMBASE:
577         case OP_STORER4_MEMBASE_REG:
578                 *size = 4;
579                 return LLVMFloatType ();
580         case OP_LOADR8_MEMBASE:
581         case OP_STORER8_MEMBASE_REG:
582                 *size = 8;
583                 return LLVMDoubleType ();
584         case OP_LOAD_MEMBASE:
585         case OP_LOAD_MEM:
586         case OP_STORE_MEMBASE_REG:
587         case OP_STORE_MEMBASE_IMM:
588                 *size = sizeof (gpointer);
589                 return IntPtrType ();
590         default:
591                 g_assert_not_reached ();
592                 return NULL;
593         }
594 }
595
596 /*
597  * ovf_op_to_intrins:
598  *
599  *   Return the LLVM intrinsics corresponding to the overflow opcode OPCODE.
600  */
601 static const char*
602 ovf_op_to_intrins (int opcode)
603 {
604         switch (opcode) {
605         case OP_IADD_OVF:
606                 return "llvm.sadd.with.overflow.i32";
607         case OP_IADD_OVF_UN:
608                 return "llvm.uadd.with.overflow.i32";
609         case OP_ISUB_OVF:
610                 return "llvm.ssub.with.overflow.i32";
611         case OP_ISUB_OVF_UN:
612                 return "llvm.usub.with.overflow.i32";
613         case OP_IMUL_OVF:
614                 return "llvm.smul.with.overflow.i32";
615         case OP_IMUL_OVF_UN:
616                 return "llvm.umul.with.overflow.i32";
617         case OP_LADD_OVF:
618                 return "llvm.sadd.with.overflow.i64";
619         case OP_LADD_OVF_UN:
620                 return "llvm.uadd.with.overflow.i64";
621         case OP_LSUB_OVF:
622                 return "llvm.ssub.with.overflow.i64";
623         case OP_LSUB_OVF_UN:
624                 return "llvm.usub.with.overflow.i64";
625         case OP_LMUL_OVF:
626                 return "llvm.smul.with.overflow.i64";
627         case OP_LMUL_OVF_UN:
628                 return "llvm.umul.with.overflow.i64";
629         default:
630                 g_assert_not_reached ();
631                 return NULL;
632         }
633 }
634
635 static const char*
636 simd_op_to_intrins (int opcode)
637 {
638         switch (opcode) {
639 #if defined(TARGET_X86) || defined(TARGET_AMD64)
640         case OP_MINPD:
641                 return "llvm.x86.sse2.min.pd";
642         case OP_MINPS:
643                 return "llvm.x86.sse.min.ps";
644         case OP_PMIND_UN:
645                 return "llvm.x86.sse41.pminud";
646         case OP_PMINW_UN:
647                 return "llvm.x86.sse41.pminuw";
648         case OP_PMINB_UN:
649                 return "llvm.x86.sse2.pminu.b";
650         case OP_PMINW:
651                 return "llvm.x86.sse2.pmins.w";
652         case OP_MAXPD:
653                 return "llvm.x86.sse2.max.pd";
654         case OP_MAXPS:
655                 return "llvm.x86.sse.max.ps";
656         case OP_HADDPD:
657                 return "llvm.x86.sse3.hadd.pd";
658         case OP_HADDPS:
659                 return "llvm.x86.sse3.hadd.ps";
660         case OP_HSUBPD:
661                 return "llvm.x86.sse3.hsub.pd";
662         case OP_HSUBPS:
663                 return "llvm.x86.sse3.hsub.ps";
664         case OP_PMAXD_UN:
665                 return "llvm.x86.sse41.pmaxud";
666         case OP_PMAXW_UN:
667                 return "llvm.x86.sse41.pmaxuw";
668         case OP_PMAXB_UN:
669                 return "llvm.x86.sse2.pmaxu.b";
670         case OP_ADDSUBPD:
671                 return "llvm.x86.sse3.addsub.pd";
672         case OP_EXTRACT_MASK:
673                 return "llvm.x86.sse2.pmovmskb.128";
674         case OP_PSHRW:
675                 return "llvm.x86.sse2.psrli.w";
676         case OP_PSHRD:
677                 return "llvm.x86.sse2.psrli.d";
678         case OP_PSHRQ:
679                 return "llvm.x86.sse2.psrli.q";
680         case OP_PSHLW:
681                 return "llvm.x86.sse2.pslli.w";
682         case OP_PSHLD:
683                 return "llvm.x86.sse2.pslli.d";
684         case OP_PSHLQ:
685                 return "llvm.x86.sse2.pslli.q";
686         case OP_PADDB_SAT:
687                 return "llvm.x86.sse2.padds.b";
688         case OP_PADDW_SAT:
689                 return "llvm.x86.sse2.padds.w";
690         case OP_PSUBB_SAT:
691                 return "llvm.x86.sse2.psubs.b";
692         case OP_PSUBW_SAT:
693                 return "llvm.x86.sse2.psubs.w";
694         case OP_PADDB_SAT_UN:
695                 return "llvm.x86.sse2.paddus.b";
696         case OP_PADDW_SAT_UN:
697                 return "llvm.x86.sse2.paddus.w";
698         case OP_PSUBB_SAT_UN:
699                 return "llvm.x86.sse2.psubus.b";
700         case OP_PSUBW_SAT_UN:
701                 return "llvm.x86.sse2.psubus.w";
702         case OP_PCMPEQB:
703                 return "llvm.x86.sse2.pcmpeq.b";
704         case OP_PCMPEQW:
705                 return "llvm.x86.sse2.pcmpeq.w";
706         case OP_PCMPEQD:
707                 return "llvm.x86.sse2.pcmpeq.d";
708         case OP_PCMPEQQ:
709                 return "llvm.x86.sse41.pcmpeqq";
710         case OP_PCMPGTB:
711                 return "llvm.x86.sse2.pcmpgt.b";
712         case OP_CVTDQ2PD:
713                 return "llvm.x86.sse2.cvtdq2pd";
714         case OP_CVTDQ2PS:
715                 return "llvm.x86.sse2.cvtdq2ps";
716         case OP_CVTPD2DQ:
717                 return "llvm.x86.sse2.cvtpd2dq";
718         case OP_CVTPS2DQ:
719                 return "llvm.x86.sse2.cvtps2dq";
720         case OP_CVTPD2PS:
721                 return "llvm.x86.sse2.cvtpd2ps";
722         case OP_CVTPS2PD:
723                 return "llvm.x86.sse2.cvtps2pd";
724         case OP_CVTTPD2DQ:
725                 return "llvm.x86.sse2.cvttpd2dq";
726         case OP_CVTTPS2DQ:
727                 return "llvm.x86.sse2.cvttps2dq";
728         case OP_COMPPS:
729                 return "llvm.x86.sse.cmp.ps";
730         case OP_COMPPD:
731                 return "llvm.x86.sse2.cmp.pd";
732 #endif
733         default:
734                 g_assert_not_reached ();
735                 return NULL;
736         }
737 }
738
739 static LLVMTypeRef
740 simd_op_to_llvm_type (int opcode)
741 {
742 #if defined(TARGET_X86) || defined(TARGET_AMD64)
743         switch (opcode) {
744         case OP_EXTRACT_R8:
745         case OP_EXPAND_R8:
746                 return type_to_simd_type (MONO_TYPE_R8);
747         case OP_EXTRACT_I8:
748         case OP_EXPAND_I8:
749                 return type_to_simd_type (MONO_TYPE_I8);
750         case OP_EXTRACT_I4:
751         case OP_EXPAND_I4:
752                 return type_to_simd_type (MONO_TYPE_I4);
753         case OP_EXTRACT_I2:
754         case OP_EXTRACT_U2:
755         case OP_EXTRACTX_U2:
756         case OP_EXPAND_I2:
757                 return type_to_simd_type (MONO_TYPE_I2);
758         case OP_EXTRACT_I1:
759         case OP_EXTRACT_U1:
760         case OP_EXPAND_I1:
761                 return type_to_simd_type (MONO_TYPE_I1);
762         case OP_EXPAND_R4:
763                 return type_to_simd_type (MONO_TYPE_R4);
764         case OP_CVTDQ2PD:
765         case OP_CVTDQ2PS:
766                 return type_to_simd_type (MONO_TYPE_I4);
767         case OP_CVTPD2DQ:
768         case OP_CVTPD2PS:
769         case OP_CVTTPD2DQ:
770                 return type_to_simd_type (MONO_TYPE_R8);
771         case OP_CVTPS2DQ:
772         case OP_CVTPS2PD:
773         case OP_CVTTPS2DQ:
774                 return type_to_simd_type (MONO_TYPE_R4);
775         case OP_EXTRACT_MASK:
776                 return type_to_simd_type (MONO_TYPE_I1);
777         default:
778                 g_assert_not_reached ();
779                 return NULL;
780         }
781 #else
782         return NULL;
783 #endif
784 }
785
786 /*
787  * get_bb:
788  *
789  *   Return the LLVM basic block corresponding to BB.
790  */
791 static LLVMBasicBlockRef
792 get_bb (EmitContext *ctx, MonoBasicBlock *bb)
793 {
794         char bb_name [128];
795
796         if (ctx->bblocks [bb->block_num].bblock == NULL) {
797                 sprintf (bb_name, "BB%d", bb->block_num);
798
799                 ctx->bblocks [bb->block_num].bblock = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
800                 ctx->bblocks [bb->block_num].end_bblock = ctx->bblocks [bb->block_num].bblock;
801         }
802
803         return ctx->bblocks [bb->block_num].bblock;
804 }
805
806 /* 
807  * get_end_bb:
808  *
809  *   Return the last LLVM bblock corresponding to BB.
810  * This might not be equal to the bb returned by get_bb () since we need to generate
811  * multiple LLVM bblocks for a mono bblock to handle throwing exceptions.
812  */
813 static LLVMBasicBlockRef
814 get_end_bb (EmitContext *ctx, MonoBasicBlock *bb)
815 {
816         get_bb (ctx, bb);
817         return ctx->bblocks [bb->block_num].end_bblock;
818 }
819
820 static LLVMBasicBlockRef
821 gen_bb (EmitContext *ctx, const char *prefix)
822 {
823         char bb_name [128];
824
825         sprintf (bb_name, "%s%d", prefix, ++ ctx->ex_index);
826         return LLVMAppendBasicBlock (ctx->lmethod, bb_name);
827 }
828
829 /*
830  * resolve_patch:
831  *
832  *   Return the target of the patch identified by TYPE and TARGET.
833  */
834 static gpointer
835 resolve_patch (MonoCompile *cfg, MonoJumpInfoType type, gconstpointer target)
836 {
837         MonoJumpInfo ji;
838
839         memset (&ji, 0, sizeof (ji));
840         ji.type = type;
841         ji.data.target = target;
842
843         return mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
844 }
845
846 /*
847  * convert_full:
848  *
849  *   Emit code to convert the LLVM value V to DTYPE.
850  */
851 static LLVMValueRef
852 convert_full (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype, gboolean is_unsigned)
853 {
854         LLVMTypeRef stype = LLVMTypeOf (v);
855
856         if (stype != dtype) {
857                 gboolean ext = FALSE;
858
859                 /* Extend */
860                 if (dtype == LLVMInt64Type () && (stype == LLVMInt32Type () || stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
861                         ext = TRUE;
862                 else if (dtype == LLVMInt32Type () && (stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
863                         ext = TRUE;
864                 else if (dtype == LLVMInt16Type () && (stype == LLVMInt8Type ()))
865                         ext = TRUE;
866
867                 if (ext)
868                         return is_unsigned ? LLVMBuildZExt (ctx->builder, v, dtype, "") : LLVMBuildSExt (ctx->builder, v, dtype, "");
869
870                 if (dtype == LLVMDoubleType () && stype == LLVMFloatType ())
871                         return LLVMBuildFPExt (ctx->builder, v, dtype, "");
872
873                 /* Trunc */
874                 if (stype == LLVMInt64Type () && (dtype == LLVMInt32Type () || dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
875                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
876                 if (stype == LLVMInt32Type () && (dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
877                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
878                 if (stype == LLVMInt16Type () && dtype == LLVMInt8Type ())
879                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
880                 if (stype == LLVMDoubleType () && dtype == LLVMFloatType ())
881                         return LLVMBuildFPTrunc (ctx->builder, v, dtype, "");
882
883                 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind && LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
884                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
885                 if (LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
886                         return LLVMBuildIntToPtr (ctx->builder, v, dtype, "");
887                 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind)
888                         return LLVMBuildPtrToInt (ctx->builder, v, dtype, "");
889
890 #ifdef MONO_ARCH_SOFT_FLOAT
891                 if (stype == LLVMInt32Type () && dtype == LLVMFloatType ())
892                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
893                 if (stype == LLVMInt32Type () && dtype == LLVMDoubleType ())
894                         return LLVMBuildBitCast (ctx->builder, LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), ""), dtype, "");
895 #endif
896
897                 if (LLVMGetTypeKind (stype) == LLVMVectorTypeKind && LLVMGetTypeKind (dtype) == LLVMVectorTypeKind)
898                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
899
900                 LLVMDumpValue (v);
901                 LLVMDumpValue (LLVMConstNull (dtype));
902                 g_assert_not_reached ();
903                 return NULL;
904         } else {
905                 return v;
906         }
907 }
908
909 static LLVMValueRef
910 convert (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype)
911 {
912         return convert_full (ctx, v, dtype, FALSE);
913 }
914
915 /*
916  * emit_volatile_load:
917  *
918  *   If vreg is volatile, emit a load from its address.
919  */
920 static LLVMValueRef
921 emit_volatile_load (EmitContext *ctx, int vreg)
922 {
923         MonoType *t;
924
925         LLVMValueRef v = LLVMBuildLoad (ctx->builder, ctx->addresses [vreg], "");
926         t = ctx->vreg_cli_types [vreg];
927         if (t && !t->byref) {
928                 /* 
929                  * Might have to zero extend since llvm doesn't have 
930                  * unsigned types.
931                  */
932                 if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_U2 || t->type == MONO_TYPE_CHAR || t->type == MONO_TYPE_BOOLEAN)
933                         v = LLVMBuildZExt (ctx->builder, v, LLVMInt32Type (), "");
934                 else if (t->type == MONO_TYPE_U8)
935                         v = LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), "");
936         }
937
938         return v;
939 }
940
941 /*
942  * emit_volatile_store:
943  *
944  *   If VREG is volatile, emit a store from its value to its address.
945  */
946 static void
947 emit_volatile_store (EmitContext *ctx, int vreg)
948 {
949         MonoInst *var = get_vreg_to_inst (ctx->cfg, vreg);
950
951         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
952                 g_assert (ctx->addresses [vreg]);
953                 LLVMBuildStore (ctx->builder, convert (ctx, ctx->values [vreg], type_to_llvm_type (ctx, var->inst_vtype)), ctx->addresses [vreg]);
954         }
955 }
956
957 typedef struct {
958         /* 
959          * Maps parameter indexes in the original signature to parameter indexes
960          * in the LLVM signature.
961          */
962         int *pindexes;
963         /* The indexes of various special arguments in the LLVM signature */
964         int vret_arg_pindex, this_arg_pindex, rgctx_arg_pindex, imt_arg_pindex;
965 } LLVMSigInfo;
966
967 /*
968  * sig_to_llvm_sig_full:
969  *
970  *   Return the LLVM signature corresponding to the mono signature SIG using the
971  * calling convention information in CINFO. Return parameter mapping information in SINFO.
972  */
973 static LLVMTypeRef
974 sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *cinfo,
975                                           LLVMSigInfo *sinfo)
976 {
977         LLVMTypeRef ret_type;
978         LLVMTypeRef *param_types = NULL;
979         LLVMTypeRef res;
980         int i, j, pindex, vret_arg_pindex = 0;
981         int *pindexes;
982         gboolean vretaddr = FALSE;
983
984         if (sinfo)
985                 memset (sinfo, 0, sizeof (LLVMSigInfo));
986
987         ret_type = type_to_llvm_type (ctx, sig->ret);
988         CHECK_FAILURE (ctx);
989
990         if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
991                 /* LLVM models this by returning an aggregate value */
992                 if (cinfo->ret.pair_storage [0] == LLVMArgInIReg && cinfo->ret.pair_storage [1] == LLVMArgNone) {
993                         LLVMTypeRef members [2];
994
995                         members [0] = IntPtrType ();
996                         ret_type = LLVMStructType (members, 1, FALSE);
997                 } else {
998                         g_assert_not_reached ();
999                 }
1000         } else if (cinfo && MONO_TYPE_ISSTRUCT (sig->ret)) {
1001                 g_assert (cinfo->ret.storage == LLVMArgVtypeRetAddr);
1002                 vretaddr = TRUE;
1003                 ret_type = LLVMVoidType ();
1004         }
1005
1006         pindexes = g_new0 (int, sig->param_count);
1007         param_types = g_new0 (LLVMTypeRef, (sig->param_count * 2) + 3);
1008         pindex = 0;
1009         if (cinfo && cinfo->rgctx_arg) {
1010                 if (sinfo)
1011                         sinfo->rgctx_arg_pindex = pindex;
1012                 param_types [pindex] = IntPtrType ();
1013                 pindex ++;
1014         }
1015         if (cinfo && cinfo->imt_arg && IS_LLVM_MONO_BRANCH) {
1016                 if (sinfo)
1017                         sinfo->imt_arg_pindex = pindex;
1018                 param_types [pindex] = IntPtrType ();
1019                 pindex ++;
1020         }
1021         if (vretaddr) {
1022                 /* Compute the index in the LLVM signature where the vret arg needs to be passed */
1023                 vret_arg_pindex = pindex;
1024                 if (cinfo->vret_arg_index == 1) {
1025                         /* Add the slots consumed by the first argument */
1026                         LLVMArgInfo *ainfo = &cinfo->args [0];
1027                         switch (ainfo->storage) {
1028                         case LLVMArgVtypeInReg:
1029                                 for (j = 0; j < 2; ++j) {
1030                                         if (ainfo->pair_storage [j] == LLVMArgInIReg)
1031                                                 vret_arg_pindex ++;
1032                                 }
1033                                 break;
1034                         default:
1035                                 vret_arg_pindex ++;
1036                         }
1037                 }
1038
1039                 if (sinfo)
1040                         sinfo->vret_arg_pindex = vret_arg_pindex;
1041         }                               
1042
1043         if (vretaddr && vret_arg_pindex == pindex)
1044                 param_types [pindex ++] = IntPtrType ();
1045         if (sig->hasthis) {
1046                 if (sinfo)
1047                         sinfo->this_arg_pindex = pindex;
1048                 param_types [pindex ++] = IntPtrType ();
1049         }
1050         if (vretaddr && vret_arg_pindex == pindex)
1051                 param_types [pindex ++] = IntPtrType ();
1052         for (i = 0; i < sig->param_count; ++i) {
1053                 if (vretaddr && vret_arg_pindex == pindex)
1054                         param_types [pindex ++] = IntPtrType ();
1055                 pindexes [i] = pindex;
1056                 if (cinfo && cinfo->args [i + sig->hasthis].storage == LLVMArgVtypeInReg) {
1057                         for (j = 0; j < 2; ++j) {
1058                                 switch (cinfo->args [i + sig->hasthis].pair_storage [j]) {
1059                                 case LLVMArgInIReg:
1060                                         param_types [pindex ++] = LLVMIntType (sizeof (gpointer) * 8);
1061                                         break;
1062                                 case LLVMArgNone:
1063                                         break;
1064                                 default:
1065                                         g_assert_not_reached ();
1066                                 }
1067                         }
1068                 } else if (cinfo && cinfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal) {
1069                         param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1070                         CHECK_FAILURE (ctx);
1071                         param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1072                         pindex ++;
1073                 } else {
1074                         param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1075                 }                       
1076         }
1077         if (vretaddr && vret_arg_pindex == pindex)
1078                 param_types [pindex ++] = IntPtrType ();
1079
1080         CHECK_FAILURE (ctx);
1081
1082         res = LLVMFunctionType (ret_type, param_types, pindex, FALSE);
1083         g_free (param_types);
1084
1085         if (sinfo) {
1086                 sinfo->pindexes = pindexes;
1087         } else {
1088                 g_free (pindexes);
1089         }
1090
1091         return res;
1092
1093  FAILURE:
1094         g_free (param_types);
1095
1096         return NULL;
1097 }
1098
1099 static LLVMTypeRef
1100 sig_to_llvm_sig (EmitContext *ctx, MonoMethodSignature *sig)
1101 {
1102         return sig_to_llvm_sig_full (ctx, sig, NULL, NULL);
1103 }
1104
1105 /*
1106  * LLVMFunctionType1:
1107  *
1108  *   Create an LLVM function type from the arguments.
1109  */
1110 static G_GNUC_UNUSED LLVMTypeRef 
1111 LLVMFunctionType1(LLVMTypeRef ReturnType,
1112                                   LLVMTypeRef ParamType1,
1113                                   int IsVarArg)
1114 {
1115         LLVMTypeRef param_types [1];
1116
1117         param_types [0] = ParamType1;
1118
1119         return LLVMFunctionType (ReturnType, param_types, 1, IsVarArg);
1120 }
1121
1122 /*
1123  * LLVMFunctionType2:
1124  *
1125  *   Create an LLVM function type from the arguments.
1126  */
1127 static LLVMTypeRef 
1128 LLVMFunctionType2(LLVMTypeRef ReturnType,
1129                                   LLVMTypeRef ParamType1,
1130                                   LLVMTypeRef ParamType2,
1131                                   int IsVarArg)
1132 {
1133         LLVMTypeRef param_types [2];
1134
1135         param_types [0] = ParamType1;
1136         param_types [1] = ParamType2;
1137
1138         return LLVMFunctionType (ReturnType, param_types, 2, IsVarArg);
1139 }
1140
1141 /*
1142  * LLVMFunctionType3:
1143  *
1144  *   Create an LLVM function type from the arguments.
1145  */
1146 static LLVMTypeRef 
1147 LLVMFunctionType3(LLVMTypeRef ReturnType,
1148                                   LLVMTypeRef ParamType1,
1149                                   LLVMTypeRef ParamType2,
1150                                   LLVMTypeRef ParamType3,
1151                                   int IsVarArg)
1152 {
1153         LLVMTypeRef param_types [3];
1154
1155         param_types [0] = ParamType1;
1156         param_types [1] = ParamType2;
1157         param_types [2] = ParamType3;
1158
1159         return LLVMFunctionType (ReturnType, param_types, 3, IsVarArg);
1160 }
1161
1162 /*
1163  * create_builder:
1164  *
1165  *   Create an LLVM builder and remember it so it can be freed later.
1166  */
1167 static LLVMBuilderRef
1168 create_builder (EmitContext *ctx)
1169 {
1170         LLVMBuilderRef builder = LLVMCreateBuilder ();
1171
1172         ctx->builders = g_slist_prepend_mempool (ctx->cfg->mempool, ctx->builders, builder);
1173
1174         return builder;
1175 }
1176
1177 static LLVMValueRef
1178 get_plt_entry (EmitContext *ctx, LLVMTypeRef llvm_sig, MonoJumpInfoType type, gconstpointer data)
1179 {
1180         char *callee_name = mono_aot_get_plt_symbol (type, data);
1181         LLVMValueRef callee;
1182
1183         if (!callee_name)
1184                 return NULL;
1185
1186         if (ctx->cfg->compile_aot)
1187                 /* Add a patch so referenced wrappers can be compiled in full aot mode */
1188                 mono_add_patch_info (ctx->cfg, 0, type, data);
1189
1190         // FIXME: Locking
1191         callee = g_hash_table_lookup (ctx->lmodule->plt_entries, callee_name);
1192         if (!callee) {
1193                 callee = LLVMAddFunction (ctx->module, callee_name, llvm_sig);
1194
1195                 LLVMSetVisibility (callee, LLVMHiddenVisibility);
1196
1197                 g_hash_table_insert (ctx->lmodule->plt_entries, (char*)callee_name, callee);
1198         }
1199
1200         return callee;
1201 }
1202
1203 static int
1204 get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
1205 {
1206         MonoMethodHeader *header = cfg->header;
1207         MonoExceptionClause *clause;
1208         int i;
1209
1210         /* Directly */
1211         if (bb->region != -1 && MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
1212                 return (bb->region >> 8) - 1;
1213
1214         /* Indirectly */
1215         for (i = 0; i < header->num_clauses; ++i) {
1216                 clause = &header->clauses [i];
1217                            
1218                 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset) && clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
1219                         return i;
1220         }
1221
1222         return -1;
1223 }
1224
1225 static void
1226 set_metadata_flag (LLVMValueRef v, const char *flag_name)
1227 {
1228 #if LLVM_CHECK_VERSION (2, 8)
1229         LLVMValueRef md_arg;
1230         int md_kind;
1231         
1232         if (!IS_LLVM_MONO_BRANCH)
1233                 return;
1234
1235         md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1236         md_arg = LLVMMDString ("mono", 4);
1237         LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1238 #endif
1239 }
1240
1241 /*
1242  * emit_call:
1243  *
1244  *   Emit an LLVM call or invoke instruction depending on whenever the call is inside
1245  * a try region.
1246  */
1247 static LLVMValueRef
1248 emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LLVMValueRef callee, LLVMValueRef *args, int pindex)
1249 {
1250         MonoCompile *cfg = ctx->cfg;
1251         LLVMValueRef lcall;
1252         LLVMBuilderRef builder = *builder_ref;
1253         int clause_index;
1254
1255         clause_index = get_handler_clause (cfg, bb);
1256
1257         if (clause_index != -1) {
1258                 MonoMethodHeader *header = cfg->header;
1259                 MonoExceptionClause *ec = &header->clauses [clause_index];
1260                 MonoBasicBlock *tblock;
1261                 LLVMBasicBlockRef ex_bb, noex_bb;
1262
1263                 /*
1264                  * Have to use an invoke instead of a call, branching to the
1265                  * handler bblock of the clause containing this bblock.
1266                  */
1267
1268                 g_assert (ec->flags == MONO_EXCEPTION_CLAUSE_NONE || ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY);
1269
1270                 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
1271                 g_assert (tblock);
1272
1273                 ctx->bblocks [tblock->block_num].invoke_target = TRUE;
1274
1275                 ex_bb = get_bb (ctx, tblock);
1276
1277                 noex_bb = gen_bb (ctx, "NOEX_BB");
1278
1279                 /* Use an invoke */
1280                 lcall = LLVMBuildInvoke (builder, callee, args, pindex, noex_bb, ex_bb, "");
1281
1282                 builder = ctx->builder = create_builder (ctx);
1283                 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1284
1285                 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1286         } else {
1287                 lcall = LLVMBuildCall (builder, callee, args, pindex, "");
1288                 ctx->builder = builder;
1289         }
1290
1291         *builder_ref = ctx->builder;
1292
1293         return lcall;
1294 }
1295
1296 static LLVMValueRef
1297 emit_load (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting)
1298 {
1299         const char *intrins_name;
1300         LLVMValueRef args [16], res;
1301         LLVMTypeRef addr_type;
1302
1303         if (is_faulting && bb->region != -1 && IS_LLVM_MONO_BRANCH) {
1304                 /*
1305                  * We handle loads which can fault by calling a mono specific intrinsic
1306                  * using an invoke, so they are handled properly inside try blocks.
1307                  * We can't use this outside clauses, since LLVM optimizes intrinsics which
1308                  * are marked with IntrReadArgMem.
1309                  */
1310                 switch (size) {
1311                 case 1:
1312                         intrins_name = "llvm.mono.load.i8.p0i8";
1313                         break;
1314                 case 2:
1315                         intrins_name = "llvm.mono.load.i16.p0i16";
1316                         break;
1317                 case 4:
1318                         intrins_name = "llvm.mono.load.i32.p0i32";
1319                         break;
1320                 case 8:
1321                         intrins_name = "llvm.mono.load.i64.p0i64";
1322                         break;
1323                 default:
1324                         g_assert_not_reached ();
1325                 }
1326
1327                 addr_type = LLVMTypeOf (addr);
1328                 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0) || addr_type == LLVMPointerType (LLVMFloatType (), 0))
1329                         addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1330
1331                 args [0] = addr;
1332                 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1333                 args [2] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1334                 res = emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 3);
1335
1336                 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0))
1337                         res = LLVMBuildBitCast (*builder_ref, res, LLVMDoubleType (), "");
1338                 else if (addr_type == LLVMPointerType (LLVMFloatType (), 0))
1339                         res = LLVMBuildBitCast (*builder_ref, res, LLVMFloatType (), "");
1340                 
1341                 return res;
1342         } else {
1343                 LLVMValueRef res;
1344
1345                 /* 
1346                  * We emit volatile loads for loads which can fault, because otherwise
1347                  * LLVM will generate invalid code when encountering a load from a
1348                  * NULL address.
1349                  */
1350                  res = mono_llvm_build_load (*builder_ref, addr, name, is_faulting);
1351
1352                  /* Mark it with a custom metadata */
1353                  /*
1354                  if (is_faulting)
1355                          set_metadata_flag (res, "mono.faulting.load");
1356                  */
1357
1358                  return res;
1359         }
1360 }
1361
1362 static void
1363 emit_store (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting)
1364 {
1365         const char *intrins_name;
1366         LLVMValueRef args [16];
1367
1368         if (is_faulting && bb->region != -1 && IS_LLVM_MONO_BRANCH) {
1369                 switch (size) {
1370                 case 1:
1371                         intrins_name = "llvm.mono.store.i8.p0i8";
1372                         break;
1373                 case 2:
1374                         intrins_name = "llvm.mono.store.i16.p0i16";
1375                         break;
1376                 case 4:
1377                         intrins_name = "llvm.mono.store.i32.p0i32";
1378                         break;
1379                 case 8:
1380                         intrins_name = "llvm.mono.store.i64.p0i64";
1381                         break;
1382                 default:
1383                         g_assert_not_reached ();
1384                 }
1385
1386                 if (LLVMTypeOf (value) == LLVMDoubleType () || LLVMTypeOf (value) == LLVMFloatType ()) {
1387                         value = LLVMBuildBitCast (*builder_ref, value, LLVMIntType (size * 8), "");
1388                         addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1389                 }
1390
1391                 args [0] = value;
1392                 args [1] = addr;
1393                 args [2] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1394                 args [3] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1395                 emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 4);
1396         } else {
1397                 LLVMBuildStore (*builder_ref, value, addr);
1398         }
1399 }
1400
1401 /*
1402  * emit_cond_system_exception:
1403  *
1404  *   Emit code to throw the exception EXC_TYPE if the condition CMP is false.
1405  * Might set the ctx exception.
1406  */
1407 static void
1408 emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp)
1409 {
1410         LLVMBasicBlockRef ex_bb, noex_bb;
1411         LLVMBuilderRef builder;
1412         MonoClass *exc_class;
1413         LLVMValueRef args [2];
1414         
1415         ex_bb = gen_bb (ctx, "EX_BB");
1416         noex_bb = gen_bb (ctx, "NOEX_BB");
1417
1418         LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb);
1419
1420         exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type);
1421         g_assert (exc_class);
1422
1423         /* Emit exception throwing code */
1424         builder = create_builder (ctx);
1425         LLVMPositionBuilderAtEnd (builder, ex_bb);
1426
1427         if (!ctx->lmodule->throw_corlib_exception) {
1428                 LLVMValueRef callee;
1429                 LLVMTypeRef sig;
1430                 const char *icall_name;
1431
1432                 MonoMethodSignature *throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 2);
1433                 throw_sig->ret = &mono_get_void_class ()->byval_arg;
1434                 throw_sig->params [0] = &mono_get_int32_class ()->byval_arg;
1435                 if (IS_LLVM_MONO_BRANCH) {
1436                         icall_name = "llvm_throw_corlib_exception_abs_trampoline";
1437                         throw_sig->params [1] = &mono_get_intptr_class ()->byval_arg;
1438                 } else {
1439                         icall_name = "llvm_throw_corlib_exception_trampoline";
1440                         throw_sig->params [1] = &mono_get_int32_class ()->byval_arg;
1441                 }
1442                 sig = sig_to_llvm_sig (ctx, throw_sig);
1443
1444                 if (ctx->cfg->compile_aot) {
1445                         callee = get_plt_entry (ctx, sig, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
1446                 } else {
1447                         callee = LLVMAddFunction (ctx->module, "llvm_throw_corlib_exception_trampoline", sig_to_llvm_sig (ctx, throw_sig));
1448
1449                         /*
1450                          * Differences between the LLVM/non-LLVM throw corlib exception trampoline:
1451                          * - On x86, LLVM generated code doesn't push the arguments
1452                          * - When using the LLVM mono branch, the trampoline takes the throw address as an
1453                          *   arguments, not a pc offset.
1454                          */
1455                         LLVMAddGlobalMapping (ee, callee, resolve_patch (ctx->cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
1456                 }
1457
1458                 mono_memory_barrier ();
1459                 ctx->lmodule->throw_corlib_exception = callee;
1460         }
1461
1462         if (IS_TARGET_X86)
1463                 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token - MONO_TOKEN_TYPE_DEF, FALSE);
1464         else
1465                 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token, FALSE);
1466
1467         if (IS_LLVM_MONO_BRANCH) {
1468                 /*
1469                  * The LLVM mono branch contains changes so a block address can be passed as an
1470                  * argument to a call.
1471                  */
1472                 args [1] = LLVMBuildPtrToInt (builder, LLVMBlockAddress (ctx->lmethod, ex_bb), IntPtrType (), "");
1473                 emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1474         } else {
1475                 /*
1476                  * FIXME: The offset is 0, this is only a problem if the code is inside a clause,
1477                  * otherwise only the line numbers in stack traces are incorrect.
1478                  */
1479                 if (bb->region != -1 && !IS_LLVM_MONO_BRANCH)
1480                         LLVM_FAILURE (ctx, "system-ex-in-region");
1481
1482                 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1483                 emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1484         }
1485
1486         LLVMBuildUnreachable (builder);
1487
1488         ctx->builder = create_builder (ctx);
1489         LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1490
1491         ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1492
1493         ctx->ex_index ++;
1494         return;
1495
1496  FAILURE:
1497         return;
1498 }
1499
1500 /*
1501  * emit_reg_to_vtype:
1502  *
1503  *   Emit code to store the vtype in the registers REGS to the address ADDRESS.
1504  */
1505 static void
1506 emit_reg_to_vtype (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs)
1507 {
1508         int j, size;
1509
1510         size = get_vtype_size (t);
1511
1512         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1513                 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1514         }
1515
1516         for (j = 0; j < 2; ++j) {
1517                 LLVMValueRef index [2], addr;
1518                 int part_size = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1519                 LLVMTypeRef part_type;
1520
1521                 if (ainfo->pair_storage [j] == LLVMArgNone)
1522                         continue;
1523
1524                 part_type = LLVMIntType (part_size * 8);
1525                 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1526                         index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1527                         addr = LLVMBuildGEP (builder, address, index, 1, "");
1528                 } else {
1529                         index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1530                         index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1531                         addr = LLVMBuildGEP (builder, address, index, 2, "");
1532                 }
1533                 switch (ainfo->pair_storage [j]) {
1534                 case LLVMArgInIReg:
1535                         LLVMBuildStore (builder, convert (ctx, regs [j], part_type), LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (part_type, 0), ""));
1536                         break;
1537                 case LLVMArgNone:
1538                         break;
1539                 default:
1540                         g_assert_not_reached ();
1541                 }
1542
1543                 size -= sizeof (gpointer);
1544         }
1545 }
1546
1547 /*
1548  * emit_vtype_to_reg:
1549  *
1550  *   Emit code to load a vtype at address ADDRESS into registers. Store the registers
1551  * into REGS, and the number of registers into NREGS.
1552  */
1553 static void
1554 emit_vtype_to_reg (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs, guint32 *nregs)
1555 {
1556         int pindex = 0;
1557         int j, size;
1558
1559         size = get_vtype_size (t);
1560
1561         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1562                 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1563         }
1564
1565         for (j = 0; j < 2; ++j) {
1566                 LLVMValueRef index [2], addr;
1567                 int partsize = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1568
1569                 if (ainfo->pair_storage [j] == LLVMArgNone)
1570                         continue;
1571
1572                 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1573                         index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1574                         addr = LLVMBuildGEP (builder, address, index, 1, "");
1575                 } else {
1576                         index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1577                         index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);                              
1578                         addr = LLVMBuildGEP (builder, address, index, 2, "");
1579                 }
1580                 switch (ainfo->pair_storage [j]) {
1581                 case LLVMArgInIReg:
1582                         regs [pindex ++] = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (LLVMIntType (partsize * 8), 0), ""), ""), IntPtrType ());
1583                         break;
1584                 case LLVMArgNone:
1585                         break;
1586                 default:
1587                         g_assert_not_reached ();
1588                 }
1589                 size -= sizeof (gpointer);
1590         }
1591
1592         *nregs = pindex;
1593 }
1594
1595 static LLVMValueRef
1596 build_alloca (EmitContext *ctx, MonoType *t)
1597 {
1598         MonoClass *k = mono_class_from_mono_type (t);
1599         int align;
1600
1601         if (MONO_CLASS_IS_SIMD (ctx->cfg, k))
1602                 align = 16;
1603         else
1604                 align = mono_class_min_align (k);
1605
1606         /* Sometimes align is not a power of 2 */
1607         while (mono_is_power_of_two (align) == -1)
1608                 align ++;
1609
1610         /*
1611          * Have to place all alloca's at the end of the entry bb, since otherwise they would
1612          * get executed every time control reaches them.
1613          */
1614         LLVMPositionBuilder (ctx->alloca_builder, get_bb (ctx, ctx->cfg->bb_entry), ctx->last_alloca);
1615
1616         ctx->last_alloca = mono_llvm_build_alloca (ctx->alloca_builder, type_to_llvm_type (ctx, t), NULL, align, "");
1617         return ctx->last_alloca;
1618 }
1619
1620 /*
1621  * Put the global into the 'llvm.used' array to prevent it from being optimized away.
1622  */
1623 static void
1624 mark_as_used (LLVMModuleRef module, LLVMValueRef global)
1625 {
1626         LLVMTypeRef used_type;
1627         LLVMValueRef used, used_elem;
1628                 
1629         used_type = LLVMArrayType (LLVMPointerType (LLVMInt8Type (), 0), 1);
1630         used = LLVMAddGlobal (module, used_type, "llvm.used");
1631         used_elem = LLVMConstBitCast (global, LLVMPointerType (LLVMInt8Type (), 0));
1632         LLVMSetInitializer (used, LLVMConstArray (LLVMPointerType (LLVMInt8Type (), 0), &used_elem, 1));
1633         LLVMSetLinkage (used, LLVMAppendingLinkage);
1634         LLVMSetSection (used, "llvm.metadata");
1635 }
1636
1637 /*
1638  * emit_entry_bb:
1639  *
1640  *   Emit code to load/convert arguments.
1641  */
1642 static void
1643 emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder)
1644 {
1645         int i, pindex;
1646         MonoCompile *cfg = ctx->cfg;
1647         MonoMethodSignature *sig = ctx->sig;
1648         LLVMCallInfo *linfo = ctx->linfo;
1649         MonoBasicBlock *bb;
1650
1651         ctx->alloca_builder = create_builder (ctx);
1652
1653         /*
1654          * Handle indirect/volatile variables by allocating memory for them
1655          * using 'alloca', and storing their address in a temporary.
1656          */
1657         for (i = 0; i < cfg->num_varinfo; ++i) {
1658                 MonoInst *var = cfg->varinfo [i];
1659                 LLVMTypeRef vtype;
1660
1661                 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || MONO_TYPE_ISSTRUCT (var->inst_vtype)) {
1662                         vtype = type_to_llvm_type (ctx, var->inst_vtype);
1663                         CHECK_FAILURE (ctx);
1664                         /* Could be already created by an OP_VPHI */
1665                         if (!ctx->addresses [var->dreg])
1666                                 ctx->addresses [var->dreg] = build_alloca (ctx, var->inst_vtype);
1667                         ctx->vreg_cli_types [var->dreg] = var->inst_vtype;
1668                 }
1669         }
1670
1671         for (i = 0; i < sig->param_count; ++i) {
1672                 LLVMArgInfo *ainfo = &linfo->args [i + sig->hasthis];
1673                 int reg = cfg->args [i + sig->hasthis]->dreg;
1674
1675                 if (ainfo->storage == LLVMArgVtypeInReg) {
1676                         LLVMValueRef regs [2];
1677
1678                         /* 
1679                          * Emit code to save the argument from the registers to 
1680                          * the real argument.
1681                          */
1682                         pindex = ctx->pindexes [i];
1683                         regs [0] = LLVMGetParam (ctx->lmethod, pindex);
1684                         if (ainfo->pair_storage [1] != LLVMArgNone)
1685                                 regs [1] = LLVMGetParam (ctx->lmethod, pindex + 1);
1686                         else
1687                                 regs [1] = NULL;
1688
1689                         ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1690
1691                         emit_reg_to_vtype (ctx, builder, sig->params [i], ctx->addresses [reg], ainfo, regs);
1692
1693                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1694                                 /* Treat these as normal values */
1695                                 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1696                         }
1697                 } else if (ainfo->storage == LLVMArgVtypeByVal) {
1698                         ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1699
1700                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1701                                 /* Treat these as normal values */
1702                                 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1703                         }
1704                 } else {
1705                         ctx->values [reg] = convert (ctx, ctx->values [reg], llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->params [i])));
1706                 }
1707         }
1708
1709         if (cfg->vret_addr)
1710                 emit_volatile_store (ctx, cfg->vret_addr->dreg);
1711         if (sig->hasthis)
1712                 emit_volatile_store (ctx, cfg->args [0]->dreg);
1713         for (i = 0; i < sig->param_count; ++i)
1714                 if (!MONO_TYPE_ISSTRUCT (sig->params [i]))
1715                         emit_volatile_store (ctx, cfg->args [i + sig->hasthis]->dreg);
1716
1717         if (sig->hasthis && !cfg->rgctx_var && cfg->generic_sharing_context) {
1718                 LLVMValueRef this_alloc;
1719
1720                 /*
1721                  * The exception handling code needs the location where the this argument was
1722                  * stored for gshared methods. We create a separate alloca to hold it, and mark it
1723                  * with the "mono.this" custom metadata to tell llvm that it needs to save its
1724                  * location into the LSDA.
1725                  */
1726                 this_alloc = mono_llvm_build_alloca (builder, IntPtrType (), LLVMConstInt (LLVMInt32Type (), 1, FALSE), 0, "");
1727                 /* This volatile store will keep the alloca alive */
1728                 mono_llvm_build_store (builder, ctx->values [cfg->args [0]->dreg], this_alloc, TRUE);
1729
1730                 set_metadata_flag (this_alloc, "mono.this");
1731         }
1732
1733         if (cfg->rgctx_var) {
1734                 LLVMValueRef rgctx_alloc, store;
1735
1736                 /*
1737                  * We handle the rgctx arg similarly to the this pointer.
1738                  */
1739                 g_assert (ctx->addresses [cfg->rgctx_var->dreg]);
1740                 rgctx_alloc = ctx->addresses [cfg->rgctx_var->dreg];
1741                 /* This volatile store will keep the alloca alive */
1742                 store = mono_llvm_build_store (builder, ctx->rgctx_arg, rgctx_alloc, TRUE);
1743
1744                 set_metadata_flag (rgctx_alloc, "mono.this");
1745         }
1746
1747         /*
1748          * For finally clauses, create an indicator variable telling OP_ENDFINALLY whenever
1749          * it needs to continue normally, or return back to the exception handling system.
1750          */
1751         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1752                 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER))
1753                         g_hash_table_insert (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)), bb);
1754                 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER) && bb->in_scount == 0) {
1755                         char name [128];
1756                         LLVMValueRef val;
1757
1758                         sprintf (name, "finally_ind_bb%d", bb->block_num);
1759                         val = LLVMBuildAlloca (builder, LLVMInt32Type (), name);
1760                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), val);
1761
1762                         ctx->bblocks [bb->block_num].finally_ind = val;
1763
1764                         /*
1765                          * Create a new bblock which CALL_HANDLER can branch to, because branching to the
1766                          * LLVM bblock containing the call to llvm.eh.selector causes problems for the
1767                          * LLVM optimizer passes.
1768                          */
1769                         sprintf (name, "BB_%d_CALL_HANDLER_TARGET", bb->block_num);
1770                         ctx->bblocks [bb->block_num].call_handler_target_bb = LLVMAppendBasicBlock (ctx->lmethod, name);
1771                 }
1772         }
1773
1774  FAILURE:
1775         ;
1776 }
1777
1778 /* Have to export this for AOT */
1779 void
1780 mono_personality (void);
1781         
1782 void
1783 mono_personality (void)
1784 {
1785         /* Not used */
1786         g_assert_not_reached ();
1787 }
1788
1789 static void
1790 process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, MonoInst *ins)
1791 {
1792         MonoCompile *cfg = ctx->cfg;
1793         LLVMModuleRef module = ctx->module;
1794         LLVMValueRef *values = ctx->values;
1795         LLVMValueRef *addresses = ctx->addresses;
1796         MonoCallInst *call = (MonoCallInst*)ins;
1797         MonoMethodSignature *sig = call->signature;
1798         LLVMValueRef callee, lcall;
1799         LLVMValueRef *args;
1800         LLVMCallInfo *cinfo;
1801         GSList *l;
1802         int i, len;
1803         gboolean vretaddr;
1804         LLVMTypeRef llvm_sig;
1805         gpointer target;
1806         gboolean virtual, calli;
1807         LLVMBuilderRef builder = *builder_ref;
1808         LLVMSigInfo sinfo;
1809
1810         if (call->signature->call_convention != MONO_CALL_DEFAULT)
1811                 LLVM_FAILURE (ctx, "non-default callconv");
1812
1813         if (call->rgctx_arg_reg && !IS_LLVM_MONO_BRANCH)
1814                 LLVM_FAILURE (ctx, "rgctx reg in call");
1815
1816         if (call->rgctx_reg && !IS_LLVM_MONO_BRANCH) {
1817                 /*
1818                  * It might be possible to support this by creating a static rgctx trampoline, but
1819                  * common_call_trampoline () would patch callsites to call the trampoline, which
1820                  * would be incorrect if the rgctx arg is computed dynamically.
1821                  */
1822                 LLVM_FAILURE (ctx, "rgctx reg");
1823         }
1824
1825         cinfo = call->cinfo;
1826         if (call->rgctx_arg_reg)
1827                 cinfo->rgctx_arg = TRUE;
1828         if (call->imt_arg_reg)
1829                 cinfo->imt_arg = TRUE;
1830
1831         vretaddr = cinfo && cinfo->ret.storage == LLVMArgVtypeRetAddr;
1832
1833         llvm_sig = sig_to_llvm_sig_full (ctx, sig, cinfo, &sinfo);
1834         CHECK_FAILURE (ctx);
1835
1836         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);
1837         calli = (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);
1838
1839         /* FIXME: Avoid creating duplicate methods */
1840
1841         if (ins->flags & MONO_INST_HAS_METHOD) {
1842                 if (virtual) {
1843                         callee = NULL;
1844                 } else {
1845                         if (cfg->compile_aot) {
1846                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_METHOD, call->method);
1847                                 if (!callee)
1848                                         LLVM_FAILURE (ctx, "can't encode patch");
1849                         } else {
1850                                 callee = LLVMAddFunction (module, "", llvm_sig);
1851  
1852                                 target =
1853                                         mono_create_jit_trampoline_in_domain (mono_domain_get (),
1854                                                                                                                   call->method);
1855                                 LLVMAddGlobalMapping (ee, callee, target);
1856                         }
1857                 }
1858         } else if (calli) {
1859         } else {
1860                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
1861
1862                 if (info) {
1863                         /*
1864                           MonoJumpInfo ji;
1865
1866                           memset (&ji, 0, sizeof (ji));
1867                           ji.type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
1868                           ji.data.target = info->name;
1869
1870                           target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
1871                         */
1872                         if (cfg->compile_aot) {
1873                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_INTERNAL_METHOD, (char*)info->name);
1874                                 if (!callee)
1875                                         LLVM_FAILURE (ctx, "can't encode patch");
1876                         } else {
1877                                 callee = LLVMAddFunction (module, "", llvm_sig);
1878                                 target = (gpointer)mono_icall_get_wrapper (info);
1879                                 LLVMAddGlobalMapping (ee, callee, target);
1880                         }
1881                 } else {
1882                         if (cfg->compile_aot) {
1883                                 callee = NULL;
1884                                 if (cfg->abs_patches) {
1885                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
1886                                         if (abs_ji) {
1887                                                 callee = get_plt_entry (ctx, llvm_sig, abs_ji->type, abs_ji->data.target);
1888                                                 if (!callee)
1889                                                         LLVM_FAILURE (ctx, "can't encode patch");
1890                                         }
1891                                 }
1892                                 if (!callee)
1893                                         LLVM_FAILURE (ctx, "aot");
1894                         } else {
1895                                 callee = LLVMAddFunction (module, "", llvm_sig);
1896                                 target = NULL;
1897                                 if (cfg->abs_patches) {
1898                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
1899                                         if (abs_ji) {
1900                                                 /*
1901                                                  * FIXME: Some trampolines might have
1902                                                  * their own calling convention on some platforms.
1903                                                  */
1904 #ifndef TARGET_AMD64
1905                                                 if (abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER || abs_ji->type == MONO_PATCH_INFO_MONITOR_EXIT || abs_ji->type == MONO_PATCH_INFO_GENERIC_CLASS_INIT)
1906                                                         LLVM_FAILURE (ctx, "trampoline with own cconv");
1907 #endif
1908                                                 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, abs_ji, FALSE);
1909                                                 LLVMAddGlobalMapping (ee, callee, target);
1910                                         }
1911                                 }
1912                                 if (!target)
1913                                         LLVMAddGlobalMapping (ee, callee, (gpointer)call->fptr);
1914                         }
1915                 }
1916         }
1917
1918         if (virtual) {
1919                 int size = sizeof (gpointer);
1920                 LLVMValueRef index;
1921
1922                 g_assert (ins->inst_offset % size == 0);
1923                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
1924
1925                 /*
1926                  * When using the llvm mono branch, we can support IMT directly, otherwise
1927                  * we need to call a trampoline.
1928                  */
1929                 if (call->method && call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE && !IS_LLVM_MONO_BRANCH) {
1930 #ifdef MONO_ARCH_HAVE_LLVM_IMT_TRAMPOLINE
1931                         if (cfg->compile_aot) {
1932                                 MonoJumpInfoImtTramp *imt_tramp = g_new0 (MonoJumpInfoImtTramp, 1);
1933                                 imt_tramp->method = call->method;
1934                                 imt_tramp->vt_offset = call->inst.inst_offset;
1935
1936                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE, imt_tramp);
1937                         } else {
1938                                 callee = LLVMAddFunction (module, "", llvm_sig);
1939                                 target = mono_create_llvm_imt_trampoline (cfg->domain, call->method, call->inst.inst_offset);
1940                                 LLVMAddGlobalMapping (ee, callee, target);
1941                         }
1942 #else
1943                         /* No support for passing the IMT argument */
1944                         LLVM_FAILURE (ctx, "imt");
1945 #endif
1946                 } else {
1947                         callee = convert (ctx, LLVMBuildLoad (builder, LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMPointerType (IntPtrType (), 0), 0)), &index, 1, ""), ""), LLVMPointerType (llvm_sig, 0));
1948                 }
1949         } else if (calli) {
1950                 callee = convert (ctx, values [ins->sreg1], LLVMPointerType (llvm_sig, 0));
1951         } else {
1952                 if (ins->flags & MONO_INST_HAS_METHOD) {
1953                 }
1954         }
1955
1956         /* 
1957          * Collect and convert arguments
1958          */
1959         len = sizeof (LLVMValueRef) * ((sig->param_count * 2) + sig->hasthis + vretaddr + call->rgctx_reg);
1960         args = alloca (len);
1961         memset (args, 0, len);
1962         l = call->out_ireg_args;
1963
1964         if (IS_LLVM_MONO_BRANCH) {
1965                 if (call->rgctx_arg_reg) {
1966                         g_assert (values [call->rgctx_arg_reg]);
1967                         args [sinfo.rgctx_arg_pindex] = values [call->rgctx_arg_reg];
1968                 }
1969                 if (call->imt_arg_reg) {
1970                         g_assert (values [call->imt_arg_reg]);
1971                         args [sinfo.imt_arg_pindex] = values [call->imt_arg_reg];
1972                 }
1973         }
1974
1975         if (vretaddr) {
1976                 if (!addresses [call->inst.dreg])
1977                         addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
1978                 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
1979         }
1980
1981         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1982                 guint32 regpair;
1983                 int reg, pindex;
1984                 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i] : NULL;
1985
1986                 if (sig->hasthis) {
1987                         if (i == 0)
1988                                 pindex = sinfo.this_arg_pindex;
1989                         else
1990                                 pindex = sinfo.pindexes [i - 1];
1991                 } else {
1992                         pindex = sinfo.pindexes [i];
1993                 }
1994
1995                 regpair = (guint32)(gssize)(l->data);
1996                 reg = regpair & 0xffffff;
1997                 args [pindex] = values [reg];
1998                 if (ainfo->storage == LLVMArgVtypeInReg) {
1999                         int j;
2000                         LLVMValueRef regs [2];
2001                         guint32 nregs;
2002
2003                         g_assert (ainfo);
2004
2005                         g_assert (addresses [reg]);
2006
2007                         emit_vtype_to_reg (ctx, builder, sig->params [i - sig->hasthis], addresses [reg], ainfo, regs, &nregs);
2008                         for (j = 0; j < nregs; ++j)
2009                                 args [pindex ++] = regs [j];
2010
2011                         // FIXME: alignment
2012                         // FIXME: Get rid of the VMOVE
2013                 } else if (ainfo->storage == LLVMArgVtypeByVal) {
2014                         g_assert (addresses [reg]);
2015                         args [pindex] = addresses [reg];
2016                 } else {
2017                         g_assert (args [pindex]);
2018                         if (i == 0 && sig->hasthis)
2019                                 args [pindex] = convert (ctx, args [pindex], IntPtrType ());
2020                         else
2021                                 args [pindex] = convert (ctx, args [pindex], type_to_llvm_arg_type (ctx, sig->params [i - sig->hasthis]));
2022                 }
2023
2024                 l = l->next;
2025         }
2026
2027         // FIXME: Align call sites
2028
2029         /*
2030          * Emit the call
2031          */
2032
2033         lcall = emit_call (ctx, bb, &builder, callee, args, LLVMCountParamTypes (llvm_sig));
2034
2035 #ifdef LLVM_MONO_BRANCH
2036         /*
2037          * Modify cconv and parameter attributes to pass rgctx/imt correctly.
2038          */
2039 #if defined(MONO_ARCH_IMT_REG) && defined(MONO_ARCH_RGCTX_REG)
2040         g_assert (MONO_ARCH_IMT_REG == MONO_ARCH_RGCTX_REG);
2041 #endif
2042         /* The two can't be used together, so use only one LLVM calling conv to pass them */
2043         g_assert (!(call->rgctx_arg_reg && call->imt_arg_reg));
2044         if (!sig->pinvoke)
2045                 LLVMSetInstructionCallConv (lcall, LLVMMono1CallConv);
2046
2047         if (call->rgctx_arg_reg)
2048                 LLVMAddInstrAttribute (lcall, 1 + sinfo.rgctx_arg_pindex, LLVMInRegAttribute);
2049         if (call->imt_arg_reg)
2050                 LLVMAddInstrAttribute (lcall, 1 + sinfo.imt_arg_pindex, LLVMInRegAttribute);
2051 #endif
2052
2053         /* Add byval attributes if needed */
2054         for (i = 0; i < sig->param_count; ++i) {
2055                 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i + sig->hasthis] : NULL;
2056
2057                 if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
2058                         LLVMAddInstrAttribute (lcall, 1 + sinfo.pindexes [i], LLVMByValAttribute);
2059                 }
2060         }
2061
2062         /*
2063          * Convert the result
2064          */
2065         if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
2066                 LLVMValueRef regs [2];
2067
2068                 if (!addresses [ins->dreg])
2069                         addresses [ins->dreg] = build_alloca (ctx, sig->ret);
2070
2071                 regs [0] = LLVMBuildExtractValue (builder, lcall, 0, "");
2072                 if (cinfo->ret.pair_storage [1] != LLVMArgNone)
2073                         regs [1] = LLVMBuildExtractValue (builder, lcall, 1, "");
2074                                         
2075                 emit_reg_to_vtype (ctx, builder, sig->ret, addresses [ins->dreg], &cinfo->ret, regs);
2076         } else if (sig->ret->type != MONO_TYPE_VOID && !vretaddr) {
2077                 /* If the method returns an unsigned value, need to zext it */
2078
2079                 values [ins->dreg] = convert_full (ctx, lcall, llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->ret)), type_is_unsigned (ctx, sig->ret));
2080         }
2081
2082         *builder_ref = ctx->builder;
2083
2084         g_free (sinfo.pindexes);
2085         
2086         return;
2087  FAILURE:
2088         return;
2089 }
2090
2091 static void
2092 process_bb (EmitContext *ctx, MonoBasicBlock *bb)
2093 {
2094         MonoCompile *cfg = ctx->cfg;
2095         MonoMethodSignature *sig = ctx->sig;
2096         LLVMValueRef method = ctx->lmethod;
2097         LLVMValueRef *values = ctx->values;
2098         LLVMValueRef *addresses = ctx->addresses;
2099         int i;
2100         LLVMCallInfo *linfo = ctx->linfo;
2101         LLVMModuleRef module = ctx->module;
2102         BBInfo *bblocks = ctx->bblocks;
2103         MonoInst *ins;
2104         LLVMBasicBlockRef cbb;
2105         LLVMBuilderRef builder;
2106         gboolean has_terminator;
2107         LLVMValueRef v;
2108         LLVMValueRef lhs, rhs;
2109
2110         cbb = get_bb (ctx, bb);
2111         builder = create_builder (ctx);
2112         ctx->builder = builder;
2113         LLVMPositionBuilderAtEnd (builder, cbb);
2114
2115         if (bb == cfg->bb_entry)
2116                 emit_entry_bb (ctx, builder);
2117         CHECK_FAILURE (ctx);
2118
2119         if (bb->flags & BB_EXCEPTION_HANDLER) {
2120                 LLVMTypeRef i8ptr;
2121                 LLVMValueRef eh_selector, eh_exception, personality, args [4];
2122                 LLVMBasicBlockRef target_bb;
2123                 MonoInst *exvar;
2124                 static gint32 mapping_inited;
2125                 static int ti_generator;
2126                 char ti_name [128];
2127                 MonoClass **ti;
2128                 LLVMValueRef type_info;
2129                 int clause_index;
2130
2131                 if (!bblocks [bb->block_num].invoke_target) {
2132                         /*
2133                          * LLVM asserts if llvm.eh.selector is called from a bblock which
2134                          * doesn't have an invoke pointing at it.
2135                          */
2136                         LLVM_FAILURE (ctx, "handler without invokes");
2137                 }
2138
2139                 eh_selector = LLVMGetNamedFunction (module, eh_selector_name);
2140
2141                 if (cfg->compile_aot) {
2142                         /* Use a dummy personality function */
2143                         personality = LLVMGetNamedFunction (module, "mono_aot_personality");
2144                         g_assert (personality);
2145                 } else {
2146                         personality = LLVMGetNamedFunction (module, "mono_personality");
2147                         if (InterlockedCompareExchange (&mapping_inited, 1, 0) == 0)
2148                                 LLVMAddGlobalMapping (ee, personality, mono_personality);
2149                 }
2150
2151                 i8ptr = LLVMPointerType (LLVMInt8Type (), 0);
2152
2153                 clause_index = (mono_get_block_region_notry (cfg, bb->region) >> 8) - 1;
2154
2155                 /*
2156                  * Create the type info
2157                  */
2158                 sprintf (ti_name, "type_info_%d", ti_generator);
2159                 ti_generator ++;
2160
2161                 if (cfg->compile_aot) {
2162                         /* decode_eh_frame () in aot-runtime.c will decode this */
2163                         type_info = LLVMAddGlobal (module, LLVMInt32Type (), ti_name);
2164                         LLVMSetInitializer (type_info, LLVMConstInt (LLVMInt32Type (), clause_index, FALSE));
2165
2166                         LLVMSetLinkage (type_info, LLVMPrivateLinkage);
2167                         LLVMSetVisibility (type_info, LLVMHiddenVisibility);
2168
2169                         /* 
2170                          * Enabling this causes llc to crash:
2171                          * http://llvm.org/bugs/show_bug.cgi?id=6102
2172                          */
2173                         //LLVM_FAILURE (ctx, "aot+clauses");
2174                 } else {
2175                         /*
2176                          * After the cfg mempool is freed, the type info will point to stale memory,
2177                          * but this is not a problem, since we decode it once in exception_cb during
2178                          * compilation.
2179                          */
2180                         ti = mono_mempool_alloc (cfg->mempool, sizeof (gint32));
2181                         *(gint32*)ti = clause_index;
2182
2183                         type_info = LLVMAddGlobal (module, i8ptr, ti_name);
2184
2185                         LLVMAddGlobalMapping (ee, type_info, ti);
2186                 }
2187
2188                 args [0] = LLVMConstNull (i8ptr);
2189                 args [1] = LLVMConstBitCast (personality, i8ptr);
2190                 args [2] = type_info;
2191                 LLVMBuildCall (builder, eh_selector, args, 3, "");
2192
2193                 /* Store the exception into the exvar */
2194                 if (bb->in_scount == 1) {
2195                         g_assert (bb->in_scount == 1);
2196                         exvar = bb->in_stack [0];
2197
2198                         eh_exception = LLVMGetNamedFunction (module, "llvm.eh.exception");
2199
2200                         // FIXME: This is shared with filter clauses ?
2201                         g_assert (!values [exvar->dreg]);
2202                         values [exvar->dreg] = LLVMBuildCall (builder, eh_exception, NULL, 0, "");
2203                         emit_volatile_store (ctx, exvar->dreg);
2204                 }
2205
2206                 /* Start a new bblock which CALL_HANDLER can branch to */
2207                 target_bb = bblocks [bb->block_num].call_handler_target_bb;
2208                 if (target_bb) {
2209                         LLVMBuildBr (builder, target_bb);
2210
2211                         ctx->builder = builder = create_builder (ctx);
2212                         LLVMPositionBuilderAtEnd (ctx->builder, target_bb);
2213
2214                         ctx->bblocks [bb->block_num].end_bblock = target_bb;
2215                 }
2216         }
2217
2218         has_terminator = FALSE;
2219         for (ins = bb->code; ins; ins = ins->next) {
2220                 const char *spec = LLVM_INS_INFO (ins->opcode);
2221                 char *dname = NULL;
2222                 char dname_buf [128];
2223
2224                 if (has_terminator)
2225                         /* There could be instructions after a terminator, skip them */
2226                         break;
2227
2228                 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins)) {
2229                         sprintf (dname_buf, "t%d", ins->dreg);
2230                         dname = dname_buf;
2231                 }
2232
2233                 if (spec [MONO_INST_SRC1] != ' ' && spec [MONO_INST_SRC1] != 'v') {
2234                         MonoInst *var = get_vreg_to_inst (cfg, ins->sreg1);
2235
2236                         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2237                                 lhs = emit_volatile_load (ctx, ins->sreg1);
2238                         } else {
2239                                 /* It is ok for SETRET to have an uninitialized argument */
2240                                 if (!values [ins->sreg1] && ins->opcode != OP_SETRET)
2241                                         LLVM_FAILURE (ctx, "sreg1");
2242                                 lhs = values [ins->sreg1];
2243                         }
2244                 } else {
2245                         lhs = NULL;
2246                 }
2247
2248                 if (spec [MONO_INST_SRC2] != ' ' && spec [MONO_INST_SRC2] != ' ') {
2249                         MonoInst *var = get_vreg_to_inst (cfg, ins->sreg2);
2250                         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2251                                 rhs = emit_volatile_load (ctx, ins->sreg2);
2252                         } else {
2253                                 if (!values [ins->sreg2])
2254                                         LLVM_FAILURE (ctx, "sreg2");
2255                                 rhs = values [ins->sreg2];
2256                         }
2257                 } else {
2258                         rhs = NULL;
2259                 }
2260
2261                 //mono_print_ins (ins);
2262                 switch (ins->opcode) {
2263                 case OP_NOP:
2264                 case OP_NOT_NULL:
2265                 case OP_LIVERANGE_START:
2266                 case OP_LIVERANGE_END:
2267                         break;
2268                 case OP_ICONST:
2269                         values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE);
2270                         break;
2271                 case OP_I8CONST:
2272 #if SIZEOF_VOID_P == 4
2273                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2274 #else
2275                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), (gint64)ins->inst_c0, FALSE);
2276 #endif
2277                         break;
2278                 case OP_R8CONST:
2279                         values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), *(double*)ins->inst_p0);
2280                         break;
2281                 case OP_R4CONST:
2282                         values [ins->dreg] = LLVMConstFPExt (LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0), LLVMDoubleType ());
2283                         break;
2284                 case OP_BR:
2285                         LLVMBuildBr (builder, get_bb (ctx, ins->inst_target_bb));
2286                         has_terminator = TRUE;
2287                         break;
2288                 case OP_SWITCH: {
2289                         int i;
2290                         LLVMValueRef v;
2291                         char bb_name [128];
2292                         LLVMBasicBlockRef new_bb;
2293                         LLVMBuilderRef new_builder;
2294
2295                         // The default branch is already handled
2296                         // FIXME: Handle it here
2297
2298                         /* Start new bblock */
2299                         sprintf (bb_name, "SWITCH_DEFAULT_BB%d", ctx->default_index ++);
2300                         new_bb = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
2301
2302                         lhs = convert (ctx, lhs, LLVMInt32Type ());
2303                         v = LLVMBuildSwitch (builder, lhs, new_bb, GPOINTER_TO_UINT (ins->klass));
2304                         for (i = 0; i < GPOINTER_TO_UINT (ins->klass); ++i) {
2305                                 MonoBasicBlock *target_bb = ins->inst_many_bb [i];
2306
2307                                 LLVMAddCase (v, LLVMConstInt (LLVMInt32Type (), i, FALSE), get_bb (ctx, target_bb));
2308                         }
2309
2310                         new_builder = create_builder (ctx);
2311                         LLVMPositionBuilderAtEnd (new_builder, new_bb);
2312                         LLVMBuildUnreachable (new_builder);
2313
2314                         has_terminator = TRUE;
2315                         g_assert (!ins->next);
2316                                 
2317                         break;
2318                 }
2319
2320                 case OP_SETRET:
2321                         if (linfo->ret.storage == LLVMArgVtypeInReg) {
2322                                 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2323                                 LLVMValueRef part1, retval;
2324                                 int size;
2325
2326                                 size = get_vtype_size (sig->ret);
2327
2328                                 g_assert (addresses [ins->sreg1]);
2329
2330                                 g_assert (linfo->ret.pair_storage [0] == LLVMArgInIReg);
2331                                 g_assert (linfo->ret.pair_storage [1] == LLVMArgNone);
2332                                         
2333                                 part1 = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMIntType (size * 8), 0), ""), ""), IntPtrType ());
2334
2335                                 retval = LLVMBuildInsertValue (builder, LLVMGetUndef (ret_type), part1, 0, "");
2336
2337                                 LLVMBuildRet (builder, retval);
2338                                 break;
2339                         }
2340
2341                         if (linfo->ret.storage == LLVMArgVtypeRetAddr) {
2342                                 LLVMBuildRetVoid (builder);
2343                                 break;
2344                         }
2345
2346                         if (!lhs || ctx->is_dead [ins->sreg1]) {
2347                                 /* 
2348                                  * The method did not set its return value, probably because it
2349                                  * ends with a throw.
2350                                  */
2351                                 if (cfg->vret_addr)
2352                                         LLVMBuildRetVoid (builder);
2353                                 else
2354                                         LLVMBuildRet (builder, LLVMConstNull (type_to_llvm_type (ctx, sig->ret)));
2355                         } else {
2356                                 LLVMBuildRet (builder, convert (ctx, lhs, type_to_llvm_type (ctx, sig->ret)));
2357                         }
2358                         has_terminator = TRUE;
2359                         break;
2360                 case OP_ICOMPARE:
2361                 case OP_FCOMPARE:
2362                 case OP_LCOMPARE:
2363                 case OP_COMPARE:
2364                 case OP_ICOMPARE_IMM:
2365                 case OP_LCOMPARE_IMM:
2366                 case OP_COMPARE_IMM: {
2367                         CompRelation rel;
2368                         LLVMValueRef cmp;
2369
2370                         if (ins->next->opcode == OP_NOP)
2371                                 break;
2372
2373                         if (ins->next->opcode == OP_BR)
2374                                 /* The comparison result is not needed */
2375                                 continue;
2376
2377                         rel = mono_opcode_to_cond (ins->next->opcode);
2378
2379                         if (ins->opcode == OP_ICOMPARE_IMM) {
2380                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2381                                 rhs = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2382                         }
2383                         if (ins->opcode == OP_LCOMPARE_IMM) {
2384                                 lhs = convert (ctx, lhs, LLVMInt64Type ());
2385                                 rhs = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2386                         }
2387                         if (ins->opcode == OP_LCOMPARE) {
2388                                 lhs = convert (ctx, lhs, LLVMInt64Type ());
2389                                 rhs = convert (ctx, rhs, LLVMInt64Type ());
2390                         }
2391                         if (ins->opcode == OP_ICOMPARE) {
2392                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2393                                 rhs = convert (ctx, rhs, LLVMInt32Type ());
2394                         }
2395
2396                         if (lhs && rhs) {
2397                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2398                                         rhs = convert (ctx, rhs, LLVMTypeOf (lhs));
2399                                 else if (LLVMGetTypeKind (LLVMTypeOf (rhs)) == LLVMPointerTypeKind)
2400                                         lhs = convert (ctx, lhs, LLVMTypeOf (rhs));
2401                         }
2402
2403                         /* We use COMPARE+SETcc/Bcc, llvm uses SETcc+br cond */
2404                         if (ins->opcode == OP_FCOMPARE)
2405                                 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2406                         else if (ins->opcode == OP_COMPARE_IMM)
2407                                 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), "");
2408                         else if (ins->opcode == OP_LCOMPARE_IMM) {
2409                                 if (SIZEOF_REGISTER == 4 && COMPILE_LLVM (cfg))  {
2410                                         /* The immediate is encoded in two fields */
2411                                         guint64 l = ((guint64)(guint32)ins->inst_offset << 32) | ((guint32)ins->inst_imm);
2412                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), l, FALSE), "");
2413                                 } else {
2414                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), ins->inst_imm, FALSE), "");
2415                                 }
2416                         }
2417                         else if (ins->opcode == OP_COMPARE)
2418                                 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), convert (ctx, rhs, IntPtrType ()), "");
2419                         else
2420                                 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2421
2422                         if (MONO_IS_COND_BRANCH_OP (ins->next)) {
2423                                 LLVMBuildCondBr (builder, cmp, get_bb (ctx, ins->next->inst_true_bb), get_bb (ctx, ins->next->inst_false_bb));
2424                                 has_terminator = TRUE;
2425                         } else if (MONO_IS_SETCC (ins->next)) {
2426                                 sprintf (dname_buf, "t%d", ins->next->dreg);
2427                                 dname = dname_buf;
2428                                 values [ins->next->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2429
2430                                 /* Add stores for volatile variables */
2431                                 emit_volatile_store (ctx, ins->next->dreg);
2432                         } else if (MONO_IS_COND_EXC (ins->next)) {
2433                                 emit_cond_system_exception (ctx, bb, ins->next->inst_p1, cmp);
2434                                 CHECK_FAILURE (ctx);
2435                                 builder = ctx->builder;
2436                         } else {
2437                                 LLVM_FAILURE (ctx, "next");
2438                         }
2439
2440                         ins = ins->next;
2441                         break;
2442                 }
2443                 case OP_FCEQ:
2444                 case OP_FCLT:
2445                 case OP_FCLT_UN:
2446                 case OP_FCGT:
2447                 case OP_FCGT_UN: {
2448                         CompRelation rel;
2449                         LLVMValueRef cmp;
2450
2451                         rel = mono_opcode_to_cond (ins->opcode);
2452
2453                         cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2454                         values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2455                         break;
2456                 }
2457                 case OP_PHI:
2458                 case OP_FPHI:
2459                 case OP_VPHI:
2460                 case OP_XPHI: {
2461                         int i;
2462                         gboolean empty = TRUE;
2463
2464                         /* Check that all input bblocks really branch to us */
2465                         for (i = 0; i < bb->in_count; ++i) {
2466                                 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_NOT_REACHED)
2467                                         ins->inst_phi_args [i + 1] = -1;
2468                                 else
2469                                         empty = FALSE;
2470                         }
2471
2472                         if (empty) {
2473                                 /* LLVM doesn't like phi instructions with zero operands */
2474                                 ctx->is_dead [ins->dreg] = TRUE;
2475                                 break;
2476                         }                                       
2477
2478                         /* Created earlier, insert it now */
2479                         LLVMInsertIntoBuilder (builder, values [ins->dreg]);
2480
2481                         for (i = 0; i < ins->inst_phi_args [0]; i++) {
2482                                 int sreg1 = ins->inst_phi_args [i + 1];
2483                                 int count, j;
2484
2485                                 /* 
2486                                  * Count the number of times the incoming bblock branches to us,
2487                                  * since llvm requires a separate entry for each.
2488                                  */
2489                                 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_SWITCH) {
2490                                         MonoInst *switch_ins = bb->in_bb [i]->last_ins;
2491
2492                                         count = 0;
2493                                         for (j = 0; j < GPOINTER_TO_UINT (switch_ins->klass); ++j) {
2494                                                 if (switch_ins->inst_many_bb [j] == bb)
2495                                                         count ++;
2496                                         }
2497                                 } else {
2498                                         count = 1;
2499                                 }
2500
2501                                 /* Remember for later */
2502                                 for (j = 0; j < count; ++j) {
2503                                         PhiNode *node = mono_mempool_alloc0 (ctx->mempool, sizeof (PhiNode));
2504                                         node->bb = bb;
2505                                         node->phi = ins;
2506                                         node->in_bb = bb->in_bb [i];
2507                                         node->sreg = sreg1;
2508                                         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);
2509                                 }
2510                         }
2511                         break;
2512                 }
2513                 case OP_MOVE:
2514                 case OP_LMOVE:
2515                 case OP_XMOVE:
2516                 case OP_SETFRET:
2517                         g_assert (lhs);
2518                         values [ins->dreg] = lhs;
2519                         break;
2520                 case OP_FMOVE: {
2521                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
2522                                 
2523                         g_assert (lhs);
2524                         values [ins->dreg] = lhs;
2525
2526                         if (var && var->klass->byval_arg.type == MONO_TYPE_R4) {
2527                                 /* 
2528                                  * This is added by the spilling pass in case of the JIT,
2529                                  * but we have to do it ourselves.
2530                                  */
2531                                 values [ins->dreg] = convert (ctx, values [ins->dreg], LLVMFloatType ());
2532                         }
2533                         break;
2534                 }
2535                 case OP_IADD:
2536                 case OP_ISUB:
2537                 case OP_IAND:
2538                 case OP_IMUL:
2539                 case OP_IDIV:
2540                 case OP_IDIV_UN:
2541                 case OP_IREM:
2542                 case OP_IREM_UN:
2543                 case OP_IOR:
2544                 case OP_IXOR:
2545                 case OP_ISHL:
2546                 case OP_ISHR:
2547                 case OP_ISHR_UN:
2548                 case OP_FADD:
2549                 case OP_FSUB:
2550                 case OP_FMUL:
2551                 case OP_FDIV:
2552                 case OP_LADD:
2553                 case OP_LSUB:
2554                 case OP_LMUL:
2555                 case OP_LDIV:
2556                 case OP_LDIV_UN:
2557                 case OP_LREM:
2558                 case OP_LREM_UN:
2559                 case OP_LAND:
2560                 case OP_LOR:
2561                 case OP_LXOR:
2562                 case OP_LSHL:
2563                 case OP_LSHR:
2564                 case OP_LSHR_UN:
2565                         lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2566                         rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2567
2568                         switch (ins->opcode) {
2569                         case OP_IADD:
2570                         case OP_LADD:
2571                                 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, dname);
2572                                 break;
2573                         case OP_ISUB:
2574                         case OP_LSUB:
2575                                 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, dname);
2576                                 break;
2577                         case OP_IMUL:
2578                         case OP_LMUL:
2579                                 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, dname);
2580                                 break;
2581                         case OP_IREM:
2582                         case OP_LREM:
2583                                 values [ins->dreg] = LLVMBuildSRem (builder, lhs, rhs, dname);
2584                                 break;
2585                         case OP_IREM_UN:
2586                         case OP_LREM_UN:
2587                                 values [ins->dreg] = LLVMBuildURem (builder, lhs, rhs, dname);
2588                                 break;
2589                         case OP_IDIV:
2590                         case OP_LDIV:
2591                                 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, rhs, dname);
2592                                 break;
2593                         case OP_IDIV_UN:
2594                         case OP_LDIV_UN:
2595                                 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, rhs, dname);
2596                                 break;
2597                         case OP_FDIV:
2598                                 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
2599                                 break;
2600                         case OP_IAND:
2601                         case OP_LAND:
2602                                 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, dname);
2603                                 break;
2604                         case OP_IOR:
2605                         case OP_LOR:
2606                                 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, dname);
2607                                 break;
2608                         case OP_IXOR:
2609                         case OP_LXOR:
2610                                 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, dname);
2611                                 break;
2612                         case OP_ISHL:
2613                         case OP_LSHL:
2614                                 values [ins->dreg] = LLVMBuildShl (builder, lhs, rhs, dname);
2615                                 break;
2616                         case OP_ISHR:
2617                         case OP_LSHR:
2618                                 values [ins->dreg] = LLVMBuildAShr (builder, lhs, rhs, dname);
2619                                 break;
2620                         case OP_ISHR_UN:
2621                         case OP_LSHR_UN:
2622                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, rhs, dname);
2623                                 break;
2624
2625                         case OP_FADD:
2626                                 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
2627                                 break;
2628                         case OP_FSUB:
2629                                 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
2630                                 break;
2631                         case OP_FMUL:
2632                                 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
2633                                 break;
2634
2635                         default:
2636                                 g_assert_not_reached ();
2637                         }
2638                         break;
2639                 case OP_IADD_IMM:
2640                 case OP_ISUB_IMM:
2641                 case OP_IMUL_IMM:
2642                 case OP_IREM_IMM:
2643                 case OP_IREM_UN_IMM:
2644                 case OP_IDIV_IMM:
2645                 case OP_IDIV_UN_IMM:
2646                 case OP_IAND_IMM:
2647                 case OP_IOR_IMM:
2648                 case OP_IXOR_IMM:
2649                 case OP_ISHL_IMM:
2650                 case OP_ISHR_IMM:
2651                 case OP_ISHR_UN_IMM:
2652                 case OP_LADD_IMM:
2653                 case OP_LSUB_IMM:
2654                 case OP_LREM_IMM:
2655                 case OP_LAND_IMM:
2656                 case OP_LOR_IMM:
2657                 case OP_LXOR_IMM:
2658                 case OP_LSHL_IMM:
2659                 case OP_LSHR_IMM:
2660                 case OP_LSHR_UN_IMM:
2661                 case OP_ADD_IMM:
2662                 case OP_AND_IMM:
2663                 case OP_MUL_IMM:
2664                 case OP_SHL_IMM:
2665                 case OP_SHR_IMM: {
2666                         LLVMValueRef imm;
2667
2668                         if (spec [MONO_INST_SRC1] == 'l') {
2669                                 imm = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2670                         } else {
2671                                 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2672                         }
2673
2674 #if SIZEOF_VOID_P == 4
2675                         if (ins->opcode == OP_LSHL_IMM || ins->opcode == OP_LSHR_IMM || ins->opcode == OP_LSHR_UN_IMM)
2676                                 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2677 #endif
2678
2679                         if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2680                                 lhs = convert (ctx, lhs, IntPtrType ());
2681                         imm = convert (ctx, imm, LLVMTypeOf (lhs));
2682                         switch (ins->opcode) {
2683                         case OP_IADD_IMM:
2684                         case OP_LADD_IMM:
2685                         case OP_ADD_IMM:
2686                                 values [ins->dreg] = LLVMBuildAdd (builder, lhs, imm, dname);
2687                                 break;
2688                         case OP_ISUB_IMM:
2689                         case OP_LSUB_IMM:
2690                                 values [ins->dreg] = LLVMBuildSub (builder, lhs, imm, dname);
2691                                 break;
2692                         case OP_IMUL_IMM:
2693                         case OP_MUL_IMM:
2694                                 values [ins->dreg] = LLVMBuildMul (builder, lhs, imm, dname);
2695                                 break;
2696                         case OP_IDIV_IMM:
2697                         case OP_LDIV_IMM:
2698                                 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, imm, dname);
2699                                 break;
2700                         case OP_IDIV_UN_IMM:
2701                         case OP_LDIV_UN_IMM:
2702                                 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, imm, dname);
2703                                 break;
2704                         case OP_IREM_IMM:
2705                         case OP_LREM_IMM:
2706                                 values [ins->dreg] = LLVMBuildSRem (builder, lhs, imm, dname);
2707                                 break;
2708                         case OP_IREM_UN_IMM:
2709                                 values [ins->dreg] = LLVMBuildURem (builder, lhs, imm, dname);
2710                                 break;
2711                         case OP_IAND_IMM:
2712                         case OP_LAND_IMM:
2713                         case OP_AND_IMM:
2714                                 values [ins->dreg] = LLVMBuildAnd (builder, lhs, imm, dname);
2715                                 break;
2716                         case OP_IOR_IMM:
2717                         case OP_LOR_IMM:
2718                                 values [ins->dreg] = LLVMBuildOr (builder, lhs, imm, dname);
2719                                 break;
2720                         case OP_IXOR_IMM:
2721                         case OP_LXOR_IMM:
2722                                 values [ins->dreg] = LLVMBuildXor (builder, lhs, imm, dname);
2723                                 break;
2724                         case OP_ISHL_IMM:
2725                         case OP_LSHL_IMM:
2726                         case OP_SHL_IMM:
2727                                 values [ins->dreg] = LLVMBuildShl (builder, lhs, imm, dname);
2728                                 break;
2729                         case OP_ISHR_IMM:
2730                         case OP_LSHR_IMM:
2731                         case OP_SHR_IMM:
2732                                 values [ins->dreg] = LLVMBuildAShr (builder, lhs, imm, dname);
2733                                 break;
2734                         case OP_ISHR_UN_IMM:
2735                                 /* This is used to implement conv.u4, so the lhs could be an i8 */
2736                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2737                                 imm = convert (ctx, imm, LLVMInt32Type ());
2738                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
2739                                 break;
2740                         case OP_LSHR_UN_IMM:
2741                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
2742                                 break;
2743                         default:
2744                                 g_assert_not_reached ();
2745                         }
2746                         break;
2747                 }
2748                 case OP_INEG:
2749                         values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
2750                         break;
2751                 case OP_LNEG:
2752                         values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt64Type (), 0, FALSE), lhs, dname);
2753                         break;
2754                 case OP_FNEG:
2755                         lhs = convert (ctx, lhs, LLVMDoubleType ());
2756                         values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMDoubleType (), 0.0), lhs, dname);
2757                         break;
2758                 case OP_INOT: {
2759                         guint32 v = 0xffffffff;
2760                         values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt32Type (), v, FALSE), lhs, dname);
2761                         break;
2762                 }
2763                 case OP_LNOT: {
2764                         guint64 v = 0xffffffffffffffffLL;
2765                         values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt64Type (), v, FALSE), lhs, dname);
2766                         break;
2767                 }
2768 #if defined(TARGET_X86) || defined(TARGET_AMD64)
2769                 case OP_X86_LEA: {
2770                         LLVMValueRef v1, v2;
2771
2772                         v1 = LLVMBuildMul (builder, convert (ctx, rhs, IntPtrType ()), LLVMConstInt (IntPtrType (), (1 << ins->backend.shift_amount), FALSE), "");
2773                         v2 = LLVMBuildAdd (builder, convert (ctx, lhs, IntPtrType ()), v1, "");
2774                         values [ins->dreg] = LLVMBuildAdd (builder, v2, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), dname);
2775                         break;
2776                 }
2777 #endif
2778
2779                 case OP_ICONV_TO_I1:
2780                 case OP_ICONV_TO_I2:
2781                 case OP_ICONV_TO_I4:
2782                 case OP_ICONV_TO_U1:
2783                 case OP_ICONV_TO_U2:
2784                 case OP_ICONV_TO_U4:
2785                 case OP_LCONV_TO_I1:
2786                 case OP_LCONV_TO_I2:
2787                 case OP_LCONV_TO_U1:
2788                 case OP_LCONV_TO_U2:
2789                 case OP_LCONV_TO_U4: {
2790                         gboolean sign;
2791
2792                         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);
2793
2794                         /* Have to do two casts since our vregs have type int */
2795                         v = LLVMBuildTrunc (builder, lhs, op_to_llvm_type (ins->opcode), "");
2796                         if (sign)
2797                                 values [ins->dreg] = LLVMBuildSExt (builder, v, LLVMInt32Type (), dname);
2798                         else
2799                                 values [ins->dreg] = LLVMBuildZExt (builder, v, LLVMInt32Type (), dname);
2800                         break;
2801                 }
2802                 case OP_ICONV_TO_I8:
2803                         values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
2804                         break;
2805                 case OP_ICONV_TO_U8:
2806                         values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
2807                         break;
2808                 case OP_FCONV_TO_I4:
2809                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt32Type (), dname);
2810                         break;
2811                 case OP_FCONV_TO_I1:
2812                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
2813                         break;
2814                 case OP_FCONV_TO_U1:
2815                         values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
2816                         break;
2817                 case OP_FCONV_TO_I2:
2818                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
2819                         break;
2820                 case OP_FCONV_TO_U2:
2821                         values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
2822                         break;
2823                 case OP_FCONV_TO_I8:
2824                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt64Type (), dname);
2825                         break;
2826                 case OP_FCONV_TO_I:
2827                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, IntPtrType (), dname);
2828                         break;
2829                 case OP_ICONV_TO_R8:
2830                 case OP_LCONV_TO_R8:
2831                         values [ins->dreg] = LLVMBuildSIToFP (builder, lhs, LLVMDoubleType (), dname);
2832                         break;
2833                 case OP_LCONV_TO_R_UN:
2834                         values [ins->dreg] = LLVMBuildUIToFP (builder, lhs, LLVMDoubleType (), dname);
2835                         break;
2836 #if SIZEOF_VOID_P == 4
2837                 case OP_LCONV_TO_U:
2838 #endif
2839                 case OP_LCONV_TO_I4:
2840                         values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
2841                         break;
2842                 case OP_ICONV_TO_R4:
2843                 case OP_LCONV_TO_R4:
2844                         v = LLVMBuildSIToFP (builder, lhs, LLVMFloatType (), "");
2845                         values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
2846                         break;
2847                 case OP_FCONV_TO_R4:
2848                         v = LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), "");
2849                         values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
2850                         break;
2851                 case OP_SEXT_I4:
2852                         values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
2853                         break;
2854                 case OP_ZEXT_I4:
2855                         values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
2856                         break;
2857                 case OP_TRUNC_I4:
2858                         values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
2859                         break;
2860                 case OP_LOCALLOC_IMM: {
2861                         LLVMValueRef v;
2862
2863                         guint32 size = ins->inst_imm;
2864                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
2865
2866                         v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
2867
2868                         if (ins->flags & MONO_INST_INIT) {
2869                                 LLVMValueRef args [5];
2870
2871                                 args [0] = v;
2872                                 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
2873                                 args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
2874                                 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
2875                                 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
2876                                 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
2877                         }
2878
2879                         values [ins->dreg] = v;
2880                         break;
2881                 }
2882                 case OP_LOCALLOC: {
2883                         LLVMValueRef v, size;
2884                                 
2885                         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), "");
2886
2887                         v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
2888
2889                         if (ins->flags & MONO_INST_INIT) {
2890                                 LLVMValueRef args [5];
2891
2892                                 args [0] = v;
2893                                 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
2894                                 args [2] = size;
2895                                 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
2896                                 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
2897                                 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
2898                         }
2899                         values [ins->dreg] = v;
2900                         break;
2901                 }
2902
2903                 case OP_LOADI1_MEMBASE:
2904                 case OP_LOADU1_MEMBASE:
2905                 case OP_LOADI2_MEMBASE:
2906                 case OP_LOADU2_MEMBASE:
2907                 case OP_LOADI4_MEMBASE:
2908                 case OP_LOADU4_MEMBASE:
2909                 case OP_LOADI8_MEMBASE:
2910                 case OP_LOADR4_MEMBASE:
2911                 case OP_LOADR8_MEMBASE:
2912                 case OP_LOAD_MEMBASE:
2913                 case OP_LOADI8_MEM:
2914                 case OP_LOADU1_MEM:
2915                 case OP_LOADU2_MEM:
2916                 case OP_LOADI4_MEM:
2917                 case OP_LOADU4_MEM:
2918                 case OP_LOAD_MEM: {
2919                         int size = 8;
2920                         LLVMValueRef index, addr;
2921                         LLVMTypeRef t;
2922                         gboolean sext = FALSE, zext = FALSE;
2923                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
2924
2925                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
2926
2927                         if (sext || zext)
2928                                 dname = (char*)"";
2929
2930                         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)) {
2931                                 addr = LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE);
2932                         } else if (ins->inst_offset == 0) {
2933                                 addr = values [ins->inst_basereg];
2934                         } else if (ins->inst_offset % size != 0) {
2935                                 /* Unaligned load */
2936                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
2937                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
2938                         } else {
2939                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
2940                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (t, 0)), &index, 1, "");
2941                         }
2942
2943                         addr = convert (ctx, addr, LLVMPointerType (t, 0));
2944
2945                         values [ins->dreg] = emit_load (ctx, bb, &builder, size, addr, dname, is_volatile);
2946
2947                         if (!is_volatile && (ins->flags & MONO_INST_CONSTANT_LOAD)) {
2948                                 /*
2949                                  * These will signal LLVM that these loads do not alias any stores, and
2950                                  * they can't fail, allowing them to be hoisted out of loops.
2951                                  */
2952                                 set_metadata_flag (values [ins->dreg], "mono.noalias");
2953                                 set_metadata_flag (values [ins->dreg], "mono.nofail.load");
2954                         }
2955
2956                         if (sext)
2957                                 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
2958                         else if (zext)
2959                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
2960                         else if (ins->opcode == OP_LOADR4_MEMBASE)
2961                                 values [ins->dreg] = LLVMBuildFPExt (builder, values [ins->dreg], LLVMDoubleType (), dname);
2962                         break;
2963                 }
2964                                 
2965                 case OP_STOREI1_MEMBASE_REG:
2966                 case OP_STOREI2_MEMBASE_REG:
2967                 case OP_STOREI4_MEMBASE_REG:
2968                 case OP_STOREI8_MEMBASE_REG:
2969                 case OP_STORER4_MEMBASE_REG:
2970                 case OP_STORER8_MEMBASE_REG:
2971                 case OP_STORE_MEMBASE_REG: {
2972                         int size = 8;
2973                         LLVMValueRef index, addr;
2974                         LLVMTypeRef t;
2975                         gboolean sext = FALSE, zext = FALSE;
2976                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
2977
2978                         if (!values [ins->inst_destbasereg])
2979                                 LLVM_FAILURE (ctx, "inst_destbasereg");
2980
2981                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
2982
2983                         if (ins->inst_offset % size != 0) {
2984                                 /* Unaligned store */
2985                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
2986                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
2987                         } else {
2988                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
2989                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
2990                         }
2991                         emit_store (ctx, bb, &builder, size, convert (ctx, values [ins->sreg1], t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
2992                         break;
2993                 }
2994
2995                 case OP_STOREI1_MEMBASE_IMM:
2996                 case OP_STOREI2_MEMBASE_IMM:
2997                 case OP_STOREI4_MEMBASE_IMM:
2998                 case OP_STOREI8_MEMBASE_IMM:
2999                 case OP_STORE_MEMBASE_IMM: {
3000                         int size = 8;
3001                         LLVMValueRef index, addr;
3002                         LLVMTypeRef t;
3003                         gboolean sext = FALSE, zext = FALSE;
3004                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3005
3006                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3007
3008                         if (ins->inst_offset % size != 0) {
3009                                 /* Unaligned store */
3010                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3011                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3012                         } else {
3013                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
3014                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3015                         }
3016                         emit_store (ctx, bb, &builder, size, convert (ctx, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), t), addr, is_volatile);
3017                         break;
3018                 }
3019
3020                 case OP_CHECK_THIS:
3021                         emit_load (ctx, bb, &builder, sizeof (gpointer), convert (ctx, values [ins->sreg1], LLVMPointerType (IntPtrType (), 0)), "", TRUE);
3022                         break;
3023                 case OP_OUTARG_VTRETADDR:
3024                         break;
3025                 case OP_VOIDCALL:
3026                 case OP_CALL:
3027                 case OP_LCALL:
3028                 case OP_FCALL:
3029                 case OP_VCALL:
3030                 case OP_VOIDCALL_MEMBASE:
3031                 case OP_CALL_MEMBASE:
3032                 case OP_LCALL_MEMBASE:
3033                 case OP_FCALL_MEMBASE:
3034                 case OP_VCALL_MEMBASE:
3035                 case OP_VOIDCALL_REG:
3036                 case OP_CALL_REG:
3037                 case OP_LCALL_REG:
3038                 case OP_FCALL_REG:
3039                 case OP_VCALL_REG: {
3040                         process_call (ctx, bb, &builder, ins);
3041                         CHECK_FAILURE (ctx);
3042                         break;
3043                 }
3044                 case OP_AOTCONST: {
3045                         guint32 got_offset;
3046                         LLVMValueRef indexes [2];
3047                         MonoJumpInfo *ji;
3048                         LLVMValueRef got_entry_addr;
3049
3050                         /* 
3051                          * FIXME: Can't allocate from the cfg mempool since that is freed if
3052                          * the LLVM compile fails.
3053                          */
3054                         ji = g_new0 (MonoJumpInfo, 1);
3055                         ji->type = (MonoJumpInfoType)ins->inst_i1;
3056                         ji->data.target = ins->inst_p0;
3057
3058                         ji = mono_aot_patch_info_dup (ji);
3059
3060                         ji->next = cfg->patch_info;
3061                         cfg->patch_info = ji;
3062                                    
3063                         //mono_add_patch_info (cfg, 0, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3064                         got_offset = mono_aot_get_got_offset (cfg->patch_info);
3065  
3066                         indexes [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3067                         indexes [1] = LLVMConstInt (LLVMInt32Type (), (gssize)got_offset, FALSE);
3068                         got_entry_addr = LLVMBuildGEP (builder, ctx->lmodule->got_var, indexes, 2, "");
3069
3070                         // FIXME: This doesn't work right now, because it must be
3071                         // paired with an invariant.end, and even then, its only in effect
3072                         // inside its basic block
3073 #if 0
3074                         {
3075                                 LLVMValueRef args [3];
3076                                 LLVMValueRef ptr, val;
3077
3078                                 ptr = LLVMBuildBitCast (builder, got_entry_addr, LLVMPointerType (LLVMInt8Type (), 0), "ptr");
3079
3080                                 args [0] = LLVMConstInt (LLVMInt64Type (), sizeof (gpointer), FALSE);
3081                                 args [1] = ptr;
3082                                 val = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.invariant.start"), args, 2, "");
3083                         }
3084 #endif
3085
3086                         values [ins->dreg] = LLVMBuildLoad (builder, got_entry_addr, dname);
3087                         break;
3088                 }
3089                 case OP_NOT_REACHED:
3090                         LLVMBuildUnreachable (builder);
3091                         has_terminator = TRUE;
3092                         g_assert (bb->block_num < cfg->max_block_num);
3093                         ctx->unreachable [bb->block_num] = TRUE;
3094                         /* Might have instructions after this */
3095                         while (ins->next) {
3096                                 MonoInst *next = ins->next;
3097                                 /* 
3098                                  * FIXME: If later code uses the regs defined by these instructions,
3099                                  * compilation will fail.
3100                                  */
3101                                 MONO_DELETE_INS (bb, next);
3102                         }                               
3103                         break;
3104                 case OP_LDADDR: {
3105                         MonoInst *var = ins->inst_p0;
3106
3107                         values [ins->dreg] = addresses [var->dreg];
3108                         break;
3109                 }
3110                 case OP_SIN: {
3111                         LLVMValueRef args [1];
3112
3113                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3114                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sin.f64"), args, 1, dname);
3115                         break;
3116                 }
3117                 case OP_COS: {
3118                         LLVMValueRef args [1];
3119
3120                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3121                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.cos.f64"), args, 1, dname);
3122                         break;
3123                 }
3124                 case OP_SQRT: {
3125                         LLVMValueRef args [1];
3126
3127                         /*
3128                          * LLVM optimizes sqrt(nan) into undefined in
3129                          * lib/Analysis/ConstantFolding.cpp
3130                          * Also, sqrt(NegativeInfinity) is optimized into 0.
3131                          */
3132                         LLVM_FAILURE (ctx, "sqrt");
3133                         args [0] = lhs;
3134                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sqrt.f64"), args, 1, dname);
3135                         break;
3136                 }
3137                 case OP_ABS: {
3138                         LLVMValueRef args [1];
3139
3140                         args [0] = lhs;
3141                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "fabs"), args, 1, dname);
3142                         break;
3143                 }
3144
3145                 case OP_IMIN:
3146                 case OP_LMIN:
3147                 case OP_IMAX:
3148                 case OP_LMAX:
3149                 case OP_IMIN_UN:
3150                 case OP_LMIN_UN:
3151                 case OP_IMAX_UN:
3152                 case OP_LMAX_UN: {
3153                         LLVMValueRef v;
3154
3155                         lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3156                         rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3157
3158                         switch (ins->opcode) {
3159                         case OP_IMIN:
3160                         case OP_LMIN:
3161                                 v = LLVMBuildICmp (builder, LLVMIntSLE, lhs, rhs, "");
3162                                 break;
3163                         case OP_IMAX:
3164                         case OP_LMAX:
3165                                 v = LLVMBuildICmp (builder, LLVMIntSGE, lhs, rhs, "");
3166                                 break;
3167                         case OP_IMIN_UN:
3168                         case OP_LMIN_UN:
3169                                 v = LLVMBuildICmp (builder, LLVMIntULE, lhs, rhs, "");
3170                                 break;
3171                         case OP_IMAX_UN:
3172                         case OP_LMAX_UN:
3173                                 v = LLVMBuildICmp (builder, LLVMIntUGE, lhs, rhs, "");
3174                                 break;
3175                         default:
3176                                 g_assert_not_reached ();
3177                                 break;
3178                         }
3179                         values [ins->dreg] = LLVMBuildSelect (builder, v, lhs, rhs, dname);
3180                         break;
3181                 }
3182                 case OP_ATOMIC_EXCHANGE_I4: {
3183                         LLVMValueRef args [2];
3184
3185                         g_assert (ins->inst_offset == 0);
3186
3187                         args [0] = convert (ctx, lhs, LLVMPointerType (LLVMInt32Type (), 0));
3188                         args [1] = rhs;
3189                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.atomic.swap.i32.p0i32"), args, 2, dname);
3190                         break;
3191                 }
3192                 case OP_ATOMIC_EXCHANGE_I8: {
3193                         LLVMValueRef args [2];
3194
3195                         g_assert (ins->inst_offset == 0);
3196
3197                         args [0] = convert (ctx, lhs, LLVMPointerType (LLVMInt64Type (), 0));
3198                         args [1] = convert (ctx, rhs, LLVMInt64Type ());
3199                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.atomic.swap.i64.p0i64"), args, 2, dname);
3200                         break;
3201                 }
3202                 case OP_ATOMIC_ADD_NEW_I4: {
3203                         LLVMValueRef args [2];
3204
3205                         g_assert (ins->inst_offset == 0);
3206
3207                         args [0] = convert (ctx, lhs, LLVMPointerType (LLVMInt32Type (), 0));
3208                         args [1] = rhs;
3209                         values [ins->dreg] = LLVMBuildAdd (builder, LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.atomic.load.add.i32.p0i32"), args, 2, ""), args [1], dname);
3210                         break;
3211                 }
3212                 case OP_ATOMIC_ADD_NEW_I8: {
3213                         LLVMValueRef args [2];
3214
3215                         g_assert (ins->inst_offset == 0);
3216
3217                         args [0] = convert (ctx, lhs, LLVMPointerType (LLVMInt64Type (), 0));
3218                         args [1] = convert (ctx, rhs, LLVMInt64Type ());
3219                         values [ins->dreg] = LLVMBuildAdd (builder, LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.atomic.load.add.i64.p0i64"), args, 2, ""), args [1], dname);
3220                         break;
3221                 }
3222                 case OP_ATOMIC_CAS_I4:
3223                 case OP_ATOMIC_CAS_I8: {
3224                         LLVMValueRef args [3];
3225                         LLVMTypeRef t;
3226                         const char *intrins;
3227                                 
3228                         if (ins->opcode == OP_ATOMIC_CAS_I4) {
3229                                 t = LLVMInt32Type ();
3230                                 intrins = "llvm.atomic.cmp.swap.i32.p0i32";
3231                         } else {
3232                                 t = LLVMInt64Type ();
3233                                 intrins = "llvm.atomic.cmp.swap.i64.p0i64";
3234                         }
3235
3236                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3237                         /* comparand */
3238                         args [1] = convert (ctx, values [ins->sreg3], t);
3239                         /* new value */
3240                         args [2] = convert (ctx, values [ins->sreg2], t);
3241                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, intrins), args, 3, dname);
3242                         break;
3243                 }
3244                 case OP_MEMORY_BARRIER: {
3245                         LLVMValueRef args [5];
3246
3247 #ifdef TARGET_ARM
3248                         /* Not yet supported by llc on arm */
3249                         LLVM_FAILURE (ctx, "memory-barrier+arm");
3250 #endif
3251
3252                         for (i = 0; i < 5; ++i)
3253                                 args [i] = LLVMConstInt (LLVMInt1Type (), TRUE, TRUE);
3254
3255                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.memory.barrier"), args, 5, "");
3256                         break;
3257                 }
3258                 case OP_RELAXED_NOP: {
3259 #if defined(TARGET_AMD64) || defined(TARGET_X86)
3260                         /* No way to get LLVM to emit this */
3261                         LLVM_FAILURE (ctx, "relaxed_nop");
3262 #else
3263                         break;
3264 #endif
3265                 }
3266                 case OP_TLS_GET: {
3267 #if defined(TARGET_AMD64) || defined(TARGET_X86)
3268 #ifdef TARGET_AMD64
3269                         // 257 == FS segment register
3270                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 257);
3271 #else
3272                         // 256 == GS segment register
3273                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3274 #endif
3275
3276                         // FIXME: XEN
3277                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), ins->inst_offset, TRUE), ptrtype, ""), "");
3278 #else
3279                         LLVM_FAILURE (ctx, "opcode tls-get");
3280 #endif
3281
3282                         break;
3283                 }
3284
3285                         /*
3286                          * Overflow opcodes.
3287                          */
3288                 case OP_IADD_OVF:
3289                 case OP_IADD_OVF_UN:
3290                 case OP_ISUB_OVF:
3291                 case OP_ISUB_OVF_UN:
3292                 case OP_IMUL_OVF:
3293                 case OP_IMUL_OVF_UN:
3294 #if SIZEOF_VOID_P == 8
3295                 case OP_LADD_OVF:
3296                 case OP_LADD_OVF_UN:
3297                 case OP_LSUB_OVF:
3298                 case OP_LSUB_OVF_UN:
3299                 case OP_LMUL_OVF:
3300                 case OP_LMUL_OVF_UN:
3301 #endif
3302                         {
3303                                 LLVMValueRef args [2], val, ovf, func;
3304
3305                                 args [0] = convert (ctx, lhs, op_to_llvm_type (ins->opcode));
3306                                 args [1] = convert (ctx, rhs, op_to_llvm_type (ins->opcode));
3307                                 func = LLVMGetNamedFunction (module, ovf_op_to_intrins (ins->opcode));
3308                                 g_assert (func);
3309                                 val = LLVMBuildCall (builder, func, args, 2, "");
3310                                 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, dname);
3311                                 ovf = LLVMBuildExtractValue (builder, val, 1, "");
3312                                 emit_cond_system_exception (ctx, bb, "OverflowException", ovf);
3313                                 CHECK_FAILURE (ctx);
3314                                 builder = ctx->builder;
3315                                 break;
3316                         }
3317
3318                         /* 
3319                          * Valuetypes.
3320                          *   We currently model them using arrays. Promotion to local vregs is 
3321                          * disabled for them in mono_handle_global_vregs () in the LLVM case, 
3322                          * so we always have an entry in cfg->varinfo for them.
3323                          * FIXME: Is this needed ?
3324                          */
3325                 case OP_VZERO: {
3326                         MonoClass *klass = ins->klass;
3327                         LLVMValueRef args [5];
3328
3329                         if (!klass) {
3330                                 // FIXME:
3331                                 LLVM_FAILURE (ctx, "!klass");
3332                                 break;
3333                         }
3334
3335                         if (!addresses [ins->dreg])
3336                                 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3337                         args [0] = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3338                         args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3339                         args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3340                         // FIXME: Alignment
3341                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3342                         args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3343                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3344                         break;
3345                 }
3346
3347                 case OP_STOREV_MEMBASE:
3348                 case OP_LOADV_MEMBASE:
3349                 case OP_VMOVE: {
3350                         MonoClass *klass = ins->klass;
3351                         LLVMValueRef src, dst, args [5];
3352                         gboolean done = FALSE;
3353
3354                         if (!klass) {
3355                                 // FIXME:
3356                                 LLVM_FAILURE (ctx, "!klass");
3357                                 break;
3358                         }
3359
3360                         switch (ins->opcode) {
3361                         case OP_STOREV_MEMBASE:
3362                                 if (cfg->gen_write_barriers && klass->has_references && ins->inst_destbasereg != cfg->frame_reg) {
3363                                         /* FIXME: Emit write barriers like in mini_emit_stobj () */
3364                                         LLVM_FAILURE (ctx, "storev_membase + write barriers");
3365                                         break;
3366                                 }
3367                                 if (!addresses [ins->sreg1]) {
3368                                         /* SIMD */
3369                                         g_assert (values [ins->sreg1]);
3370                                         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));
3371                                         LLVMBuildStore (builder, values [ins->sreg1], dst);
3372                                         done = TRUE;
3373                                 } else {
3374                                         src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3375                                         dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3376                                 }
3377                                 break;
3378                         case OP_LOADV_MEMBASE:
3379                                 if (!addresses [ins->dreg])
3380                                         addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3381                                 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3382                                 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3383                                 break;
3384                         case OP_VMOVE:
3385                                 if (!addresses [ins->sreg1])
3386                                         addresses [ins->sreg1] = build_alloca (ctx, &klass->byval_arg);
3387                                 if (!addresses [ins->dreg])
3388                                         addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3389                                 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3390                                 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3391                                 break;
3392                         default:
3393                                 g_assert_not_reached ();
3394                         }
3395                         CHECK_FAILURE (ctx);
3396
3397                         if (done)
3398                                 break;
3399
3400                         args [0] = dst;
3401                         args [1] = src;
3402                         args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3403                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3404                         // FIXME: Alignment
3405                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3406                         args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3407                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
3408                         break;
3409                 }
3410                 case OP_LLVM_OUTARG_VT:
3411                         if (!addresses [ins->sreg1]) {
3412                                 addresses [ins->sreg1] = build_alloca (ctx, &ins->klass->byval_arg);
3413                                 g_assert (values [ins->sreg1]);
3414                                 LLVMBuildStore (builder, values [ins->sreg1], addresses [ins->sreg1]);
3415                         }
3416                         addresses [ins->dreg] = addresses [ins->sreg1];
3417                         break;
3418
3419                         /* 
3420                          * SIMD
3421                          */
3422 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3423                 case OP_XZERO: {
3424                         values [ins->dreg] = LLVMConstNull (type_to_llvm_type (ctx, &ins->klass->byval_arg));
3425                         break;
3426                 }
3427                 case OP_LOADX_MEMBASE: {
3428                         LLVMTypeRef t = type_to_llvm_type (ctx, &ins->klass->byval_arg);
3429                         LLVMValueRef src;
3430
3431                         src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3432                         values [ins->dreg] = mono_llvm_build_aligned_load (builder, src, "", FALSE, 1);
3433                         break;
3434                 }
3435                 case OP_STOREX_MEMBASE: {
3436                         LLVMTypeRef t = LLVMTypeOf (values [ins->sreg1]);
3437                         LLVMValueRef dest;
3438
3439                         dest = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3440                         mono_llvm_build_aligned_store (builder, values [ins->sreg1], dest, FALSE, 1);
3441                         break;
3442                 }
3443                 case OP_PADDB:
3444                 case OP_PADDW:
3445                 case OP_PADDD:
3446                 case OP_PADDQ:
3447                         values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, "");
3448                         break;
3449                 case OP_ADDPD:
3450                 case OP_ADDPS:
3451                         values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, "");
3452                         break;
3453                 case OP_PSUBB:
3454                 case OP_PSUBW:
3455                 case OP_PSUBD:
3456                 case OP_PSUBQ:
3457                         values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, "");
3458                         break;
3459                 case OP_SUBPD:
3460                 case OP_SUBPS:
3461                         values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, "");
3462                         break;
3463                 case OP_MULPD:
3464                 case OP_MULPS:
3465                         values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, "");
3466                         break;
3467                 case OP_DIVPD:
3468                 case OP_DIVPS:
3469                         values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, "");
3470                         break;
3471                 case OP_PAND:
3472                         values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, "");
3473                         break;
3474                 case OP_POR:
3475                         values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, "");
3476                         break;
3477                 case OP_PXOR:
3478                         values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, "");
3479                         break;
3480                 case OP_ANDPS:
3481                 case OP_ANDNPS:
3482                 case OP_ORPS:
3483                 case OP_XORPS:
3484                 case OP_ANDPD:
3485                 case OP_ANDNPD:
3486                 case OP_ORPD:
3487                 case OP_XORPD: {
3488                         LLVMTypeRef t, rt;
3489                         LLVMValueRef v;
3490
3491                         switch (ins->opcode) {
3492                         case OP_ANDPS:
3493                         case OP_ANDNPS:
3494                         case OP_ORPS:
3495                         case OP_XORPS:
3496                                 t = LLVMVectorType (LLVMInt32Type (), 4);
3497                                 rt = LLVMVectorType (LLVMFloatType (), 4);
3498                                 break;
3499                         case OP_ANDPD:
3500                         case OP_ANDNPD:
3501                         case OP_ORPD:
3502                         case OP_XORPD:
3503                                 t = LLVMVectorType (LLVMInt64Type (), 2);
3504                                 rt = LLVMVectorType (LLVMDoubleType (), 2);
3505                                 break;
3506                         default:
3507                                 t = LLVMInt32Type ();
3508                                 rt = LLVMInt32Type ();
3509                                 g_assert_not_reached ();
3510                         }
3511
3512                         lhs = LLVMBuildBitCast (builder, lhs, t, "");
3513                         rhs = LLVMBuildBitCast (builder, rhs, t, "");
3514                         switch (ins->opcode) {
3515                         case OP_ANDPS:
3516                         case OP_ANDPD:
3517                                 v = LLVMBuildAnd (builder, lhs, rhs, "");
3518                                 break;
3519                         case OP_ORPS:
3520                         case OP_ORPD:
3521                                 v = LLVMBuildOr (builder, lhs, rhs, "");
3522                                 break;
3523                         case OP_XORPS:
3524                         case OP_XORPD:
3525                                 v = LLVMBuildXor (builder, lhs, rhs, "");
3526                                 break;
3527                         case OP_ANDNPS:
3528                         case OP_ANDNPD:
3529                                 v = LLVMBuildAnd (builder, rhs, LLVMBuildNot (builder, lhs, ""), "");
3530                                 break;
3531                         }
3532                         values [ins->dreg] = LLVMBuildBitCast (builder, v, rt, "");
3533                         break;
3534                 }
3535                 case OP_MINPD:
3536                 case OP_MINPS:
3537                 case OP_MAXPD:
3538                 case OP_MAXPS:
3539                 case OP_ADDSUBPD:
3540                 case OP_PMIND_UN:
3541                 case OP_PMINW_UN:
3542                 case OP_PMINB_UN:
3543                 case OP_PMINW:
3544                 case OP_PMAXD_UN:
3545                 case OP_PMAXW_UN:
3546                 case OP_PMAXB_UN:
3547                 case OP_HADDPD:
3548                 case OP_HADDPS:
3549                 case OP_HSUBPD:
3550                 case OP_HSUBPS:
3551                 case OP_PADDB_SAT:
3552                 case OP_PADDW_SAT:
3553                 case OP_PSUBB_SAT:
3554                 case OP_PSUBW_SAT:
3555                 case OP_PADDB_SAT_UN:
3556                 case OP_PADDW_SAT_UN:
3557                 case OP_PSUBB_SAT_UN:
3558                 case OP_PSUBW_SAT_UN:
3559                 case OP_PCMPEQB:
3560                 case OP_PCMPEQW:
3561                 case OP_PCMPEQD:
3562                 case OP_PCMPEQQ:
3563                 case OP_PCMPGTB: {
3564                         LLVMValueRef args [2];
3565
3566                         args [0] = lhs;
3567                         args [1] = rhs;
3568
3569                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3570                         break;
3571                 }
3572                 case OP_EXTRACT_R8:
3573                 case OP_EXTRACT_I8:
3574                 case OP_EXTRACT_I4:
3575                 case OP_EXTRACT_I2:
3576                 case OP_EXTRACT_U2:
3577                 case OP_EXTRACTX_U2:
3578                 case OP_EXTRACT_I1:
3579                 case OP_EXTRACT_U1: {
3580                         LLVMTypeRef t;
3581                         gboolean zext = FALSE;
3582
3583                         t = simd_op_to_llvm_type (ins->opcode);
3584
3585                         switch (ins->opcode) {
3586                         case OP_EXTRACT_R8:
3587                         case OP_EXTRACT_I8:
3588                         case OP_EXTRACT_I4:
3589                         case OP_EXTRACT_I2:
3590                         case OP_EXTRACT_I1:
3591                                 break;
3592                         case OP_EXTRACT_U2:
3593                         case OP_EXTRACTX_U2:
3594                         case OP_EXTRACT_U1:
3595                                 zext = TRUE;
3596                                 break;
3597                         default:
3598                                 t = LLVMInt32Type ();
3599                                 g_assert_not_reached ();
3600                         }
3601
3602                         lhs = LLVMBuildBitCast (builder, lhs, t, "");
3603                         values [ins->dreg] = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), "");
3604                         if (zext)
3605                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), "");
3606                         break;
3607                 }
3608
3609                 case OP_EXPAND_I1:
3610                 case OP_EXPAND_I2:
3611                 case OP_EXPAND_I4:
3612                 case OP_EXPAND_I8:
3613                 case OP_EXPAND_R4:
3614                 case OP_EXPAND_R8: {
3615                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
3616                         LLVMValueRef mask [16], v;
3617
3618                         for (i = 0; i < 16; ++i)
3619                                 mask [i] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3620
3621                         v = convert (ctx, values [ins->sreg1], LLVMGetElementType (t));
3622
3623                         values [ins->dreg] = LLVMBuildInsertElement (builder, LLVMConstNull (t), v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
3624                         values [ins->dreg] = LLVMBuildShuffleVector (builder, values [ins->dreg], LLVMGetUndef (t), LLVMConstVector (mask, LLVMGetVectorSize (t)), "");
3625                         break;
3626                 }
3627
3628                 case OP_CVTDQ2PD:
3629                 case OP_CVTDQ2PS:
3630                 case OP_CVTPD2DQ:
3631                 case OP_CVTPS2DQ:
3632                 case OP_CVTPD2PS:
3633                 case OP_CVTPS2PD:
3634                 case OP_CVTTPD2DQ:
3635                 case OP_CVTTPS2DQ:
3636                 case OP_EXTRACT_MASK: {
3637                         LLVMValueRef v;
3638
3639                         v = convert (ctx, values [ins->sreg1], simd_op_to_llvm_type (ins->opcode));
3640
3641                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), &v, 1, dname);
3642                         break;
3643                 }
3644
3645                 case OP_ICONV_TO_R8_RAW:
3646                         /* Same as OP_ICONV_TO_R8 */
3647                         values [ins->dreg] = convert (ctx, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType ());
3648                         break;
3649
3650                 case OP_COMPPS:
3651                 case OP_COMPPD: {
3652                         LLVMValueRef args [3];
3653
3654                         args [0] = lhs;
3655                         args [1] = rhs;
3656                         args [2] = LLVMConstInt (LLVMInt8Type (), ins->inst_c0, FALSE);
3657
3658                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 3, dname);
3659                         break;
3660                 }
3661
3662                 case OP_PSHRW:
3663                 case OP_PSHRD:
3664                 case OP_PSHRQ:
3665                 case OP_PSHLW:
3666                 case OP_PSHLD:
3667                 case OP_PSHLQ: {
3668                         LLVMValueRef args [3];
3669
3670                         args [0] = lhs;
3671                         args [1] = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3672
3673                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3674                         break;
3675                 }
3676
3677 #endif /* SIMD */
3678
3679                 case OP_DUMMY_USE:
3680                         break;
3681
3682                         /*
3683                          * EXCEPTION HANDLING
3684                          */
3685                 case OP_IMPLICIT_EXCEPTION:
3686                         /* This marks a place where an implicit exception can happen */
3687                         if (bb->region != -1)
3688                                 LLVM_FAILURE (ctx, "implicit-exception");
3689                         break;
3690                 case OP_THROW:
3691                 case OP_RETHROW: {
3692                         MonoMethodSignature *throw_sig;
3693                         LLVMValueRef callee, arg;
3694                         gboolean rethrow = (ins->opcode == OP_RETHROW);
3695                         const char *icall_name;
3696                                 
3697                         callee = rethrow ? ctx->lmodule->rethrow : ctx->lmodule->throw;
3698                         icall_name = rethrow ? "mono_arch_rethrow_exception" : "mono_arch_throw_exception";
3699
3700                         if (!callee) {
3701                                 throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 1);
3702                                 throw_sig->ret = &mono_get_void_class ()->byval_arg;
3703                                 throw_sig->params [0] = &mono_get_object_class ()->byval_arg;
3704                                 if (cfg->compile_aot) {
3705                                         callee = get_plt_entry (ctx, sig_to_llvm_sig (ctx, throw_sig), MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
3706                                 } else {
3707                                         callee = LLVMAddFunction (module, icall_name, sig_to_llvm_sig (ctx, throw_sig));
3708
3709 #ifdef TARGET_X86
3710                                         /* 
3711                                          * LLVM doesn't push the exception argument, so we need a different
3712                                          * trampoline.
3713                                          */
3714                                         LLVMAddGlobalMapping (ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, rethrow ? "llvm_rethrow_exception_trampoline" : "llvm_throw_exception_trampoline"));
3715 #else
3716                                         LLVMAddGlobalMapping (ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
3717 #endif
3718                                 }
3719
3720                                 mono_memory_barrier ();
3721                                 if (rethrow)
3722                                         ctx->lmodule->rethrow = callee;
3723                                 else
3724                                         ctx->lmodule->throw = callee;
3725                         }
3726                         arg = convert (ctx, values [ins->sreg1], type_to_llvm_type (ctx, &mono_get_object_class ()->byval_arg));
3727                         emit_call (ctx, bb, &builder, callee, &arg, 1);
3728                         break;
3729                 }
3730                 case OP_CALL_HANDLER: {
3731                         /* 
3732                          * We don't 'call' handlers, but instead simply branch to them.
3733                          * The code generated by ENDFINALLY will branch back to us.
3734                          */
3735                         LLVMBasicBlockRef noex_bb;
3736                         GSList *bb_list;
3737                         BBInfo *info = &bblocks [ins->inst_target_bb->block_num];
3738
3739                         bb_list = info->call_handler_return_bbs;
3740
3741                         /* 
3742                          * Set the indicator variable for the finally clause.
3743                          */
3744                         lhs = info->finally_ind;
3745                         g_assert (lhs);
3746                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), g_slist_length (bb_list) + 1, FALSE), lhs);
3747                                 
3748                         /* Branch to the finally clause */
3749                         LLVMBuildBr (builder, info->call_handler_target_bb);
3750
3751                         noex_bb = gen_bb (ctx, "CALL_HANDLER_CONT_BB");
3752                         info->call_handler_return_bbs = g_slist_append_mempool (cfg->mempool, info->call_handler_return_bbs, noex_bb);
3753
3754                         builder = ctx->builder = create_builder (ctx);
3755                         LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
3756
3757                         bblocks [bb->block_num].end_bblock = noex_bb;
3758                         break;
3759                 }
3760                 case OP_START_HANDLER: {
3761                         break;
3762                 }
3763                 case OP_ENDFINALLY: {
3764                         LLVMBasicBlockRef resume_bb;
3765                         MonoBasicBlock *handler_bb;
3766                         LLVMValueRef val, switch_ins, callee;
3767                         GSList *bb_list;
3768                         BBInfo *info;
3769
3770                         handler_bb = g_hash_table_lookup (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)));
3771                         g_assert (handler_bb);
3772                         info = &bblocks [handler_bb->block_num];
3773                         lhs = info->finally_ind;
3774                         g_assert (lhs);
3775
3776                         bb_list = info->call_handler_return_bbs;
3777
3778                         resume_bb = gen_bb (ctx, "ENDFINALLY_RESUME_BB");
3779
3780                         /* Load the finally variable */
3781                         val = LLVMBuildLoad (builder, lhs, "");
3782
3783                         /* Reset the variable */
3784                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), lhs);
3785
3786                         /* Branch to either resume_bb, or to the bblocks in bb_list */
3787                         switch_ins = LLVMBuildSwitch (builder, val, resume_bb, g_slist_length (bb_list));
3788                         /* 
3789                          * The other targets are added at the end to handle OP_CALL_HANDLER
3790                          * opcodes processed later.
3791                          */
3792                         info->endfinally_switch_ins_list = g_slist_append_mempool (cfg->mempool, info->endfinally_switch_ins_list, switch_ins);
3793
3794                         builder = ctx->builder = create_builder (ctx);
3795                         LLVMPositionBuilderAtEnd (ctx->builder, resume_bb);
3796
3797                         if (ctx->cfg->compile_aot) {
3798                                 callee = get_plt_entry (ctx, LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE), MONO_PATCH_INFO_INTERNAL_METHOD, "llvm_resume_unwind_trampoline");
3799                         } else {
3800                                 callee = LLVMGetNamedFunction (module, "llvm_resume_unwind_trampoline");
3801                         }
3802                         LLVMBuildCall (builder, callee, NULL, 0, "");
3803
3804                         LLVMBuildUnreachable (builder);
3805                         has_terminator = TRUE;
3806                         break;
3807                 }
3808                 default: {
3809                         char reason [128];
3810
3811                         sprintf (reason, "opcode %s", mono_inst_name (ins->opcode));
3812                         LLVM_FAILURE (ctx, reason);
3813                         break;
3814                 }
3815                 }
3816
3817                 /* Convert the value to the type required by phi nodes */
3818                 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
3819                         if (!values [ins->dreg])
3820                                 /* vtypes */
3821                                 values [ins->dreg] = addresses [ins->dreg];
3822                         else
3823                                 values [ins->dreg] = convert (ctx, values [ins->dreg], ctx->vreg_types [ins->dreg]);
3824                 }
3825
3826                 /* Add stores for volatile variables */
3827                 if (spec [MONO_INST_DEST] != ' ' && spec [MONO_INST_DEST] != 'v' && !MONO_IS_STORE_MEMBASE (ins))
3828                         emit_volatile_store (ctx, ins->dreg);
3829         }
3830
3831         if (!has_terminator && bb->next_bb && (bb == cfg->bb_entry || bb->in_count > 0))
3832                 LLVMBuildBr (builder, get_bb (ctx, bb->next_bb));
3833
3834         if (bb == cfg->bb_exit && sig->ret->type == MONO_TYPE_VOID)
3835                 LLVMBuildRetVoid (builder);
3836
3837         if (bb == cfg->bb_entry)
3838                 ctx->last_alloca = LLVMGetLastInstruction (get_bb (ctx, cfg->bb_entry));
3839
3840         return;
3841
3842  FAILURE:
3843         return;
3844 }
3845
3846 /*
3847  * mono_llvm_check_method_supported:
3848  *
3849  *   Do some quick checks to decide whenever cfg->method can be compiled by LLVM, to avoid
3850  * compiling a method twice.
3851  */
3852 void
3853 mono_llvm_check_method_supported (MonoCompile *cfg)
3854 {
3855         /*
3856         MonoMethodHeader *header = cfg->header;
3857         MonoExceptionClause *clause;
3858         int i;
3859         */
3860
3861         if (cfg->generic_sharing_context && !IS_LLVM_MONO_BRANCH) {
3862                 /* No way to obtain location info for this/rgctx */
3863                 cfg->exception_message = g_strdup ("gshared");
3864                 cfg->disable_llvm = TRUE;
3865         }
3866
3867         if (cfg->method->save_lmf) {
3868                 cfg->exception_message = g_strdup ("lmf");
3869                 cfg->disable_llvm = TRUE;
3870         }
3871
3872         if (!LLVM_CHECK_VERSION (2, 8)) {
3873                 /*
3874                  * FIXME: LLLVM 2.6 no longer seems to generate correct exception info
3875                  * for JITted code.
3876                  */
3877                 cfg->exception_message = g_strdup ("clauses");
3878                 cfg->disable_llvm = TRUE;
3879         }
3880
3881 #if 0
3882         for (i = 0; i < header->num_clauses; ++i) {
3883                 clause = &header->clauses [i];
3884                 
3885                 if (i > 0 && clause->try_offset <= header->clauses [i - 1].handler_offset + header->clauses [i - 1].handler_len) {
3886                         /*
3887                          * FIXME: Some tests still fail with nested clauses.
3888                          */
3889                         cfg->exception_message = g_strdup ("nested clauses");
3890                         cfg->disable_llvm = TRUE;
3891                 }
3892         }
3893 #endif
3894
3895         /* FIXME: */
3896         if (cfg->method->dynamic) {
3897                 cfg->exception_message = g_strdup ("dynamic.");
3898                 cfg->disable_llvm = TRUE;
3899         }
3900 }
3901
3902 /*
3903  * mono_llvm_emit_method:
3904  *
3905  *   Emit LLVM IL from the mono IL, and compile it to native code using LLVM.
3906  */
3907 void
3908 mono_llvm_emit_method (MonoCompile *cfg)
3909 {
3910         EmitContext *ctx;
3911         MonoMethodSignature *sig;
3912         MonoBasicBlock *bb;
3913         LLVMTypeRef method_type;
3914         LLVMValueRef method = NULL;
3915         char *method_name;
3916         LLVMValueRef *values;
3917         int i, max_block_num, bb_index;
3918         gboolean last = FALSE;
3919         GPtrArray *phi_values;
3920         LLVMCallInfo *linfo;
3921         GSList *l;
3922         LLVMModuleRef module;
3923         BBInfo *bblocks;
3924         GPtrArray *bblock_list;
3925         MonoMethodHeader *header;
3926         MonoExceptionClause *clause;
3927         LLVMSigInfo sinfo;
3928         char **names;
3929
3930         /* The code below might acquire the loader lock, so use it for global locking */
3931         mono_loader_lock ();
3932
3933         /* Used to communicate with the callbacks */
3934         TlsSetValue (current_cfg_tls_id, cfg);
3935
3936         ctx = g_new0 (EmitContext, 1);
3937         ctx->cfg = cfg;
3938         ctx->mempool = cfg->mempool;
3939
3940         /*
3941          * This maps vregs to the LLVM instruction defining them
3942          */
3943         values = g_new0 (LLVMValueRef, cfg->next_vreg);
3944         /*
3945          * This maps vregs for volatile variables to the LLVM instruction defining their
3946          * address.
3947          */
3948         ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
3949         ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
3950         ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
3951         phi_values = g_ptr_array_new ();
3952         /* 
3953          * This signals whenever the vreg was defined by a phi node with no input vars
3954          * (i.e. all its input bblocks end with NOT_REACHABLE).
3955          */
3956         ctx->is_dead = g_new0 (gboolean, cfg->next_vreg);
3957         /* Whenever the bblock is unreachable */
3958         ctx->unreachable = g_new0 (gboolean, cfg->max_block_num);
3959
3960         bblock_list = g_ptr_array_new ();
3961
3962         ctx->values = values;
3963         ctx->region_to_handler = g_hash_table_new (NULL, NULL);
3964  
3965         if (cfg->compile_aot) {
3966                 ctx->lmodule = &aot_module;
3967                 method_name = mono_aot_get_method_name (cfg);
3968                 cfg->llvm_method_name = g_strdup (method_name);
3969         } else {
3970                 init_jit_module ();
3971                 ctx->lmodule = &jit_module;
3972                 method_name = mono_method_full_name (cfg->method, TRUE);
3973         }
3974         
3975         module = ctx->module = ctx->lmodule->module;
3976
3977 #if 1
3978         {
3979                 static int count = 0;
3980                 count ++;
3981
3982                 if (getenv ("LLVM_COUNT")) {
3983                         if (count == atoi (getenv ("LLVM_COUNT"))) {
3984                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
3985                                 fflush (stdout);
3986                                 last = TRUE;
3987                         }
3988                         if (count > atoi (getenv ("LLVM_COUNT")))
3989                                 LLVM_FAILURE (ctx, "");
3990                 }
3991         }
3992 #endif
3993
3994         sig = mono_method_signature (cfg->method);
3995         ctx->sig = sig;
3996
3997         linfo = mono_arch_get_llvm_call_info (cfg, sig);
3998         ctx->linfo = linfo;
3999         CHECK_FAILURE (ctx);
4000
4001         if (cfg->rgctx_var) {
4002                 if (IS_LLVM_MONO_BRANCH)
4003                         linfo->rgctx_arg = TRUE;
4004                 else
4005                         LLVM_FAILURE (ctx, "rgctx arg");
4006         }
4007         method_type = sig_to_llvm_sig_full (ctx, sig, linfo, &sinfo);
4008         CHECK_FAILURE (ctx);
4009
4010         /* 
4011          * This maps parameter indexes in the original signature to the indexes in
4012          * the LLVM signature.
4013          */
4014         ctx->pindexes = sinfo.pindexes;
4015
4016         method = LLVMAddFunction (module, method_name, method_type);
4017         ctx->lmethod = method;
4018
4019 #ifdef LLVM_MONO_BRANCH
4020         LLVMSetFunctionCallConv (method, LLVMMono1CallConv);
4021 #endif
4022         LLVMSetLinkage (method, LLVMPrivateLinkage);
4023
4024         if (cfg->compile_aot) {
4025                 LLVMSetLinkage (method, LLVMInternalLinkage);
4026                 LLVMSetVisibility (method, LLVMHiddenVisibility);
4027         } else {
4028                 LLVMSetLinkage (method, LLVMPrivateLinkage);
4029         }
4030
4031         if (cfg->method->save_lmf)
4032                 LLVM_FAILURE (ctx, "lmf");
4033
4034         if (sig->pinvoke)
4035                 LLVM_FAILURE (ctx, "pinvoke signature");
4036
4037         header = cfg->header;
4038         for (i = 0; i < header->num_clauses; ++i) {
4039                 clause = &header->clauses [i];
4040                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
4041                         LLVM_FAILURE (ctx, "non-finally/catch clause.");
4042         }
4043
4044         if (linfo->rgctx_arg) {
4045                 ctx->rgctx_arg = LLVMGetParam (method, sinfo.rgctx_arg_pindex);
4046                 /*
4047                  * We mark the rgctx parameter with the inreg attribute, which is mapped to
4048                  * MONO_ARCH_RGCTX_REG in the Mono calling convention in llvm, i.e.
4049                  * CC_X86_64_Mono in X86CallingConv.td.
4050                  */
4051                 LLVMAddAttribute (ctx->rgctx_arg, LLVMInRegAttribute);
4052                 LLVMSetValueName (ctx->rgctx_arg, "rgctx");
4053         }
4054         if (cfg->vret_addr) {
4055                 values [cfg->vret_addr->dreg] = LLVMGetParam (method, sinfo.vret_arg_pindex);
4056                 LLVMSetValueName (values [cfg->vret_addr->dreg], "vret");
4057         }
4058         if (sig->hasthis) {
4059                 values [cfg->args [0]->dreg] = LLVMGetParam (method, sinfo.this_arg_pindex);
4060                 LLVMSetValueName (values [cfg->args [0]->dreg], "this");
4061         }
4062
4063         names = g_new (char *, sig->param_count);
4064         mono_method_get_param_names (cfg->method, (const char **) names);
4065
4066         for (i = 0; i < sig->param_count; ++i) {
4067                 char *name;
4068
4069                 values [cfg->args [i + sig->hasthis]->dreg] = LLVMGetParam (method, sinfo.pindexes [i]);
4070                 if (names [i] && names [i][0] != '\0')
4071                         name = g_strdup_printf ("arg_%s", names [i]);
4072                 else
4073                         name = g_strdup_printf ("arg_%d", i);
4074                 LLVMSetValueName (values [cfg->args [i + sig->hasthis]->dreg], name);
4075                 g_free (name);
4076                 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal)
4077                         LLVMAddAttribute (LLVMGetParam (method, sinfo.pindexes [i]), LLVMByValAttribute);
4078         }
4079         g_free (names);
4080
4081         max_block_num = 0;
4082         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4083                 max_block_num = MAX (max_block_num, bb->block_num);
4084         ctx->bblocks = bblocks = g_new0 (BBInfo, max_block_num + 1);
4085
4086         /* Add branches between non-consecutive bblocks */
4087         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4088                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4089                         bb->next_bb != bb->last_ins->inst_false_bb) {
4090                         
4091                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4092                         inst->opcode = OP_BR;
4093                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
4094                         mono_bblock_add_inst (bb, inst);
4095                 }
4096         }
4097
4098         /*
4099          * The INDIRECT flag added by OP_LDADDR inhibits optimizations, even if the LDADDR
4100          * was later optimized away, so clear these flags, and add them back for the still
4101          * present OP_LDADDR instructions.
4102          */
4103         for (i = 0; i < cfg->next_vreg; ++i) {
4104                 MonoInst *ins;
4105
4106                 ins = get_vreg_to_inst (cfg, i);
4107                 if (ins && ins != cfg->rgctx_var)
4108                         ins->flags &= ~MONO_INST_INDIRECT;
4109         }
4110
4111         /*
4112          * Make a first pass over the code to precreate PHI nodes/set INDIRECT flags.
4113          */
4114         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4115                 MonoInst *ins;
4116                 LLVMBuilderRef builder;
4117                 char *dname;
4118                 char dname_buf[128];
4119
4120                 builder = create_builder (ctx);
4121
4122                 for (ins = bb->code; ins; ins = ins->next) {
4123                         switch (ins->opcode) {
4124                         case OP_PHI:
4125                         case OP_FPHI:
4126                         case OP_VPHI:
4127                         case OP_XPHI: {
4128                                 LLVMTypeRef phi_type = llvm_type_to_stack_type (type_to_llvm_type (ctx, &ins->klass->byval_arg));
4129
4130                                 CHECK_FAILURE (ctx);
4131
4132                                 if (ins->opcode == OP_VPHI) {
4133                                         /* Treat valuetype PHI nodes as operating on the address itself */
4134                                         g_assert (ins->klass);
4135                                         phi_type = LLVMPointerType (type_to_llvm_type (ctx, &ins->klass->byval_arg), 0);
4136                                 }
4137
4138                                 /* 
4139                                  * Have to precreate these, as they can be referenced by
4140                                  * earlier instructions.
4141                                  */
4142                                 sprintf (dname_buf, "t%d", ins->dreg);
4143                                 dname = dname_buf;
4144                                 values [ins->dreg] = LLVMBuildPhi (builder, phi_type, dname);
4145
4146                                 if (ins->opcode == OP_VPHI)
4147                                         ctx->addresses [ins->dreg] = values [ins->dreg];
4148
4149                                 g_ptr_array_add (phi_values, values [ins->dreg]);
4150
4151                                 /* 
4152                                  * Set the expected type of the incoming arguments since these have
4153                                  * to have the same type.
4154                                  */
4155                                 for (i = 0; i < ins->inst_phi_args [0]; i++) {
4156                                         int sreg1 = ins->inst_phi_args [i + 1];
4157                                         
4158                                         if (sreg1 != -1)
4159                                                 ctx->vreg_types [sreg1] = phi_type;
4160                                 }
4161                                 break;
4162                                 }
4163                         case OP_LDADDR:
4164                                 ((MonoInst*)ins->inst_p0)->flags |= MONO_INST_INDIRECT;
4165                                 break;
4166                         default:
4167                                 break;
4168                         }
4169                 }
4170         }
4171
4172         /* 
4173          * Create an ordering for bblocks, use the depth first order first, then
4174          * put the exception handling bblocks last.
4175          */
4176         for (bb_index = 0; bb_index < cfg->num_bblocks; ++bb_index) {
4177                 bb = cfg->bblocks [bb_index];
4178                 if (!(bb->region != -1 && !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))) {
4179                         g_ptr_array_add (bblock_list, bb);
4180                         bblocks [bb->block_num].added = TRUE;
4181                 }
4182         }
4183
4184         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4185                 if (!bblocks [bb->block_num].added)
4186                         g_ptr_array_add (bblock_list, bb);
4187         }
4188
4189         /*
4190          * Second pass: generate code.
4191          */
4192         for (bb_index = 0; bb_index < bblock_list->len; ++bb_index) {
4193                 bb = g_ptr_array_index (bblock_list, bb_index);
4194
4195                 if (!(bb == cfg->bb_entry || bb->in_count > 0))
4196                         continue;
4197
4198                 process_bb (ctx, bb);
4199                 CHECK_FAILURE (ctx);
4200         }
4201
4202         /* Add incoming phi values */
4203         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4204                 GSList *l, *ins_list;
4205
4206                 ins_list = bblocks [bb->block_num].phi_nodes;
4207
4208                 for (l = ins_list; l; l = l->next) {
4209                         PhiNode *node = l->data;
4210                         MonoInst *phi = node->phi;
4211                         int sreg1 = node->sreg;
4212                         LLVMBasicBlockRef in_bb;
4213
4214                         if (sreg1 == -1)
4215                                 continue;
4216
4217                         in_bb = get_end_bb (ctx, node->in_bb);
4218
4219                         if (ctx->unreachable [node->in_bb->block_num])
4220                                 continue;
4221
4222                         g_assert (values [sreg1]);
4223
4224                         if (phi->opcode == OP_VPHI) {
4225                                 g_assert (LLVMTypeOf (ctx->addresses [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4226                                 LLVMAddIncoming (values [phi->dreg], &ctx->addresses [sreg1], &in_bb, 1);
4227                         } else {
4228                                 g_assert (LLVMTypeOf (values [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4229                                 LLVMAddIncoming (values [phi->dreg], &values [sreg1], &in_bb, 1);
4230                         }
4231                 }
4232         }
4233
4234         /* Create the SWITCH statements for ENDFINALLY instructions */
4235         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4236                 BBInfo *info = &bblocks [bb->block_num];
4237                 GSList *l;
4238                 for (l = info->endfinally_switch_ins_list; l; l = l->next) {
4239                         LLVMValueRef switch_ins = l->data;
4240                         GSList *bb_list = info->call_handler_return_bbs;
4241
4242                         for (i = 0; i < g_slist_length (bb_list); ++i)
4243                                 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), i + 1, FALSE), g_slist_nth (bb_list, i)->data);
4244                 }
4245         }
4246
4247         if (cfg->verbose_level > 1)
4248                 mono_llvm_dump_value (method);
4249
4250         mark_as_used (module, method);
4251
4252         if (cfg->compile_aot) {
4253                 /* Don't generate native code, keep the LLVM IR */
4254                 if (cfg->compile_aot && cfg->verbose_level)
4255                         printf ("%s emitted as %s\n", mono_method_full_name (cfg->method, TRUE), method_name);
4256
4257                 //LLVMVerifyFunction(method, 0);
4258         } else {
4259                 mono_llvm_optimize_method (method);
4260
4261                 if (cfg->verbose_level > 1)
4262                         mono_llvm_dump_value (method);
4263
4264                 cfg->native_code = LLVMGetPointerToGlobal (ee, method);
4265
4266                 /* Set by emit_cb */
4267                 g_assert (cfg->code_len);
4268
4269                 /* FIXME: Free the LLVM IL for the function */
4270         }
4271
4272         goto CLEANUP;
4273
4274  FAILURE:
4275
4276         if (method) {
4277                 /* Need to add unused phi nodes as they can be referenced by other values */
4278                 LLVMBasicBlockRef phi_bb = LLVMAppendBasicBlock (method, "PHI_BB");
4279                 LLVMBuilderRef builder;
4280
4281                 builder = create_builder (ctx);
4282                 LLVMPositionBuilderAtEnd (builder, phi_bb);
4283
4284                 for (i = 0; i < phi_values->len; ++i) {
4285                         LLVMValueRef v = g_ptr_array_index (phi_values, i);
4286                         if (LLVMGetInstructionParent (v) == NULL)
4287                                 LLVMInsertIntoBuilder (builder, v);
4288                 }
4289                 
4290                 LLVMDeleteFunction (method);
4291         }
4292
4293  CLEANUP:
4294         g_free (values);
4295         g_free (ctx->addresses);
4296         g_free (ctx->vreg_types);
4297         g_free (ctx->vreg_cli_types);
4298         g_free (ctx->pindexes);
4299         g_free (ctx->is_dead);
4300         g_free (ctx->unreachable);
4301         g_ptr_array_free (phi_values, TRUE);
4302         g_free (ctx->bblocks);
4303         g_hash_table_destroy (ctx->region_to_handler);
4304         g_free (method_name);
4305         g_ptr_array_free (bblock_list, TRUE);
4306
4307         for (l = ctx->builders; l; l = l->next) {
4308                 LLVMBuilderRef builder = l->data;
4309                 LLVMDisposeBuilder (builder);
4310         }
4311
4312         g_free (ctx);
4313
4314         TlsSetValue (current_cfg_tls_id, NULL);
4315
4316         mono_loader_unlock ();
4317 }
4318
4319 /*
4320  * mono_llvm_emit_call:
4321  *
4322  *   Same as mono_arch_emit_call () for LLVM.
4323  */
4324 void
4325 mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
4326 {
4327         MonoInst *in;
4328         MonoMethodSignature *sig;
4329         int i, n, stack_size;
4330         LLVMArgInfo *ainfo;
4331
4332         stack_size = 0;
4333
4334         sig = call->signature;
4335         n = sig->param_count + sig->hasthis;
4336
4337         call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4338
4339         if (cfg->disable_llvm)
4340                 return;
4341
4342         if (sig->call_convention == MONO_CALL_VARARG) {
4343                 cfg->exception_message = g_strdup ("varargs");
4344                 cfg->disable_llvm = TRUE;
4345         }
4346
4347         for (i = 0; i < n; ++i) {
4348                 MonoInst *ins;
4349
4350                 ainfo = call->cinfo->args + i;
4351
4352                 in = call->args [i];
4353                         
4354                 /* Simply remember the arguments */
4355                 switch (ainfo->storage) {
4356                 case LLVMArgInIReg:
4357                         MONO_INST_NEW (cfg, ins, OP_MOVE);
4358                         ins->dreg = mono_alloc_ireg (cfg);
4359                         ins->sreg1 = in->dreg;
4360                         break;
4361                 case LLVMArgInFPReg:
4362                         MONO_INST_NEW (cfg, ins, OP_FMOVE);
4363                         ins->dreg = mono_alloc_freg (cfg);
4364                         ins->sreg1 = in->dreg;
4365                         break;
4366                 case LLVMArgVtypeByVal:
4367                 case LLVMArgVtypeInReg:
4368                         MONO_INST_NEW (cfg, ins, OP_LLVM_OUTARG_VT);
4369                         ins->dreg = mono_alloc_ireg (cfg);
4370                         ins->sreg1 = in->dreg;
4371                         ins->klass = mono_class_from_mono_type (sig->params [i - sig->hasthis]);
4372                         break;
4373                 default:
4374                         call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4375                         cfg->exception_message = g_strdup ("ainfo->storage");
4376                         cfg->disable_llvm = TRUE;
4377                         return;
4378                 }
4379
4380                 if (!cfg->disable_llvm) {
4381                         MONO_ADD_INS (cfg->cbb, ins);
4382                         mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, 0, FALSE);
4383                 }
4384         }
4385 }
4386
4387 static unsigned char*
4388 alloc_cb (LLVMValueRef function, int size)
4389 {
4390         MonoCompile *cfg;
4391
4392         cfg = TlsGetValue (current_cfg_tls_id);
4393
4394         if (cfg) {
4395                 // FIXME: dynamic
4396                 return mono_domain_code_reserve (cfg->domain, size);
4397         } else {
4398                 return mono_domain_code_reserve (mono_domain_get (), size);
4399         }
4400 }
4401
4402 static void
4403 emitted_cb (LLVMValueRef function, void *start, void *end)
4404 {
4405         MonoCompile *cfg;
4406
4407         cfg = TlsGetValue (current_cfg_tls_id);
4408         g_assert (cfg);
4409         cfg->code_len = (guint8*)end - (guint8*)start;
4410 }
4411
4412 static void
4413 exception_cb (void *data)
4414 {
4415         MonoCompile *cfg;
4416         MonoJitExceptionInfo *ei;
4417         guint32 ei_len, i, j, nested_len, nindex;
4418         gpointer *type_info;
4419         int this_reg, this_offset;
4420
4421         cfg = TlsGetValue (current_cfg_tls_id);
4422         g_assert (cfg);
4423
4424         /*
4425          * data points to a DWARF FDE structure, convert it to our unwind format and
4426          * save it.
4427          * An alternative would be to save it directly, and modify our unwinder to work
4428          * with it.
4429          */
4430         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);
4431
4432         /* Count nested clauses */
4433         nested_len = 0;
4434         for (i = 0; i < ei_len; ++i) {
4435                 for (j = 0; j < ei_len; ++j) {
4436                         gint32 cindex1 = *(gint32*)type_info [i];
4437                         MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
4438                         gint32 cindex2 = *(gint32*)type_info [j];
4439                         MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
4440
4441                         if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
4442                                 nested_len ++;
4443                         }
4444                 }
4445         }
4446
4447         cfg->llvm_ex_info = mono_mempool_alloc0 (cfg->mempool, (ei_len + nested_len) * sizeof (MonoJitExceptionInfo));
4448         cfg->llvm_ex_info_len = ei_len + nested_len;
4449         memcpy (cfg->llvm_ex_info, ei, ei_len * sizeof (MonoJitExceptionInfo));
4450         /* Fill the rest of the information from the type info */
4451         for (i = 0; i < ei_len; ++i) {
4452                 gint32 clause_index = *(gint32*)type_info [i];
4453                 MonoExceptionClause *clause = &cfg->header->clauses [clause_index];
4454
4455                 cfg->llvm_ex_info [i].flags = clause->flags;
4456                 cfg->llvm_ex_info [i].data.catch_class = clause->data.catch_class;
4457         }
4458
4459         /*
4460          * For nested clauses, the LLVM produced exception info associates the try interval with
4461          * the innermost handler, while mono expects it to be associated with all nesting clauses.
4462          */
4463         /* FIXME: These should be order with the normal clauses */
4464         nindex = ei_len;
4465         for (i = 0; i < ei_len; ++i) {
4466                 for (j = 0; j < ei_len; ++j) {
4467                         gint32 cindex1 = *(gint32*)type_info [i];
4468                         MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
4469                         gint32 cindex2 = *(gint32*)type_info [j];
4470                         MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
4471
4472                         if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
4473                                 /* 
4474                                  * The try interval comes from the nested clause, everything else from the
4475                                  * nesting clause.
4476                                  */
4477                                 memcpy (&cfg->llvm_ex_info [nindex], &cfg->llvm_ex_info [j], sizeof (MonoJitExceptionInfo));
4478                                 cfg->llvm_ex_info [nindex].try_start = cfg->llvm_ex_info [i].try_start;
4479                                 cfg->llvm_ex_info [nindex].try_end = cfg->llvm_ex_info [i].try_end;
4480                                 nindex ++;
4481                         }
4482                 }
4483         }
4484         g_assert (nindex == ei_len + nested_len);
4485         cfg->llvm_this_reg = this_reg;
4486         cfg->llvm_this_offset = this_offset;
4487
4488         /* type_info [i] is cfg mempool allocated, no need to free it */
4489
4490         g_free (ei);
4491         g_free (type_info);
4492 }
4493
4494 static void
4495 add_intrinsics (LLVMModuleRef module)
4496 {
4497         /* Emit declarations of instrinsics */
4498         {
4499                 LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
4500
4501                 if (LLVM_CHECK_VERSION(2, 8)) {
4502                         memset_param_count = 5;
4503                         memset_func_name = "llvm.memset.p0i8.i32";
4504                 } else {
4505                         memset_param_count = 4;
4506                         memset_func_name = "llvm.memset.i32";
4507                 }
4508                 LLVMAddFunction (module, memset_func_name, LLVMFunctionType (LLVMVoidType (), memset_params, memset_param_count, FALSE));
4509         }
4510
4511         {
4512                 LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
4513
4514                 if (LLVM_CHECK_VERSION(2, 8)) {
4515                         memcpy_param_count = 5;
4516                         memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
4517                 } else {
4518                         memcpy_param_count = 4;
4519                         memcpy_func_name = "llvm.memcpy.i32";
4520                 }
4521
4522                 LLVMAddFunction (module, memcpy_func_name, LLVMFunctionType (LLVMVoidType (), memcpy_params, memcpy_param_count, FALSE));
4523         }
4524
4525         {
4526                 LLVMTypeRef params [] = { LLVMDoubleType () };
4527
4528                 LLVMAddFunction (module, "llvm.sin.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
4529                 LLVMAddFunction (module, "llvm.cos.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
4530                 LLVMAddFunction (module, "llvm.sqrt.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
4531
4532                 /* This isn't an intrinsic, instead llvm seems to special case it by name */
4533                 LLVMAddFunction (module, "fabs", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
4534         }
4535
4536         {
4537                 LLVMTypeRef membar_params [] = { LLVMInt1Type (), LLVMInt1Type (), LLVMInt1Type (), LLVMInt1Type (), LLVMInt1Type () };
4538
4539                 LLVMAddFunction (module, "llvm.atomic.swap.i32.p0i32", LLVMFunctionType2 (LLVMInt32Type (), LLVMPointerType (LLVMInt32Type (), 0), LLVMInt32Type (), FALSE));
4540                 LLVMAddFunction (module, "llvm.atomic.swap.i64.p0i64", LLVMFunctionType2 (LLVMInt64Type (), LLVMPointerType (LLVMInt64Type (), 0), LLVMInt64Type (), FALSE));
4541                 LLVMAddFunction (module, "llvm.atomic.load.add.i32.p0i32", LLVMFunctionType2 (LLVMInt32Type (), LLVMPointerType (LLVMInt32Type (), 0), LLVMInt32Type (), FALSE));
4542                 LLVMAddFunction (module, "llvm.atomic.load.add.i64.p0i64", LLVMFunctionType2 (LLVMInt64Type (), LLVMPointerType (LLVMInt64Type (), 0), LLVMInt64Type (), FALSE));
4543                 LLVMAddFunction (module, "llvm.atomic.cmp.swap.i32.p0i32", LLVMFunctionType3 (LLVMInt32Type (), LLVMPointerType (LLVMInt32Type (), 0), LLVMInt32Type (), LLVMInt32Type (), FALSE));
4544                 LLVMAddFunction (module, "llvm.atomic.cmp.swap.i64.p0i64", LLVMFunctionType3 (LLVMInt64Type (), LLVMPointerType (LLVMInt64Type (), 0), LLVMInt64Type (), LLVMInt64Type (), FALSE));
4545                 LLVMAddFunction (module, "llvm.memory.barrier", LLVMFunctionType (LLVMVoidType (), membar_params, 5, FALSE));
4546         }
4547
4548         {
4549                 LLVMTypeRef ovf_res_i32 [] = { LLVMInt32Type (), LLVMInt1Type () };
4550                 LLVMTypeRef ovf_params_i32 [] = { LLVMInt32Type (), LLVMInt32Type () };
4551
4552                 LLVMAddFunction (module, "llvm.sadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
4553                 LLVMAddFunction (module, "llvm.uadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
4554                 LLVMAddFunction (module, "llvm.ssub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
4555                 LLVMAddFunction (module, "llvm.usub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
4556                 LLVMAddFunction (module, "llvm.smul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
4557                 LLVMAddFunction (module, "llvm.umul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
4558         }
4559
4560         {
4561                 LLVMTypeRef ovf_res_i64 [] = { LLVMInt64Type (), LLVMInt1Type () };
4562                 LLVMTypeRef ovf_params_i64 [] = { LLVMInt64Type (), LLVMInt64Type () };
4563
4564                 LLVMAddFunction (module, "llvm.sadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
4565                 LLVMAddFunction (module, "llvm.uadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
4566                 LLVMAddFunction (module, "llvm.ssub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
4567                 LLVMAddFunction (module, "llvm.usub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
4568                 LLVMAddFunction (module, "llvm.smul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
4569                 LLVMAddFunction (module, "llvm.umul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
4570         }
4571
4572         {
4573                 LLVMTypeRef struct_ptr = LLVMPointerType (LLVMStructType (NULL, 0, FALSE), 0);
4574                 LLVMTypeRef invariant_start_params [] = { LLVMInt64Type (), LLVMPointerType (LLVMInt8Type (), 0) };
4575                 LLVMTypeRef invariant_end_params [] = { struct_ptr, LLVMInt64Type (), LLVMPointerType (LLVMInt8Type (), 0) };
4576
4577                 LLVMAddFunction (module, "llvm.invariant.start", LLVMFunctionType (struct_ptr, invariant_start_params, 2, FALSE));
4578
4579                 LLVMAddFunction (module, "llvm.invariant.end", LLVMFunctionType (LLVMVoidType (), invariant_end_params, 3, FALSE));
4580         }
4581
4582         /* EH intrinsics */
4583         {
4584                 LLVMTypeRef arg_types [2];
4585                 LLVMTypeRef ret_type;
4586
4587                 arg_types [0] = LLVMPointerType (LLVMInt8Type (), 0);
4588                 arg_types [1] = LLVMPointerType (LLVMInt8Type (), 0);
4589                 if (LLVM_CHECK_VERSION(2, 8)) {
4590                         eh_selector_name = "llvm.eh.selector";
4591                         ret_type = LLVMInt32Type ();
4592                 } else {
4593                         if (SIZEOF_VOID_P == 8) {
4594                                 eh_selector_name = "llvm.eh.selector.i64";
4595                                 ret_type = LLVMInt64Type ();
4596                         } else {
4597                                 eh_selector_name = "llvm.eh.selector.i32";
4598                                 ret_type = LLVMInt32Type ();
4599                         }
4600                 }
4601                 LLVMAddFunction (module, eh_selector_name, LLVMFunctionType (ret_type, arg_types, 2, TRUE));
4602
4603                 LLVMAddFunction (module, "llvm.eh.exception", LLVMFunctionType (LLVMPointerType (LLVMInt8Type (), 0), NULL, 0, FALSE));
4604
4605                 LLVMAddFunction (module, "mono_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
4606
4607                 LLVMAddFunction (module, "llvm_resume_unwind_trampoline", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
4608         }
4609
4610         /* SSE intrinsics */
4611         {
4612                 LLVMTypeRef ret_type, arg_types [2];
4613
4614                 /* Binary ops */
4615                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4616                 arg_types [0] = ret_type;
4617                 arg_types [1] = ret_type;
4618                 LLVMAddFunction (module, "llvm.x86.sse41.pminud", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4619                 LLVMAddFunction (module, "llvm.x86.sse41.pmaxud", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4620                 LLVMAddFunction (module, "llvm.x86.sse2.pcmpeq.d", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4621
4622                 ret_type = type_to_simd_type (MONO_TYPE_I2);
4623                 arg_types [0] = ret_type;
4624                 arg_types [1] = ret_type;
4625                 LLVMAddFunction (module, "llvm.x86.sse41.pminuw", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4626                 LLVMAddFunction (module, "llvm.x86.sse2.pmins.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4627                 LLVMAddFunction (module, "llvm.x86.sse41.pmaxuw", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4628                 LLVMAddFunction (module, "llvm.x86.sse2.pcmpeq.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4629                 LLVMAddFunction (module, "llvm.x86.sse2.padds.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4630                 LLVMAddFunction (module, "llvm.x86.sse2.psubs.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4631                 LLVMAddFunction (module, "llvm.x86.sse2.paddus.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4632                 LLVMAddFunction (module, "llvm.x86.sse2.psubus.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4633
4634                 ret_type = type_to_simd_type (MONO_TYPE_I1);
4635                 arg_types [0] = ret_type;
4636                 arg_types [1] = ret_type;
4637                 LLVMAddFunction (module, "llvm.x86.sse2.pminu.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4638                 LLVMAddFunction (module, "llvm.x86.sse2.pmaxu.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4639                 LLVMAddFunction (module, "llvm.x86.sse2.pcmpeq.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4640                 LLVMAddFunction (module, "llvm.x86.sse2.pcmpgt.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4641                 LLVMAddFunction (module, "llvm.x86.sse2.padds.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4642                 LLVMAddFunction (module, "llvm.x86.sse2.psubs.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4643                 LLVMAddFunction (module, "llvm.x86.sse2.paddus.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4644                 LLVMAddFunction (module, "llvm.x86.sse2.psubus.b", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4645
4646                 ret_type = type_to_simd_type (MONO_TYPE_I8);
4647                 arg_types [0] = ret_type;
4648                 arg_types [1] = ret_type;
4649                 LLVMAddFunction (module, "llvm.x86.sse41.pcmpeqq", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4650
4651                 ret_type = type_to_simd_type (MONO_TYPE_R8);
4652                 arg_types [0] = ret_type;
4653                 arg_types [1] = ret_type;
4654                 LLVMAddFunction (module, "llvm.x86.sse2.min.pd", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4655                 LLVMAddFunction (module, "llvm.x86.sse2.max.pd", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4656                 LLVMAddFunction (module, "llvm.x86.sse3.hadd.pd", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4657                 LLVMAddFunction (module, "llvm.x86.sse3.hsub.pd", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4658                 LLVMAddFunction (module, "llvm.x86.sse3.addsub.pd", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4659
4660                 ret_type = type_to_simd_type (MONO_TYPE_R4);
4661                 arg_types [0] = ret_type;
4662                 arg_types [1] = ret_type;
4663                 LLVMAddFunction (module, "llvm.x86.sse.min.ps", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4664                 LLVMAddFunction (module, "llvm.x86.sse.max.ps", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4665                 LLVMAddFunction (module, "llvm.x86.sse3.hadd.ps", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4666                 LLVMAddFunction (module, "llvm.x86.sse3.hsub.ps", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4667
4668                 /* cmp pd/ps */
4669                 ret_type = type_to_simd_type (MONO_TYPE_R8);
4670                 arg_types [0] = ret_type;
4671                 arg_types [1] = ret_type;
4672                 arg_types [2] = LLVMInt8Type ();
4673                 LLVMAddFunction (module, "llvm.x86.sse2.cmp.pd", LLVMFunctionType (ret_type, arg_types, 3, FALSE));
4674                 ret_type = type_to_simd_type (MONO_TYPE_R4);
4675                 arg_types [0] = ret_type;
4676                 arg_types [1] = ret_type;
4677                 arg_types [2] = LLVMInt8Type ();
4678                 LLVMAddFunction (module, "llvm.x86.sse.cmp.ps", LLVMFunctionType (ret_type, arg_types, 3, FALSE));
4679
4680                 /* Conversion ops */
4681                 ret_type = type_to_simd_type (MONO_TYPE_R8);
4682                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
4683                 LLVMAddFunction (module, "llvm.x86.sse2.cvtdq2pd", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4684                 ret_type = type_to_simd_type (MONO_TYPE_R4);
4685                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
4686                 LLVMAddFunction (module, "llvm.x86.sse2.cvtdq2ps", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4687                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4688                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
4689                 LLVMAddFunction (module, "llvm.x86.sse2.cvtpd2dq", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4690                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4691                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
4692                 LLVMAddFunction (module, "llvm.x86.sse2.cvtps2dq", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4693                 ret_type = type_to_simd_type (MONO_TYPE_R4);
4694                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
4695                 LLVMAddFunction (module, "llvm.x86.sse2.cvtpd2ps", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4696                 ret_type = type_to_simd_type (MONO_TYPE_R8);
4697                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
4698                 LLVMAddFunction (module, "llvm.x86.sse2.cvtps2pd", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4699
4700                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4701                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
4702                 LLVMAddFunction (module, "llvm.x86.sse2.cvttpd2dq", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4703                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4704                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
4705                 LLVMAddFunction (module, "llvm.x86.sse2.cvttps2dq", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4706
4707                 /* psrl/psll */
4708                 ret_type = type_to_simd_type (MONO_TYPE_I2);
4709                 arg_types [0] = ret_type;
4710                 arg_types [1] = LLVMInt32Type ();
4711                 LLVMAddFunction (module, "llvm.x86.sse2.psrli.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4712                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4713                 arg_types [0] = ret_type;
4714                 arg_types [1] = LLVMInt32Type ();
4715                 LLVMAddFunction (module, "llvm.x86.sse2.psrli.d", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4716                 ret_type = type_to_simd_type (MONO_TYPE_I8);
4717                 arg_types [0] = ret_type;
4718                 arg_types [1] = LLVMInt32Type ();
4719                 LLVMAddFunction (module, "llvm.x86.sse2.psrli.q", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4720                 ret_type = type_to_simd_type (MONO_TYPE_I2);
4721                 arg_types [0] = ret_type;
4722                 arg_types [1] = LLVMInt32Type ();
4723                 LLVMAddFunction (module, "llvm.x86.sse2.pslli.w", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4724                 ret_type = type_to_simd_type (MONO_TYPE_I4);
4725                 arg_types [0] = ret_type;
4726                 arg_types [1] = LLVMInt32Type ();
4727                 LLVMAddFunction (module, "llvm.x86.sse2.pslli.d", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4728                 ret_type = type_to_simd_type (MONO_TYPE_I8);
4729                 arg_types [0] = ret_type;
4730                 arg_types [1] = LLVMInt32Type ();
4731                 LLVMAddFunction (module, "llvm.x86.sse2.pslli.q", LLVMFunctionType (ret_type, arg_types, 2, FALSE));
4732
4733                 /* pmovmskb */
4734                 ret_type = LLVMInt32Type ();
4735                 arg_types [0] = type_to_simd_type (MONO_TYPE_I1);
4736                 LLVMAddFunction (module, "llvm.x86.sse2.pmovmskb.128", LLVMFunctionType (ret_type, arg_types, 1, FALSE));
4737         }
4738
4739         /* Load/Store intrinsics */
4740         if (IS_LLVM_MONO_BRANCH) {
4741                 LLVMTypeRef arg_types [5];
4742                 int i;
4743                 char name [128];
4744
4745                 for (i = 1; i <= 8; i *= 2) {
4746                         arg_types [0] = LLVMPointerType (LLVMIntType (i * 8), 0);
4747                         arg_types [1] = LLVMInt32Type ();
4748                         arg_types [2] = LLVMInt1Type ();
4749                         sprintf (name, "llvm.mono.load.i%d.p0i%d", i * 8, i * 8);
4750                         LLVMAddFunction (module, name, LLVMFunctionType (LLVMIntType (i * 8), arg_types, 3, FALSE));
4751
4752                         arg_types [0] = LLVMIntType (i * 8);
4753                         arg_types [1] = LLVMPointerType (LLVMIntType (i * 8), 0);
4754                         arg_types [2] = LLVMInt32Type ();
4755                         arg_types [3] = LLVMInt1Type ();
4756                         sprintf (name, "llvm.mono.store.i%d.p0i%d", i * 8, i * 8);
4757                         LLVMAddFunction (module, name, LLVMFunctionType (LLVMVoidType (), arg_types, 4, FALSE));
4758                 }
4759         }
4760 }
4761
4762 void
4763 mono_llvm_init (void)
4764 {
4765         current_cfg_tls_id = TlsAlloc ();
4766 }
4767
4768 static void
4769 init_jit_module (void)
4770 {
4771         MonoJitICallInfo *info;
4772
4773         if (jit_module_inited)
4774                 return;
4775
4776         mono_loader_lock ();
4777
4778         if (jit_module_inited) {
4779                 mono_loader_unlock ();
4780                 return;
4781         }
4782
4783         jit_module.module = LLVMModuleCreateWithName ("mono");
4784
4785         ee = mono_llvm_create_ee (LLVMCreateModuleProviderForExistingModule (jit_module.module), alloc_cb, emitted_cb, exception_cb);
4786
4787         add_intrinsics (jit_module.module);
4788
4789         jit_module.llvm_types = g_hash_table_new (NULL, NULL);
4790
4791         info = mono_find_jit_icall_by_name ("llvm_resume_unwind_trampoline");
4792         g_assert (info);
4793         LLVMAddGlobalMapping (ee, LLVMGetNamedFunction (jit_module.module, "llvm_resume_unwind_trampoline"), (void*)info->func);
4794
4795         jit_module_inited = TRUE;
4796
4797         mono_loader_unlock ();
4798 }
4799
4800 void
4801 mono_llvm_cleanup (void)
4802 {
4803         if (ee)
4804                 mono_llvm_dispose_ee (ee);
4805
4806         if (jit_module.llvm_types)
4807                 g_hash_table_destroy (jit_module.llvm_types);
4808
4809         if (aot_module.module)
4810                 LLVMDisposeModule (aot_module.module);
4811
4812         LLVMContextDispose (LLVMGetGlobalContext ());
4813 }
4814
4815 void
4816 mono_llvm_create_aot_module (const char *got_symbol)
4817 {
4818         /* Delete previous module */
4819         if (aot_module.plt_entries)
4820                 g_hash_table_destroy (aot_module.plt_entries);
4821         if (aot_module.module)
4822                 LLVMDisposeModule (aot_module.module);
4823
4824         memset (&aot_module, 0, sizeof (aot_module));
4825
4826         aot_module.module = LLVMModuleCreateWithName ("aot");
4827         aot_module.got_symbol = got_symbol;
4828
4829         add_intrinsics (aot_module.module);
4830
4831         /* Add GOT */
4832         /*
4833          * We couldn't compute the type of the LLVM global representing the got because
4834          * its size is only known after all the methods have been emitted. So create
4835          * a dummy variable, and replace all uses it with the real got variable when
4836          * its size is known in mono_llvm_emit_aot_module ().
4837          */
4838         {
4839                 LLVMTypeRef got_type = LLVMArrayType (IntPtrType (), 0);
4840
4841                 aot_module.got_var = LLVMAddGlobal (aot_module.module, got_type, "mono_dummy_got");
4842                 LLVMSetInitializer (aot_module.got_var, LLVMConstNull (got_type));
4843         }
4844
4845         /* Add a dummy personality function */
4846         {
4847                 LLVMBasicBlockRef lbb;
4848                 LLVMBuilderRef lbuilder;
4849                 LLVMValueRef personality;
4850
4851                 personality = LLVMAddFunction (aot_module.module, "mono_aot_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
4852                 LLVMSetLinkage (personality, LLVMPrivateLinkage);
4853                 lbb = LLVMAppendBasicBlock (personality, "BB0");
4854                 lbuilder = LLVMCreateBuilder ();
4855                 LLVMPositionBuilderAtEnd (lbuilder, lbb);
4856                 LLVMBuildRetVoid (lbuilder);
4857         }
4858
4859         aot_module.llvm_types = g_hash_table_new (NULL, NULL);
4860         aot_module.plt_entries = g_hash_table_new (g_str_hash, g_str_equal);
4861 }
4862
4863 /*
4864  * Emit the aot module into the LLVM bitcode file FILENAME.
4865  */
4866 void
4867 mono_llvm_emit_aot_module (const char *filename, int got_size)
4868 {
4869         LLVMTypeRef got_type;
4870         LLVMValueRef real_got;
4871
4872         /* 
4873          * Create the real got variable and replace all uses of the dummy variable with
4874          * the real one.
4875          */
4876         got_type = LLVMArrayType (IntPtrType (), got_size);
4877         real_got = LLVMAddGlobal (aot_module.module, got_type, aot_module.got_symbol);
4878         LLVMSetInitializer (real_got, LLVMConstNull (got_type));
4879         LLVMSetLinkage (real_got, LLVMInternalLinkage);
4880
4881         mono_llvm_replace_uses_of (aot_module.got_var, real_got);
4882
4883         mark_as_used (aot_module.module, real_got);
4884
4885         /* Delete the dummy got so it doesn't become a global */
4886         LLVMDeleteGlobal (aot_module.got_var);
4887
4888 #if 0
4889         {
4890                 char *verifier_err;
4891
4892                 if (LLVMVerifyModule (aot_module.module, LLVMReturnStatusAction, &verifier_err)) {
4893                         g_assert_not_reached ();
4894                 }
4895         }
4896 #endif
4897
4898         LLVMWriteBitcodeToFile (aot_module.module, filename);
4899 }
4900
4901 /*
4902   DESIGN:
4903   - Emit LLVM IR from the mono IR using the LLVM C API.
4904   - The original arch specific code remains, so we can fall back to it if we run
4905     into something we can't handle.
4906 */
4907
4908 /*  
4909   A partial list of issues:
4910   - Handling of opcodes which can throw exceptions.
4911
4912       In the mono JIT, these are implemented using code like this:
4913           method:
4914       <compare>
4915           throw_pos:
4916           b<cond> ex_label
4917           <rest of code>
4918       ex_label:
4919           push throw_pos - method
4920           call <exception trampoline>
4921
4922           The problematic part is push throw_pos - method, which cannot be represented
4923       in the LLVM IR, since it does not support label values.
4924           -> this can be implemented in AOT mode using inline asm + labels, but cannot
4925           be implemented in JIT mode ?
4926           -> a possible but slower implementation would use the normal exception 
4927       throwing code but it would need to control the placement of the throw code
4928       (it needs to be exactly after the compare+branch).
4929           -> perhaps add a PC offset intrinsics ?
4930
4931   - efficient implementation of .ovf opcodes.
4932
4933           These are currently implemented as:
4934           <ins which sets the condition codes>
4935           b<cond> ex_label
4936
4937           Some overflow opcodes are now supported by LLVM SVN.
4938
4939   - exception handling, unwinding.
4940     - SSA is disabled for methods with exception handlers    
4941         - How to obtain unwind info for LLVM compiled methods ?
4942           -> this is now solved by converting the unwind info generated by LLVM
4943              into our format.
4944         - LLVM uses the c++ exception handling framework, while we use our home grown
4945       code, and couldn't use the c++ one:
4946       - its not supported under VC++, other exotic platforms.
4947           - it might be impossible to support filter clauses with it.
4948
4949   - trampolines.
4950   
4951     The trampolines need a predictable call sequence, since they need to disasm
4952     the calling code to obtain register numbers / offsets.
4953
4954     LLVM currently generates this code in non-JIT mode:
4955            mov    -0x98(%rax),%eax
4956            callq  *%rax
4957     Here, the vtable pointer is lost. 
4958     -> solution: use one vtable trampoline per class.
4959
4960   - passing/receiving the IMT pointer/RGCTX.
4961     -> solution: pass them as normal arguments ?
4962
4963   - argument passing.
4964   
4965           LLVM does not allow the specification of argument registers etc. This means
4966       that all calls are made according to the platform ABI.
4967
4968   - passing/receiving vtypes.
4969
4970       Vtypes passed/received in registers are handled by the front end by using
4971           a signature with scalar arguments, and loading the parts of the vtype into those
4972           arguments.
4973
4974           Vtypes passed on the stack are handled using the 'byval' attribute.
4975
4976   - ldaddr.
4977
4978     Supported though alloca, we need to emit the load/store code.
4979
4980   - types.
4981
4982     The mono JIT uses pointer sized iregs/double fregs, while LLVM uses precisely
4983     typed registers, so we have to keep track of the precise LLVM type of each vreg.
4984     This is made easier because the IR is already in SSA form.
4985     An additional problem is that our IR is not consistent with types, i.e. i32/ia64 
4986         types are frequently used incorrectly.
4987 */
4988
4989 /*
4990   AOT SUPPORT:
4991   Emit LLVM bytecode into a .bc file, compile it using llc into a .s file, then 
4992   append the AOT data structures to that file. For methods which cannot be
4993   handled by LLVM, the normal JIT compiled versions are used.
4994 */
4995
4996 /* FIXME: Normalize some aspects of the mono IR to allow easier translation, like:
4997  *   - each bblock should end with a branch
4998  *   - setting the return value, making cfg->ret non-volatile
4999  * - avoid some transformations in the JIT which make it harder for us to generate
5000  *   code.
5001  * - use pointer types to help optimizations.
5002  */