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