2 * mini-llvm.c: llvm "Backend" for the mono JIT
4 * Copyright 2009-2011 Novell Inc (http://www.novell.com)
5 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
9 #include <mono/metadata/debug-helpers.h>
10 #include <mono/metadata/debug-mono-symfile.h>
11 #include <mono/metadata/mempool-internals.h>
12 #include <mono/utils/mono-tls.h>
13 #include <mono/utils/mono-dl.h>
14 #include <mono/utils/mono-time.h>
15 #include <mono/utils/freebsd-dwarf.h>
17 #ifndef __STDC_LIMIT_MACROS
18 #define __STDC_LIMIT_MACROS
20 #ifndef __STDC_CONSTANT_MACROS
21 #define __STDC_CONSTANT_MACROS
24 #include "llvm-c/Core.h"
25 #include "llvm-c/ExecutionEngine.h"
26 #include "llvm-c/BitWriter.h"
27 #include "llvm-c/Analysis.h"
29 #include "mini-llvm-cpp.h"
32 * Information associated by mono with LLVM modules.
36 LLVMValueRef throw, rethrow, throw_corlib_exception;
37 GHashTable *llvm_types;
39 const char *got_symbol;
40 GHashTable *plt_entries;
41 GHashTable *plt_entries_ji;
42 GHashTable *method_to_lmethod;
47 GPtrArray *subprogram_mds;
49 LLVMExecutionEngineRef ee;
53 * Information associated by the backend with mono basic blocks.
56 LLVMBasicBlockRef bblock, end_bblock;
57 LLVMValueRef finally_ind;
58 gboolean added, invoke_target;
60 * If this bblock is the start of a finally clause, this is a list of bblocks it
61 * needs to branch to in ENDFINALLY.
63 GSList *call_handler_return_bbs;
65 * If this bblock is the start of a finally clause, this is the bblock that
66 * CALL_HANDLER needs to branch to.
68 LLVMBasicBlockRef call_handler_target_bb;
69 /* The list of switch statements generated by ENDFINALLY instructions */
70 GSList *endfinally_switch_ins_list;
75 * Structure containing emit state
80 /* Maps method names to the corresponding LLVMValueRef */
81 GHashTable *emitted_method_decls;
85 MonoLLVMModule *lmodule;
88 int sindex, default_index, ex_index;
89 LLVMBuilderRef builder;
90 LLVMValueRef *values, *addresses;
91 MonoType **vreg_cli_types;
93 MonoMethodSignature *sig;
95 GHashTable *region_to_handler;
96 LLVMBuilderRef alloca_builder;
97 LLVMValueRef last_alloca;
98 LLVMValueRef rgctx_arg;
99 LLVMTypeRef *vreg_types;
101 gboolean *unreachable;
103 LLVMValueRef imt_rgctx_loc;
104 GHashTable *llvm_types;
106 MonoDebugMethodInfo *minfo;
113 MonoBasicBlock *in_bb;
118 * Instruction metadata
119 * This is the same as ins_info, but LREG != IREG.
127 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
128 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
135 /* keep in sync with the enum in mini.h */
138 #include "mini-ops.h"
143 #if SIZEOF_VOID_P == 4
144 #define GET_LONG_IMM(ins) (((guint64)(ins)->inst_ms_word << 32) | (guint64)(guint32)(ins)->inst_ls_word)
146 #define GET_LONG_IMM(ins) ((ins)->inst_imm)
149 #define LLVM_INS_INFO(opcode) (&llvm_ins_info [((opcode) - OP_START - 1) * 4])
152 #define TRACE_FAILURE(msg) do { printf ("%s\n", msg); } while (0)
154 #define TRACE_FAILURE(msg)
158 #define IS_TARGET_X86 1
160 #define IS_TARGET_X86 0
164 #define IS_TARGET_AMD64 1
166 #define IS_TARGET_AMD64 0
169 #define LLVM_FAILURE(ctx, reason) do { \
170 TRACE_FAILURE (reason); \
171 (ctx)->cfg->exception_message = g_strdup (reason); \
172 (ctx)->cfg->disable_llvm = TRUE; \
176 #define CHECK_FAILURE(ctx) do { \
177 if ((ctx)->cfg->disable_llvm) \
181 static LLVMIntPredicate cond_to_llvm_cond [] = {
194 static LLVMRealPredicate fpcond_to_llvm_cond [] = {
207 static MonoNativeTlsKey current_cfg_tls_id;
209 static MonoLLVMModule aot_module;
210 static int memset_param_count, memcpy_param_count;
211 static const char *memset_func_name;
212 static const char *memcpy_func_name;
214 static void init_jit_module (MonoDomain *domain);
216 static void emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code);
217 static LLVMValueRef emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name);
218 static void emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name);
223 * The LLVM type with width == sizeof (gpointer)
228 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
234 return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
240 return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
246 * Return the size of the LLVM representation of the vtype T.
249 get_vtype_size (MonoType *t)
253 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
255 while (size < 2 * sizeof (gpointer) && mono_is_power_of_two (size) == -1)
262 * simd_class_to_llvm_type:
264 * Return the LLVM type corresponding to the Mono.SIMD class KLASS
267 simd_class_to_llvm_type (EmitContext *ctx, MonoClass *klass)
269 if (!strcmp (klass->name, "Vector2d")) {
270 return LLVMVectorType (LLVMDoubleType (), 2);
271 } else if (!strcmp (klass->name, "Vector2l")) {
272 return LLVMVectorType (LLVMInt64Type (), 2);
273 } else if (!strcmp (klass->name, "Vector2ul")) {
274 return LLVMVectorType (LLVMInt64Type (), 2);
275 } else if (!strcmp (klass->name, "Vector4i")) {
276 return LLVMVectorType (LLVMInt32Type (), 4);
277 } else if (!strcmp (klass->name, "Vector4ui")) {
278 return LLVMVectorType (LLVMInt32Type (), 4);
279 } else if (!strcmp (klass->name, "Vector4f")) {
280 return LLVMVectorType (LLVMFloatType (), 4);
281 } else if (!strcmp (klass->name, "Vector8s")) {
282 return LLVMVectorType (LLVMInt16Type (), 8);
283 } else if (!strcmp (klass->name, "Vector8us")) {
284 return LLVMVectorType (LLVMInt16Type (), 8);
285 } else if (!strcmp (klass->name, "Vector16sb")) {
286 return LLVMVectorType (LLVMInt8Type (), 16);
287 } else if (!strcmp (klass->name, "Vector16b")) {
288 return LLVMVectorType (LLVMInt8Type (), 16);
290 printf ("%s\n", klass->name);
296 /* Return the 128 bit SIMD type corresponding to the mono type TYPE */
297 static inline G_GNUC_UNUSED LLVMTypeRef
298 type_to_simd_type (int type)
302 return LLVMVectorType (LLVMInt8Type (), 16);
304 return LLVMVectorType (LLVMInt16Type (), 8);
306 return LLVMVectorType (LLVMInt32Type (), 4);
308 return LLVMVectorType (LLVMInt64Type (), 2);
310 return LLVMVectorType (LLVMDoubleType (), 2);
312 return LLVMVectorType (LLVMFloatType (), 4);
314 g_assert_not_reached ();
322 * Return the LLVM type corresponding to T.
325 type_to_llvm_type (EmitContext *ctx, MonoType *t)
327 t = mini_replace_type (t);
330 return LLVMPointerType (LLVMInt8Type (), 0);
333 return LLVMVoidType ();
335 return LLVMInt8Type ();
337 return LLVMInt16Type ();
339 return LLVMInt32Type ();
341 return LLVMInt8Type ();
343 return LLVMInt16Type ();
345 return LLVMInt32Type ();
346 case MONO_TYPE_BOOLEAN:
347 return LLVMInt8Type ();
350 return LLVMInt64Type ();
352 return LLVMInt16Type ();
354 return LLVMFloatType ();
356 return LLVMDoubleType ();
359 return IntPtrType ();
360 case MONO_TYPE_OBJECT:
361 case MONO_TYPE_CLASS:
362 case MONO_TYPE_ARRAY:
363 case MONO_TYPE_SZARRAY:
364 case MONO_TYPE_STRING:
366 return ObjRefType ();
369 /* Because of generic sharing */
370 return ObjRefType ();
371 case MONO_TYPE_GENERICINST:
372 if (!mono_type_generic_inst_is_valuetype (t))
373 return ObjRefType ();
375 case MONO_TYPE_VALUETYPE:
376 case MONO_TYPE_TYPEDBYREF: {
380 klass = mono_class_from_mono_type (t);
382 if (MONO_CLASS_IS_SIMD (ctx->cfg, klass))
383 return simd_class_to_llvm_type (ctx, klass);
386 return type_to_llvm_type (ctx, mono_class_enum_basetype (klass));
388 ltype = g_hash_table_lookup (ctx->lmodule->llvm_types, klass);
391 LLVMTypeRef *eltypes;
394 size = get_vtype_size (t);
396 eltypes = g_new (LLVMTypeRef, size);
397 for (i = 0; i < size; ++i)
398 eltypes [i] = LLVMInt8Type ();
400 name = mono_type_full_name (&klass->byval_arg);
401 ltype = LLVMStructCreateNamed (LLVMGetGlobalContext (), name);
402 LLVMStructSetBody (ltype, eltypes, size, FALSE);
403 g_hash_table_insert (ctx->lmodule->llvm_types, klass, ltype);
411 printf ("X: %d\n", t->type);
412 ctx->cfg->exception_message = g_strdup_printf ("type %s", mono_type_full_name (t));
413 ctx->cfg->disable_llvm = TRUE;
421 * Return whenever T is an unsigned int type.
424 type_is_unsigned (EmitContext *ctx, MonoType *t)
441 * type_to_llvm_arg_type:
443 * Same as type_to_llvm_type, but treat i8/i16 as i32.
446 type_to_llvm_arg_type (EmitContext *ctx, MonoType *t)
448 LLVMTypeRef ptype = type_to_llvm_type (ctx, t);
451 * This works on all abis except arm64/ios which passes multiple
452 * arguments in one stack slot.
455 if (ptype == LLVMInt8Type () || ptype == LLVMInt16Type ()) {
457 * LLVM generates code which only sets the lower bits, while JITted
458 * code expects all the bits to be set.
460 ptype = LLVMInt32Type ();
468 * llvm_type_to_stack_type:
470 * Return the LLVM type which needs to be used when a value of type TYPE is pushed
473 static G_GNUC_UNUSED LLVMTypeRef
474 llvm_type_to_stack_type (LLVMTypeRef type)
478 if (type == LLVMInt8Type ())
479 return LLVMInt32Type ();
480 else if (type == LLVMInt16Type ())
481 return LLVMInt32Type ();
482 else if (type == LLVMFloatType ())
483 return LLVMDoubleType ();
489 * regtype_to_llvm_type:
491 * Return the LLVM type corresponding to the regtype C used in instruction
495 regtype_to_llvm_type (char c)
499 return LLVMInt32Type ();
501 return LLVMInt64Type ();
503 return LLVMDoubleType ();
512 * Return the LLVM type corresponding to the unary/binary opcode OPCODE.
515 op_to_llvm_type (int opcode)
520 return LLVMInt8Type ();
523 return LLVMInt8Type ();
526 return LLVMInt16Type ();
529 return LLVMInt16Type ();
532 return LLVMInt32Type ();
535 return LLVMInt32Type ();
537 return LLVMInt64Type ();
539 return LLVMFloatType ();
541 return LLVMDoubleType ();
543 return LLVMInt64Type ();
545 return LLVMInt32Type ();
547 return LLVMInt64Type ();
550 return LLVMInt8Type ();
553 return LLVMInt16Type ();
556 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
563 return LLVMInt32Type ();
570 return LLVMInt64Type ();
572 printf ("%s\n", mono_inst_name (opcode));
573 g_assert_not_reached ();
579 * load_store_to_llvm_type:
581 * Return the size/sign/zero extension corresponding to the load/store opcode
585 load_store_to_llvm_type (int opcode, int *size, gboolean *sext, gboolean *zext)
591 case OP_LOADI1_MEMBASE:
592 case OP_STOREI1_MEMBASE_REG:
593 case OP_STOREI1_MEMBASE_IMM:
596 return LLVMInt8Type ();
597 case OP_LOADU1_MEMBASE:
601 return LLVMInt8Type ();
602 case OP_LOADI2_MEMBASE:
603 case OP_STOREI2_MEMBASE_REG:
604 case OP_STOREI2_MEMBASE_IMM:
607 return LLVMInt16Type ();
608 case OP_LOADU2_MEMBASE:
612 return LLVMInt16Type ();
613 case OP_LOADI4_MEMBASE:
614 case OP_LOADU4_MEMBASE:
617 case OP_STOREI4_MEMBASE_REG:
618 case OP_STOREI4_MEMBASE_IMM:
620 return LLVMInt32Type ();
621 case OP_LOADI8_MEMBASE:
623 case OP_STOREI8_MEMBASE_REG:
624 case OP_STOREI8_MEMBASE_IMM:
626 return LLVMInt64Type ();
627 case OP_LOADR4_MEMBASE:
628 case OP_STORER4_MEMBASE_REG:
630 return LLVMFloatType ();
631 case OP_LOADR8_MEMBASE:
632 case OP_STORER8_MEMBASE_REG:
634 return LLVMDoubleType ();
635 case OP_LOAD_MEMBASE:
637 case OP_STORE_MEMBASE_REG:
638 case OP_STORE_MEMBASE_IMM:
639 *size = sizeof (gpointer);
640 return IntPtrType ();
642 g_assert_not_reached ();
650 * Return the LLVM intrinsics corresponding to the overflow opcode OPCODE.
653 ovf_op_to_intrins (int opcode)
657 return "llvm.sadd.with.overflow.i32";
659 return "llvm.uadd.with.overflow.i32";
661 return "llvm.ssub.with.overflow.i32";
663 return "llvm.usub.with.overflow.i32";
665 return "llvm.smul.with.overflow.i32";
667 return "llvm.umul.with.overflow.i32";
669 return "llvm.sadd.with.overflow.i64";
671 return "llvm.uadd.with.overflow.i64";
673 return "llvm.ssub.with.overflow.i64";
675 return "llvm.usub.with.overflow.i64";
677 return "llvm.smul.with.overflow.i64";
679 return "llvm.umul.with.overflow.i64";
681 g_assert_not_reached ();
687 simd_op_to_intrins (int opcode)
690 #if defined(TARGET_X86) || defined(TARGET_AMD64)
692 return "llvm.x86.sse2.min.pd";
694 return "llvm.x86.sse.min.ps";
696 return "llvm.x86.sse41.pminud";
698 return "llvm.x86.sse41.pminuw";
700 return "llvm.x86.sse2.pminu.b";
702 return "llvm.x86.sse2.pmins.w";
704 return "llvm.x86.sse2.max.pd";
706 return "llvm.x86.sse.max.ps";
708 return "llvm.x86.sse3.hadd.pd";
710 return "llvm.x86.sse3.hadd.ps";
712 return "llvm.x86.sse3.hsub.pd";
714 return "llvm.x86.sse3.hsub.ps";
716 return "llvm.x86.sse41.pmaxud";
718 return "llvm.x86.sse41.pmaxuw";
720 return "llvm.x86.sse2.pmaxu.b";
722 return "llvm.x86.sse3.addsub.ps";
724 return "llvm.x86.sse3.addsub.pd";
725 case OP_EXTRACT_MASK:
726 return "llvm.x86.sse2.pmovmskb.128";
729 return "llvm.x86.sse2.psrli.w";
732 return "llvm.x86.sse2.psrli.d";
735 return "llvm.x86.sse2.psrli.q";
738 return "llvm.x86.sse2.pslli.w";
741 return "llvm.x86.sse2.pslli.d";
744 return "llvm.x86.sse2.pslli.q";
747 return "llvm.x86.sse2.psrai.w";
750 return "llvm.x86.sse2.psrai.d";
752 return "llvm.x86.sse2.padds.b";
754 return "llvm.x86.sse2.padds.w";
756 return "llvm.x86.sse2.psubs.b";
758 return "llvm.x86.sse2.psubs.w";
759 case OP_PADDB_SAT_UN:
760 return "llvm.x86.sse2.paddus.b";
761 case OP_PADDW_SAT_UN:
762 return "llvm.x86.sse2.paddus.w";
763 case OP_PSUBB_SAT_UN:
764 return "llvm.x86.sse2.psubus.b";
765 case OP_PSUBW_SAT_UN:
766 return "llvm.x86.sse2.psubus.w";
768 return "llvm.x86.sse2.pavg.b";
770 return "llvm.x86.sse2.pavg.w";
772 return "llvm.x86.sse.sqrt.ps";
774 return "llvm.x86.sse2.sqrt.pd";
776 return "llvm.x86.sse.rsqrt.ps";
778 return "llvm.x86.sse.rcp.ps";
780 return "llvm.x86.sse2.cvtdq2pd";
782 return "llvm.x86.sse2.cvtdq2ps";
784 return "llvm.x86.sse2.cvtpd2dq";
786 return "llvm.x86.sse2.cvtps2dq";
788 return "llvm.x86.sse2.cvtpd2ps";
790 return "llvm.x86.sse2.cvtps2pd";
792 return "llvm.x86.sse2.cvttpd2dq";
794 return "llvm.x86.sse2.cvttps2dq";
796 return "llvm.x86.sse.cmp.ps";
798 return "llvm.x86.sse2.cmp.pd";
800 return "llvm.x86.sse2.packsswb.128";
802 return "llvm.x86.sse2.packssdw.128";
804 return "llvm.x86.sse2.packuswb.128";
806 return "llvm.x86.sse41.packusdw";
808 return "llvm.x86.sse2.pmulh.w";
809 case OP_PMULW_HIGH_UN:
810 return "llvm.x86.sse2.pmulhu.w";
813 g_assert_not_reached ();
819 simd_op_to_llvm_type (int opcode)
821 #if defined(TARGET_X86) || defined(TARGET_AMD64)
825 return type_to_simd_type (MONO_TYPE_R8);
828 return type_to_simd_type (MONO_TYPE_I8);
831 return type_to_simd_type (MONO_TYPE_I4);
836 return type_to_simd_type (MONO_TYPE_I2);
840 return type_to_simd_type (MONO_TYPE_I1);
842 return type_to_simd_type (MONO_TYPE_R4);
845 return type_to_simd_type (MONO_TYPE_I4);
849 return type_to_simd_type (MONO_TYPE_R8);
853 return type_to_simd_type (MONO_TYPE_R4);
854 case OP_EXTRACT_MASK:
855 return type_to_simd_type (MONO_TYPE_I1);
861 return type_to_simd_type (MONO_TYPE_R4);
864 return type_to_simd_type (MONO_TYPE_R8);
866 g_assert_not_reached ();
877 * Return the LLVM basic block corresponding to BB.
879 static LLVMBasicBlockRef
880 get_bb (EmitContext *ctx, MonoBasicBlock *bb)
882 char bb_name_buf [128];
885 if (ctx->bblocks [bb->block_num].bblock == NULL) {
886 if (bb->flags & BB_EXCEPTION_HANDLER) {
887 int clause_index = (mono_get_block_region_notry (ctx->cfg, bb->region) >> 8) - 1;
888 sprintf (bb_name_buf, "EH_CLAUSE%d_BB%d", clause_index, bb->block_num);
889 bb_name = bb_name_buf;
890 } else if (bb->block_num < 256) {
891 if (!ctx->lmodule->bb_names) {
892 ctx->lmodule->bb_names_len = 256;
893 ctx->lmodule->bb_names = g_new0 (char*, ctx->lmodule->bb_names_len);
895 if (!ctx->lmodule->bb_names [bb->block_num]) {
898 n = g_strdup_printf ("BB%d", bb->block_num);
899 mono_memory_barrier ();
900 ctx->lmodule->bb_names [bb->block_num] = n;
902 bb_name = ctx->lmodule->bb_names [bb->block_num];
904 sprintf (bb_name_buf, "BB%d", bb->block_num);
905 bb_name = bb_name_buf;
908 ctx->bblocks [bb->block_num].bblock = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
909 ctx->bblocks [bb->block_num].end_bblock = ctx->bblocks [bb->block_num].bblock;
912 return ctx->bblocks [bb->block_num].bblock;
918 * Return the last LLVM bblock corresponding to BB.
919 * This might not be equal to the bb returned by get_bb () since we need to generate
920 * multiple LLVM bblocks for a mono bblock to handle throwing exceptions.
922 static LLVMBasicBlockRef
923 get_end_bb (EmitContext *ctx, MonoBasicBlock *bb)
926 return ctx->bblocks [bb->block_num].end_bblock;
929 static LLVMBasicBlockRef
930 gen_bb (EmitContext *ctx, const char *prefix)
934 sprintf (bb_name, "%s%d", prefix, ++ ctx->ex_index);
935 return LLVMAppendBasicBlock (ctx->lmethod, bb_name);
941 * Return the target of the patch identified by TYPE and TARGET.
944 resolve_patch (MonoCompile *cfg, MonoJumpInfoType type, gconstpointer target)
948 memset (&ji, 0, sizeof (ji));
950 ji.data.target = target;
952 return mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
958 * Emit code to convert the LLVM value V to DTYPE.
961 convert_full (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype, gboolean is_unsigned)
963 LLVMTypeRef stype = LLVMTypeOf (v);
965 if (stype != dtype) {
966 gboolean ext = FALSE;
969 if (dtype == LLVMInt64Type () && (stype == LLVMInt32Type () || stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
971 else if (dtype == LLVMInt32Type () && (stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
973 else if (dtype == LLVMInt16Type () && (stype == LLVMInt8Type ()))
977 return is_unsigned ? LLVMBuildZExt (ctx->builder, v, dtype, "") : LLVMBuildSExt (ctx->builder, v, dtype, "");
979 if (dtype == LLVMDoubleType () && stype == LLVMFloatType ())
980 return LLVMBuildFPExt (ctx->builder, v, dtype, "");
983 if (stype == LLVMInt64Type () && (dtype == LLVMInt32Type () || dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
984 return LLVMBuildTrunc (ctx->builder, v, dtype, "");
985 if (stype == LLVMInt32Type () && (dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
986 return LLVMBuildTrunc (ctx->builder, v, dtype, "");
987 if (stype == LLVMInt16Type () && dtype == LLVMInt8Type ())
988 return LLVMBuildTrunc (ctx->builder, v, dtype, "");
989 if (stype == LLVMDoubleType () && dtype == LLVMFloatType ())
990 return LLVMBuildFPTrunc (ctx->builder, v, dtype, "");
992 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind && LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
993 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
994 if (LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
995 return LLVMBuildIntToPtr (ctx->builder, v, dtype, "");
996 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind)
997 return LLVMBuildPtrToInt (ctx->builder, v, dtype, "");
999 if (mono_arch_is_soft_float ()) {
1000 if (stype == LLVMInt32Type () && dtype == LLVMFloatType ())
1001 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1002 if (stype == LLVMInt32Type () && dtype == LLVMDoubleType ())
1003 return LLVMBuildBitCast (ctx->builder, LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), ""), dtype, "");
1006 if (LLVMGetTypeKind (stype) == LLVMVectorTypeKind && LLVMGetTypeKind (dtype) == LLVMVectorTypeKind)
1007 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1010 LLVMDumpValue (LLVMConstNull (dtype));
1011 g_assert_not_reached ();
1019 convert (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype)
1021 return convert_full (ctx, v, dtype, FALSE);
1025 * emit_volatile_load:
1027 * If vreg is volatile, emit a load from its address.
1030 emit_volatile_load (EmitContext *ctx, int vreg)
1034 LLVMValueRef v = LLVMBuildLoad (ctx->builder, ctx->addresses [vreg], "");
1035 t = ctx->vreg_cli_types [vreg];
1036 if (t && !t->byref) {
1038 * Might have to zero extend since llvm doesn't have
1041 if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_U2 || t->type == MONO_TYPE_CHAR || t->type == MONO_TYPE_BOOLEAN)
1042 v = LLVMBuildZExt (ctx->builder, v, LLVMInt32Type (), "");
1043 else if (t->type == MONO_TYPE_U8)
1044 v = LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), "");
1051 * emit_volatile_store:
1053 * If VREG is volatile, emit a store from its value to its address.
1056 emit_volatile_store (EmitContext *ctx, int vreg)
1058 MonoInst *var = get_vreg_to_inst (ctx->cfg, vreg);
1060 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
1061 g_assert (ctx->addresses [vreg]);
1062 LLVMBuildStore (ctx->builder, convert (ctx, ctx->values [vreg], type_to_llvm_type (ctx, var->inst_vtype)), ctx->addresses [vreg]);
1068 * Maps parameter indexes in the original signature to parameter indexes
1069 * in the LLVM signature.
1072 /* The indexes of various special arguments in the LLVM signature */
1073 int vret_arg_pindex, this_arg_pindex, rgctx_arg_pindex, imt_arg_pindex;
1077 * sig_to_llvm_sig_full:
1079 * Return the LLVM signature corresponding to the mono signature SIG using the
1080 * calling convention information in CINFO. Return parameter mapping information in SINFO.
1083 sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *cinfo,
1086 LLVMTypeRef ret_type;
1087 LLVMTypeRef *param_types = NULL;
1089 int i, j, pindex, vret_arg_pindex = 0;
1091 gboolean vretaddr = FALSE;
1095 memset (sinfo, 0, sizeof (LLVMSigInfo));
1097 rtype = mini_replace_type (sig->ret);
1098 ret_type = type_to_llvm_type (ctx, rtype);
1099 CHECK_FAILURE (ctx);
1101 if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
1102 /* LLVM models this by returning an aggregate value */
1103 if (cinfo->ret.pair_storage [0] == LLVMArgInIReg && cinfo->ret.pair_storage [1] == LLVMArgNone) {
1104 LLVMTypeRef members [2];
1106 members [0] = IntPtrType ();
1107 ret_type = LLVMStructType (members, 1, FALSE);
1109 g_assert_not_reached ();
1111 } else if (cinfo && mini_type_is_vtype (ctx->cfg, rtype)) {
1112 g_assert (cinfo->ret.storage == LLVMArgVtypeRetAddr);
1114 ret_type = LLVMVoidType ();
1117 pindexes = g_new0 (int, sig->param_count);
1118 param_types = g_new0 (LLVMTypeRef, (sig->param_count * 2) + 3);
1120 if (cinfo && cinfo->rgctx_arg) {
1122 sinfo->rgctx_arg_pindex = pindex;
1123 param_types [pindex] = ctx->lmodule->ptr_type;
1126 if (cinfo && cinfo->imt_arg) {
1128 sinfo->imt_arg_pindex = pindex;
1129 param_types [pindex] = ctx->lmodule->ptr_type;
1133 /* Compute the index in the LLVM signature where the vret arg needs to be passed */
1134 vret_arg_pindex = pindex;
1135 if (cinfo->vret_arg_index == 1) {
1136 /* Add the slots consumed by the first argument */
1137 LLVMArgInfo *ainfo = &cinfo->args [0];
1138 switch (ainfo->storage) {
1139 case LLVMArgVtypeInReg:
1140 for (j = 0; j < 2; ++j) {
1141 if (ainfo->pair_storage [j] == LLVMArgInIReg)
1151 sinfo->vret_arg_pindex = vret_arg_pindex;
1154 if (vretaddr && vret_arg_pindex == pindex)
1155 param_types [pindex ++] = IntPtrType ();
1158 sinfo->this_arg_pindex = pindex;
1159 param_types [pindex ++] = ThisType ();
1161 if (vretaddr && vret_arg_pindex == pindex)
1162 param_types [pindex ++] = IntPtrType ();
1163 for (i = 0; i < sig->param_count; ++i) {
1164 if (vretaddr && vret_arg_pindex == pindex)
1165 param_types [pindex ++] = IntPtrType ();
1166 pindexes [i] = pindex;
1167 if (cinfo && cinfo->args [i + sig->hasthis].storage == LLVMArgVtypeInReg) {
1168 for (j = 0; j < 2; ++j) {
1169 switch (cinfo->args [i + sig->hasthis].pair_storage [j]) {
1171 param_types [pindex ++] = LLVMIntType (sizeof (gpointer) * 8);
1176 g_assert_not_reached ();
1179 } else if (cinfo && cinfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal) {
1180 param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1181 CHECK_FAILURE (ctx);
1182 param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1185 param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1188 if (vretaddr && vret_arg_pindex == pindex)
1189 param_types [pindex ++] = IntPtrType ();
1191 CHECK_FAILURE (ctx);
1193 res = LLVMFunctionType (ret_type, param_types, pindex, FALSE);
1194 g_free (param_types);
1197 sinfo->pindexes = pindexes;
1205 g_free (param_types);
1211 sig_to_llvm_sig (EmitContext *ctx, MonoMethodSignature *sig)
1213 return sig_to_llvm_sig_full (ctx, sig, NULL, NULL);
1217 * LLVMFunctionType1:
1219 * Create an LLVM function type from the arguments.
1221 static G_GNUC_UNUSED LLVMTypeRef
1222 LLVMFunctionType1(LLVMTypeRef ReturnType,
1223 LLVMTypeRef ParamType1,
1226 LLVMTypeRef param_types [1];
1228 param_types [0] = ParamType1;
1230 return LLVMFunctionType (ReturnType, param_types, 1, IsVarArg);
1234 * LLVMFunctionType2:
1236 * Create an LLVM function type from the arguments.
1238 static G_GNUC_UNUSED LLVMTypeRef
1239 LLVMFunctionType2(LLVMTypeRef ReturnType,
1240 LLVMTypeRef ParamType1,
1241 LLVMTypeRef ParamType2,
1244 LLVMTypeRef param_types [2];
1246 param_types [0] = ParamType1;
1247 param_types [1] = ParamType2;
1249 return LLVMFunctionType (ReturnType, param_types, 2, IsVarArg);
1253 * LLVMFunctionType3:
1255 * Create an LLVM function type from the arguments.
1257 static G_GNUC_UNUSED LLVMTypeRef
1258 LLVMFunctionType3(LLVMTypeRef ReturnType,
1259 LLVMTypeRef ParamType1,
1260 LLVMTypeRef ParamType2,
1261 LLVMTypeRef ParamType3,
1264 LLVMTypeRef param_types [3];
1266 param_types [0] = ParamType1;
1267 param_types [1] = ParamType2;
1268 param_types [2] = ParamType3;
1270 return LLVMFunctionType (ReturnType, param_types, 3, IsVarArg);
1276 * Create an LLVM builder and remember it so it can be freed later.
1278 static LLVMBuilderRef
1279 create_builder (EmitContext *ctx)
1281 LLVMBuilderRef builder = LLVMCreateBuilder ();
1283 ctx->builders = g_slist_prepend_mempool (ctx->cfg->mempool, ctx->builders, builder);
1289 get_plt_entry (EmitContext *ctx, LLVMTypeRef llvm_sig, MonoJumpInfoType type, gconstpointer data)
1291 char *callee_name = mono_aot_get_plt_symbol (type, data);
1292 LLVMValueRef callee;
1293 MonoJumpInfo *ji = NULL;
1298 if (ctx->cfg->compile_aot)
1299 /* Add a patch so referenced wrappers can be compiled in full aot mode */
1300 mono_add_patch_info (ctx->cfg, 0, type, data);
1303 callee = g_hash_table_lookup (ctx->lmodule->plt_entries, callee_name);
1305 callee = LLVMAddFunction (ctx->module, callee_name, llvm_sig);
1307 LLVMSetVisibility (callee, LLVMHiddenVisibility);
1309 g_hash_table_insert (ctx->lmodule->plt_entries, (char*)callee_name, callee);
1312 if (ctx->cfg->compile_aot) {
1313 ji = g_new0 (MonoJumpInfo, 1);
1315 ji->data.target = data;
1317 g_hash_table_insert (ctx->lmodule->plt_entries_ji, ji, callee);
1324 get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
1326 MonoMethodHeader *header = cfg->header;
1327 MonoExceptionClause *clause;
1331 if (bb->region != -1 && MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
1332 return (bb->region >> 8) - 1;
1335 for (i = 0; i < header->num_clauses; ++i) {
1336 clause = &header->clauses [i];
1338 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset) && clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
1346 set_metadata_flag (LLVMValueRef v, const char *flag_name)
1348 LLVMValueRef md_arg;
1351 md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1352 md_arg = LLVMMDString ("mono", 4);
1353 LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1357 set_invariant_load_flag (LLVMValueRef v)
1359 LLVMValueRef md_arg;
1361 const char *flag_name;
1363 // FIXME: Cache this
1364 flag_name = "invariant.load";
1365 md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1366 md_arg = LLVMMDString ("<index>", strlen ("<index>"));
1367 LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1373 * Emit an LLVM call or invoke instruction depending on whenever the call is inside
1377 emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LLVMValueRef callee, LLVMValueRef *args, int pindex)
1379 MonoCompile *cfg = ctx->cfg;
1381 LLVMBuilderRef builder = *builder_ref;
1384 clause_index = get_handler_clause (cfg, bb);
1386 if (clause_index != -1) {
1387 MonoMethodHeader *header = cfg->header;
1388 MonoExceptionClause *ec = &header->clauses [clause_index];
1389 MonoBasicBlock *tblock;
1390 LLVMBasicBlockRef ex_bb, noex_bb;
1393 * Have to use an invoke instead of a call, branching to the
1394 * handler bblock of the clause containing this bblock.
1397 g_assert (ec->flags == MONO_EXCEPTION_CLAUSE_NONE || ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY);
1399 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
1402 ctx->bblocks [tblock->block_num].invoke_target = TRUE;
1404 ex_bb = get_bb (ctx, tblock);
1406 noex_bb = gen_bb (ctx, "NOEX_BB");
1409 lcall = LLVMBuildInvoke (builder, callee, args, pindex, noex_bb, ex_bb, "");
1411 builder = ctx->builder = create_builder (ctx);
1412 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1414 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1416 lcall = LLVMBuildCall (builder, callee, args, pindex, "");
1417 ctx->builder = builder;
1420 *builder_ref = ctx->builder;
1426 emit_load (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting)
1428 const char *intrins_name;
1429 LLVMValueRef args [16], res;
1430 LLVMTypeRef addr_type;
1432 if (is_faulting && bb->region != -1) {
1434 * We handle loads which can fault by calling a mono specific intrinsic
1435 * using an invoke, so they are handled properly inside try blocks.
1436 * We can't use this outside clauses, since LLVM optimizes intrinsics which
1437 * are marked with IntrReadArgMem.
1441 intrins_name = "llvm.mono.load.i8.p0i8";
1444 intrins_name = "llvm.mono.load.i16.p0i16";
1447 intrins_name = "llvm.mono.load.i32.p0i32";
1450 intrins_name = "llvm.mono.load.i64.p0i64";
1453 g_assert_not_reached ();
1456 addr_type = LLVMTypeOf (addr);
1457 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0) || addr_type == LLVMPointerType (LLVMFloatType (), 0))
1458 addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1461 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1462 args [2] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1463 res = emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 3);
1465 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0))
1466 res = LLVMBuildBitCast (*builder_ref, res, LLVMDoubleType (), "");
1467 else if (addr_type == LLVMPointerType (LLVMFloatType (), 0))
1468 res = LLVMBuildBitCast (*builder_ref, res, LLVMFloatType (), "");
1475 * We emit volatile loads for loads which can fault, because otherwise
1476 * LLVM will generate invalid code when encountering a load from a
1479 res = mono_llvm_build_load (*builder_ref, addr, name, is_faulting);
1481 /* Mark it with a custom metadata */
1484 set_metadata_flag (res, "mono.faulting.load");
1492 emit_store (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting)
1494 const char *intrins_name;
1495 LLVMValueRef args [16];
1497 if (is_faulting && bb->region != -1) {
1500 intrins_name = "llvm.mono.store.i8.p0i8";
1503 intrins_name = "llvm.mono.store.i16.p0i16";
1506 intrins_name = "llvm.mono.store.i32.p0i32";
1509 intrins_name = "llvm.mono.store.i64.p0i64";
1512 g_assert_not_reached ();
1515 if (LLVMTypeOf (value) == LLVMDoubleType () || LLVMTypeOf (value) == LLVMFloatType ()) {
1516 value = LLVMBuildBitCast (*builder_ref, value, LLVMIntType (size * 8), "");
1517 addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1522 args [2] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1523 args [3] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1524 emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 4);
1526 LLVMBuildStore (*builder_ref, value, addr);
1531 * emit_cond_system_exception:
1533 * Emit code to throw the exception EXC_TYPE if the condition CMP is false.
1534 * Might set the ctx exception.
1537 emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp)
1539 LLVMBasicBlockRef ex_bb, noex_bb;
1540 LLVMBuilderRef builder;
1541 MonoClass *exc_class;
1542 LLVMValueRef args [2];
1544 ex_bb = gen_bb (ctx, "EX_BB");
1545 noex_bb = gen_bb (ctx, "NOEX_BB");
1547 LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb);
1549 exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type);
1550 g_assert (exc_class);
1552 /* Emit exception throwing code */
1553 builder = create_builder (ctx);
1554 LLVMPositionBuilderAtEnd (builder, ex_bb);
1556 if (!ctx->lmodule->throw_corlib_exception) {
1557 LLVMValueRef callee;
1559 const char *icall_name;
1561 MonoMethodSignature *throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 2);
1562 throw_sig->ret = &mono_get_void_class ()->byval_arg;
1563 throw_sig->params [0] = &mono_get_int32_class ()->byval_arg;
1564 icall_name = "llvm_throw_corlib_exception_abs_trampoline";
1565 /* This will become i8* */
1566 throw_sig->params [1] = &mono_get_byte_class ()->this_arg;
1567 sig = sig_to_llvm_sig (ctx, throw_sig);
1569 if (ctx->cfg->compile_aot) {
1570 callee = get_plt_entry (ctx, sig, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
1572 callee = LLVMAddFunction (ctx->module, "llvm_throw_corlib_exception_trampoline", sig_to_llvm_sig (ctx, throw_sig));
1575 * Differences between the LLVM/non-LLVM throw corlib exception trampoline:
1576 * - On x86, LLVM generated code doesn't push the arguments
1577 * - The trampoline takes the throw address as an arguments, not a pc offset.
1579 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (ctx->cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
1582 mono_memory_barrier ();
1583 ctx->lmodule->throw_corlib_exception = callee;
1586 if (IS_TARGET_X86 || IS_TARGET_AMD64)
1587 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token - MONO_TOKEN_TYPE_DEF, FALSE);
1589 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token, FALSE);
1592 * The LLVM mono branch contains changes so a block address can be passed as an
1593 * argument to a call.
1595 args [1] = LLVMBlockAddress (ctx->lmethod, ex_bb);
1596 emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1598 LLVMBuildUnreachable (builder);
1600 ctx->builder = create_builder (ctx);
1601 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1603 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1610 * emit_reg_to_vtype:
1612 * Emit code to store the vtype in the registers REGS to the address ADDRESS.
1615 emit_reg_to_vtype (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs)
1619 size = get_vtype_size (t);
1621 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1622 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1625 for (j = 0; j < 2; ++j) {
1626 LLVMValueRef index [2], addr;
1627 int part_size = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1628 LLVMTypeRef part_type;
1630 if (ainfo->pair_storage [j] == LLVMArgNone)
1633 part_type = LLVMIntType (part_size * 8);
1634 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1635 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1636 addr = LLVMBuildGEP (builder, address, index, 1, "");
1638 index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1639 index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1640 addr = LLVMBuildGEP (builder, address, index, 2, "");
1642 switch (ainfo->pair_storage [j]) {
1644 LLVMBuildStore (builder, convert (ctx, regs [j], part_type), LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (part_type, 0), ""));
1649 g_assert_not_reached ();
1652 size -= sizeof (gpointer);
1657 * emit_vtype_to_reg:
1659 * Emit code to load a vtype at address ADDRESS into registers. Store the registers
1660 * into REGS, and the number of registers into NREGS.
1663 emit_vtype_to_reg (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs, guint32 *nregs)
1668 size = get_vtype_size (t);
1670 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1671 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1674 for (j = 0; j < 2; ++j) {
1675 LLVMValueRef index [2], addr;
1676 int partsize = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1678 if (ainfo->pair_storage [j] == LLVMArgNone)
1681 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1682 index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1683 addr = LLVMBuildGEP (builder, address, index, 1, "");
1685 index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1686 index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1687 addr = LLVMBuildGEP (builder, address, index, 2, "");
1689 switch (ainfo->pair_storage [j]) {
1691 regs [pindex ++] = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (LLVMIntType (partsize * 8), 0), ""), ""), IntPtrType ());
1696 g_assert_not_reached ();
1698 size -= sizeof (gpointer);
1705 build_alloca_llvm_type (EmitContext *ctx, LLVMTypeRef t, int align)
1708 * Have to place all alloca's at the end of the entry bb, since otherwise they would
1709 * get executed every time control reaches them.
1711 LLVMPositionBuilder (ctx->alloca_builder, get_bb (ctx, ctx->cfg->bb_entry), ctx->last_alloca);
1713 ctx->last_alloca = mono_llvm_build_alloca (ctx->alloca_builder, t, NULL, align, "");
1714 return ctx->last_alloca;
1718 build_alloca (EmitContext *ctx, MonoType *t)
1720 MonoClass *k = mono_class_from_mono_type (t);
1723 if (MONO_CLASS_IS_SIMD (ctx->cfg, k))
1726 align = mono_class_min_align (k);
1728 /* Sometimes align is not a power of 2 */
1729 while (mono_is_power_of_two (align) == -1)
1732 return build_alloca_llvm_type (ctx, type_to_llvm_type (ctx, t), align);
1736 * Put the global into the 'llvm.used' array to prevent it from being optimized away.
1739 mark_as_used (MonoLLVMModule *lmodule, LLVMValueRef global)
1742 lmodule->used = g_ptr_array_sized_new (16);
1743 g_ptr_array_add (lmodule->used, global);
1747 emit_llvm_used (MonoLLVMModule *lmodule)
1749 LLVMModuleRef module = lmodule->module;
1750 LLVMTypeRef used_type;
1751 LLVMValueRef used, *used_elem;
1757 used_type = LLVMArrayType (LLVMPointerType (LLVMInt8Type (), 0), lmodule->used->len);
1758 used = LLVMAddGlobal (module, used_type, "llvm.used");
1759 used_elem = g_new0 (LLVMValueRef, lmodule->used->len);
1760 for (i = 0; i < lmodule->used->len; ++i)
1761 used_elem [i] = LLVMConstBitCast (g_ptr_array_index (lmodule->used, i), LLVMPointerType (LLVMInt8Type (), 0));
1762 LLVMSetInitializer (used, LLVMConstArray (LLVMPointerType (LLVMInt8Type (), 0), used_elem, lmodule->used->len));
1763 LLVMSetLinkage (used, LLVMAppendingLinkage);
1764 LLVMSetSection (used, "llvm.metadata");
1770 * Emit code to load/convert arguments.
1773 emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder)
1776 MonoCompile *cfg = ctx->cfg;
1777 MonoMethodSignature *sig = ctx->sig;
1778 LLVMCallInfo *linfo = ctx->linfo;
1781 ctx->alloca_builder = create_builder (ctx);
1784 * Handle indirect/volatile variables by allocating memory for them
1785 * using 'alloca', and storing their address in a temporary.
1787 for (i = 0; i < cfg->num_varinfo; ++i) {
1788 MonoInst *var = cfg->varinfo [i];
1791 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || mini_type_is_vtype (cfg, var->inst_vtype)) {
1792 vtype = type_to_llvm_type (ctx, var->inst_vtype);
1793 CHECK_FAILURE (ctx);
1794 /* Could be already created by an OP_VPHI */
1795 if (!ctx->addresses [var->dreg])
1796 ctx->addresses [var->dreg] = build_alloca (ctx, var->inst_vtype);
1797 ctx->vreg_cli_types [var->dreg] = var->inst_vtype;
1801 for (i = 0; i < sig->param_count; ++i) {
1802 LLVMArgInfo *ainfo = &linfo->args [i + sig->hasthis];
1803 int reg = cfg->args [i + sig->hasthis]->dreg;
1805 if (ainfo->storage == LLVMArgVtypeInReg) {
1806 LLVMValueRef regs [2];
1809 * Emit code to save the argument from the registers to
1810 * the real argument.
1812 pindex = ctx->pindexes [i];
1813 regs [0] = LLVMGetParam (ctx->lmethod, pindex);
1814 if (ainfo->pair_storage [1] != LLVMArgNone)
1815 regs [1] = LLVMGetParam (ctx->lmethod, pindex + 1);
1819 ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1821 emit_reg_to_vtype (ctx, builder, sig->params [i], ctx->addresses [reg], ainfo, regs);
1823 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1824 /* Treat these as normal values */
1825 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1827 } else if (ainfo->storage == LLVMArgVtypeByVal) {
1828 ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1830 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1831 /* Treat these as normal values */
1832 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1835 ctx->values [reg] = convert_full (ctx, ctx->values [reg], llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->params [i])), type_is_unsigned (ctx, sig->params [i]));
1840 emit_volatile_store (ctx, cfg->vret_addr->dreg);
1842 emit_volatile_store (ctx, cfg->args [0]->dreg);
1843 for (i = 0; i < sig->param_count; ++i)
1844 if (!mini_type_is_vtype (cfg, sig->params [i]))
1845 emit_volatile_store (ctx, cfg->args [i + sig->hasthis]->dreg);
1847 if (sig->hasthis && !cfg->rgctx_var && cfg->generic_sharing_context) {
1848 LLVMValueRef this_alloc;
1851 * The exception handling code needs the location where the this argument was
1852 * stored for gshared methods. We create a separate alloca to hold it, and mark it
1853 * with the "mono.this" custom metadata to tell llvm that it needs to save its
1854 * location into the LSDA.
1856 this_alloc = mono_llvm_build_alloca (builder, ThisType (), LLVMConstInt (LLVMInt32Type (), 1, FALSE), 0, "");
1857 /* This volatile store will keep the alloca alive */
1858 mono_llvm_build_store (builder, ctx->values [cfg->args [0]->dreg], this_alloc, TRUE);
1860 set_metadata_flag (this_alloc, "mono.this");
1863 if (cfg->rgctx_var) {
1864 LLVMValueRef rgctx_alloc, store;
1867 * We handle the rgctx arg similarly to the this pointer.
1869 g_assert (ctx->addresses [cfg->rgctx_var->dreg]);
1870 rgctx_alloc = ctx->addresses [cfg->rgctx_var->dreg];
1871 /* This volatile store will keep the alloca alive */
1872 store = mono_llvm_build_store (builder, convert (ctx, ctx->rgctx_arg, IntPtrType ()), rgctx_alloc, TRUE);
1874 set_metadata_flag (rgctx_alloc, "mono.this");
1878 * For finally clauses, create an indicator variable telling OP_ENDFINALLY whenever
1879 * it needs to continue normally, or return back to the exception handling system.
1881 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1882 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER))
1883 g_hash_table_insert (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)), bb);
1884 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER) && bb->in_scount == 0) {
1888 sprintf (name, "finally_ind_bb%d", bb->block_num);
1889 val = LLVMBuildAlloca (builder, LLVMInt32Type (), name);
1890 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), val);
1892 ctx->bblocks [bb->block_num].finally_ind = val;
1895 * Create a new bblock which CALL_HANDLER can branch to, because branching to the
1896 * LLVM bblock containing the call to llvm.eh.selector causes problems for the
1897 * LLVM optimizer passes.
1899 sprintf (name, "BB_%d_CALL_HANDLER_TARGET", bb->block_num);
1900 ctx->bblocks [bb->block_num].call_handler_target_bb = LLVMAppendBasicBlock (ctx->lmethod, name);
1908 /* Have to export this for AOT */
1910 mono_personality (void);
1913 mono_personality (void)
1916 g_assert_not_reached ();
1920 process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, MonoInst *ins)
1922 MonoCompile *cfg = ctx->cfg;
1923 LLVMModuleRef module = ctx->module;
1924 LLVMValueRef *values = ctx->values;
1925 LLVMValueRef *addresses = ctx->addresses;
1926 MonoCallInst *call = (MonoCallInst*)ins;
1927 MonoMethodSignature *sig = call->signature;
1928 LLVMValueRef callee = NULL, lcall;
1930 LLVMCallInfo *cinfo;
1934 LLVMTypeRef llvm_sig;
1936 gboolean virtual, calli;
1937 LLVMBuilderRef builder = *builder_ref;
1940 if (call->signature->call_convention != MONO_CALL_DEFAULT)
1941 LLVM_FAILURE (ctx, "non-default callconv");
1943 cinfo = call->cinfo;
1944 if (call->rgctx_arg_reg)
1945 cinfo->rgctx_arg = TRUE;
1946 if (call->imt_arg_reg)
1947 cinfo->imt_arg = TRUE;
1949 vretaddr = cinfo && cinfo->ret.storage == LLVMArgVtypeRetAddr;
1951 llvm_sig = sig_to_llvm_sig_full (ctx, sig, cinfo, &sinfo);
1952 CHECK_FAILURE (ctx);
1954 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);
1955 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);
1957 /* FIXME: Avoid creating duplicate methods */
1959 if (ins->flags & MONO_INST_HAS_METHOD) {
1963 if (cfg->compile_aot) {
1964 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_METHOD, call->method);
1966 LLVM_FAILURE (ctx, "can't encode patch");
1968 callee = LLVMAddFunction (module, "", llvm_sig);
1971 mono_create_jit_trampoline_in_domain (mono_domain_get (),
1973 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
1977 if (call->method && strstr (call->method->klass->name, "AsyncVoidMethodBuilder"))
1978 /* LLVM miscompiles async methods */
1979 LLVM_FAILURE (ctx, "#13734");
1982 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
1988 memset (&ji, 0, sizeof (ji));
1989 ji.type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
1990 ji.data.target = info->name;
1992 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
1994 if (cfg->compile_aot) {
1995 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_INTERNAL_METHOD, (char*)info->name);
1997 LLVM_FAILURE (ctx, "can't encode patch");
1999 callee = LLVMAddFunction (module, "", llvm_sig);
2000 target = (gpointer)mono_icall_get_wrapper (info);
2001 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2004 if (cfg->compile_aot) {
2006 if (cfg->abs_patches) {
2007 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2009 callee = get_plt_entry (ctx, llvm_sig, abs_ji->type, abs_ji->data.target);
2011 LLVM_FAILURE (ctx, "can't encode patch");
2015 LLVM_FAILURE (ctx, "aot");
2017 callee = LLVMAddFunction (module, "", llvm_sig);
2019 if (cfg->abs_patches) {
2020 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2023 * FIXME: Some trampolines might have
2024 * their own calling convention on some platforms.
2026 #ifndef TARGET_AMD64
2027 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)
2028 LLVM_FAILURE (ctx, "trampoline with own cconv");
2030 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, abs_ji, FALSE);
2031 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2035 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, (gpointer)call->fptr);
2041 int size = sizeof (gpointer);
2044 g_assert (ins->inst_offset % size == 0);
2045 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
2047 callee = convert (ctx, LLVMBuildLoad (builder, LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMPointerType (IntPtrType (), 0), 0)), &index, 1, ""), ""), LLVMPointerType (llvm_sig, 0));
2049 callee = convert (ctx, values [ins->sreg1], LLVMPointerType (llvm_sig, 0));
2051 if (ins->flags & MONO_INST_HAS_METHOD) {
2056 * Collect and convert arguments
2058 nargs = (sig->param_count * 2) + sig->hasthis + vretaddr + call->rgctx_reg + call->imt_arg_reg;
2059 len = sizeof (LLVMValueRef) * nargs;
2060 args = alloca (len);
2061 memset (args, 0, len);
2062 l = call->out_ireg_args;
2064 if (call->rgctx_arg_reg) {
2065 g_assert (values [call->rgctx_arg_reg]);
2066 g_assert (sinfo.rgctx_arg_pindex < nargs);
2068 * On ARM, the imt/rgctx argument is passed in a caller save register, but some of our trampolines etc. clobber it, leading to
2069 * problems is LLVM moves the arg assignment earlier. To work around this, save the argument into a stack slot and load
2070 * it using a volatile load.
2073 if (!ctx->imt_rgctx_loc)
2074 ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2075 LLVMBuildStore (builder, convert (ctx, ctx->values [call->rgctx_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2076 args [sinfo.rgctx_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE);
2078 args [sinfo.rgctx_arg_pindex] = convert (ctx, values [call->rgctx_arg_reg], ctx->lmodule->ptr_type);
2081 if (call->imt_arg_reg) {
2082 g_assert (values [call->imt_arg_reg]);
2083 g_assert (sinfo.imt_arg_pindex < nargs);
2085 if (!ctx->imt_rgctx_loc)
2086 ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2087 LLVMBuildStore (builder, convert (ctx, ctx->values [call->imt_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2088 args [sinfo.imt_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE);
2090 args [sinfo.imt_arg_pindex] = convert (ctx, values [call->imt_arg_reg], ctx->lmodule->ptr_type);
2095 if (!addresses [call->inst.dreg])
2096 addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2097 g_assert (sinfo.vret_arg_pindex < nargs);
2098 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2101 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2104 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i] : NULL;
2108 pindex = sinfo.this_arg_pindex;
2110 pindex = sinfo.pindexes [i - 1];
2112 pindex = sinfo.pindexes [i];
2115 regpair = (guint32)(gssize)(l->data);
2116 reg = regpair & 0xffffff;
2117 args [pindex] = values [reg];
2118 if (ainfo->storage == LLVMArgVtypeInReg) {
2120 LLVMValueRef regs [2];
2125 g_assert (addresses [reg]);
2127 emit_vtype_to_reg (ctx, builder, sig->params [i - sig->hasthis], addresses [reg], ainfo, regs, &nregs);
2128 for (j = 0; j < nregs; ++j)
2129 args [pindex ++] = regs [j];
2132 // FIXME: Get rid of the VMOVE
2133 } else if (ainfo->storage == LLVMArgVtypeByVal) {
2134 g_assert (addresses [reg]);
2135 args [pindex] = addresses [reg];
2137 g_assert (args [pindex]);
2138 if (i == 0 && sig->hasthis)
2139 args [pindex] = convert (ctx, args [pindex], ThisType ());
2141 args [pindex] = convert (ctx, args [pindex], type_to_llvm_arg_type (ctx, sig->params [i - sig->hasthis]));
2147 // FIXME: Align call sites
2153 lcall = emit_call (ctx, bb, &builder, callee, args, LLVMCountParamTypes (llvm_sig));
2156 * Modify cconv and parameter attributes to pass rgctx/imt correctly.
2158 #if defined(MONO_ARCH_IMT_REG) && defined(MONO_ARCH_RGCTX_REG)
2159 g_assert (MONO_ARCH_IMT_REG == MONO_ARCH_RGCTX_REG);
2161 /* The two can't be used together, so use only one LLVM calling conv to pass them */
2162 g_assert (!(call->rgctx_arg_reg && call->imt_arg_reg));
2164 LLVMSetInstructionCallConv (lcall, LLVMMono1CallConv);
2166 if (call->rgctx_arg_reg)
2167 LLVMAddInstrAttribute (lcall, 1 + sinfo.rgctx_arg_pindex, LLVMInRegAttribute);
2168 if (call->imt_arg_reg)
2169 LLVMAddInstrAttribute (lcall, 1 + sinfo.imt_arg_pindex, LLVMInRegAttribute);
2171 /* Add byval attributes if needed */
2172 for (i = 0; i < sig->param_count; ++i) {
2173 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i + sig->hasthis] : NULL;
2175 if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
2176 LLVMAddInstrAttribute (lcall, 1 + sinfo.pindexes [i], LLVMByValAttribute);
2181 * Convert the result
2183 if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
2184 LLVMValueRef regs [2];
2186 if (!addresses [ins->dreg])
2187 addresses [ins->dreg] = build_alloca (ctx, sig->ret);
2189 regs [0] = LLVMBuildExtractValue (builder, lcall, 0, "");
2190 if (cinfo->ret.pair_storage [1] != LLVMArgNone)
2191 regs [1] = LLVMBuildExtractValue (builder, lcall, 1, "");
2193 emit_reg_to_vtype (ctx, builder, sig->ret, addresses [ins->dreg], &cinfo->ret, regs);
2194 } else if (sig->ret->type != MONO_TYPE_VOID && !vretaddr) {
2195 /* If the method returns an unsigned value, need to zext it */
2197 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));
2200 *builder_ref = ctx->builder;
2202 g_free (sinfo.pindexes);
2210 process_bb (EmitContext *ctx, MonoBasicBlock *bb)
2212 MonoCompile *cfg = ctx->cfg;
2213 MonoMethodSignature *sig = ctx->sig;
2214 LLVMValueRef method = ctx->lmethod;
2215 LLVMValueRef *values = ctx->values;
2216 LLVMValueRef *addresses = ctx->addresses;
2218 LLVMCallInfo *linfo = ctx->linfo;
2219 LLVMModuleRef module = ctx->module;
2220 BBInfo *bblocks = ctx->bblocks;
2222 LLVMBasicBlockRef cbb;
2223 LLVMBuilderRef builder, starting_builder;
2224 gboolean has_terminator;
2226 LLVMValueRef lhs, rhs;
2229 cbb = get_bb (ctx, bb);
2230 builder = create_builder (ctx);
2231 ctx->builder = builder;
2232 LLVMPositionBuilderAtEnd (builder, cbb);
2234 if (bb == cfg->bb_entry)
2235 emit_entry_bb (ctx, builder);
2236 CHECK_FAILURE (ctx);
2238 if (bb->flags & BB_EXCEPTION_HANDLER) {
2240 LLVMValueRef personality;
2241 LLVMBasicBlockRef target_bb;
2243 static gint32 mapping_inited;
2244 static int ti_generator;
2247 LLVMValueRef type_info;
2250 if (!bblocks [bb->block_num].invoke_target) {
2252 * LLVM asserts if llvm.eh.selector is called from a bblock which
2253 * doesn't have an invoke pointing at it.
2254 * Update: LLVM no longer asserts, but some tests in exceptions.exe now fail.
2256 LLVM_FAILURE (ctx, "handler without invokes");
2259 // <resultval> = landingpad <somety> personality <type> <pers_fn> <clause>+
2261 if (cfg->compile_aot) {
2262 /* Use a dummy personality function */
2263 personality = LLVMGetNamedFunction (module, "mono_aot_personality");
2264 g_assert (personality);
2266 personality = LLVMGetNamedFunction (module, "mono_personality");
2267 if (InterlockedCompareExchange (&mapping_inited, 1, 0) == 0)
2268 LLVMAddGlobalMapping (ctx->lmodule->ee, personality, mono_personality);
2271 i8ptr = LLVMPointerType (LLVMInt8Type (), 0);
2273 clause_index = (mono_get_block_region_notry (cfg, bb->region) >> 8) - 1;
2276 * Create the type info
2278 sprintf (ti_name, "type_info_%d", ti_generator);
2281 if (cfg->compile_aot) {
2282 /* decode_eh_frame () in aot-runtime.c will decode this */
2283 type_info = LLVMAddGlobal (module, LLVMInt32Type (), ti_name);
2284 LLVMSetInitializer (type_info, LLVMConstInt (LLVMInt32Type (), clause_index, FALSE));
2287 * These symbols are not really used, the clause_index is embedded into the EH tables generated by DwarfMonoException in LLVM.
2289 LLVMSetLinkage (type_info, LLVMInternalLinkage);
2292 * Enabling this causes llc to crash:
2293 * http://llvm.org/bugs/show_bug.cgi?id=6102
2295 //LLVM_FAILURE (ctx, "aot+clauses");
2297 // test_0_invalid_unbox_arrays () fails
2298 LLVM_FAILURE (ctx, "aot+clauses");
2302 * After the cfg mempool is freed, the type info will point to stale memory,
2303 * but this is not a problem, since we decode it once in exception_cb during
2306 ti = mono_mempool_alloc (cfg->mempool, sizeof (gint32));
2307 *(gint32*)ti = clause_index;
2309 type_info = LLVMAddGlobal (module, i8ptr, ti_name);
2311 LLVMAddGlobalMapping (ctx->lmodule->ee, type_info, ti);
2315 LLVMTypeRef members [2], ret_type;
2316 LLVMValueRef landing_pad;
2318 members [0] = i8ptr;
2319 members [1] = LLVMInt32Type ();
2320 ret_type = LLVMStructType (members, 2, FALSE);
2322 landing_pad = LLVMBuildLandingPad (builder, ret_type, personality, 1, "");
2323 LLVMAddClause (landing_pad, type_info);
2325 /* Store the exception into the exvar */
2326 if (bb->in_scount == 1) {
2327 g_assert (bb->in_scount == 1);
2328 exvar = bb->in_stack [0];
2330 // FIXME: This is shared with filter clauses ?
2331 g_assert (!values [exvar->dreg]);
2333 values [exvar->dreg] = LLVMBuildExtractValue (builder, landing_pad, 0, "ex_obj");
2334 emit_volatile_store (ctx, exvar->dreg);
2338 /* Start a new bblock which CALL_HANDLER can branch to */
2339 target_bb = bblocks [bb->block_num].call_handler_target_bb;
2341 LLVMBuildBr (builder, target_bb);
2343 ctx->builder = builder = create_builder (ctx);
2344 LLVMPositionBuilderAtEnd (ctx->builder, target_bb);
2346 ctx->bblocks [bb->block_num].end_bblock = target_bb;
2350 has_terminator = FALSE;
2351 starting_builder = builder;
2352 for (ins = bb->code; ins; ins = ins->next) {
2353 const char *spec = LLVM_INS_INFO (ins->opcode);
2355 char dname_buf [128];
2357 emit_dbg_loc (ctx, builder, ins->cil_code);
2360 if (nins > 5000 && builder == starting_builder) {
2361 /* some steps in llc are non-linear in the size of basic blocks, see #5714 */
2362 LLVM_FAILURE (ctx, "basic block too long");
2366 /* There could be instructions after a terminator, skip them */
2369 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins)) {
2370 sprintf (dname_buf, "t%d", ins->dreg);
2374 if (spec [MONO_INST_SRC1] != ' ' && spec [MONO_INST_SRC1] != 'v') {
2375 MonoInst *var = get_vreg_to_inst (cfg, ins->sreg1);
2377 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2378 lhs = emit_volatile_load (ctx, ins->sreg1);
2380 /* It is ok for SETRET to have an uninitialized argument */
2381 if (!values [ins->sreg1] && ins->opcode != OP_SETRET)
2382 LLVM_FAILURE (ctx, "sreg1");
2383 lhs = values [ins->sreg1];
2389 if (spec [MONO_INST_SRC2] != ' ' && spec [MONO_INST_SRC2] != ' ') {
2390 MonoInst *var = get_vreg_to_inst (cfg, ins->sreg2);
2391 if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2392 rhs = emit_volatile_load (ctx, ins->sreg2);
2394 if (!values [ins->sreg2])
2395 LLVM_FAILURE (ctx, "sreg2");
2396 rhs = values [ins->sreg2];
2402 //mono_print_ins (ins);
2403 switch (ins->opcode) {
2406 case OP_LIVERANGE_START:
2407 case OP_LIVERANGE_END:
2410 values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE);
2413 #if SIZEOF_VOID_P == 4
2414 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2416 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), (gint64)ins->inst_c0, FALSE);
2420 values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), *(double*)ins->inst_p0);
2423 values [ins->dreg] = LLVMConstFPExt (LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0), LLVMDoubleType ());
2425 case OP_DUMMY_ICONST:
2426 values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
2428 case OP_DUMMY_I8CONST:
2429 values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
2431 case OP_DUMMY_R8CONST:
2432 values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), 0.0f);
2435 LLVMBuildBr (builder, get_bb (ctx, ins->inst_target_bb));
2436 has_terminator = TRUE;
2442 LLVMBasicBlockRef new_bb;
2443 LLVMBuilderRef new_builder;
2445 // The default branch is already handled
2446 // FIXME: Handle it here
2448 /* Start new bblock */
2449 sprintf (bb_name, "SWITCH_DEFAULT_BB%d", ctx->default_index ++);
2450 new_bb = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
2452 lhs = convert (ctx, lhs, LLVMInt32Type ());
2453 v = LLVMBuildSwitch (builder, lhs, new_bb, GPOINTER_TO_UINT (ins->klass));
2454 for (i = 0; i < GPOINTER_TO_UINT (ins->klass); ++i) {
2455 MonoBasicBlock *target_bb = ins->inst_many_bb [i];
2457 LLVMAddCase (v, LLVMConstInt (LLVMInt32Type (), i, FALSE), get_bb (ctx, target_bb));
2460 new_builder = create_builder (ctx);
2461 LLVMPositionBuilderAtEnd (new_builder, new_bb);
2462 LLVMBuildUnreachable (new_builder);
2464 has_terminator = TRUE;
2465 g_assert (!ins->next);
2471 if (linfo->ret.storage == LLVMArgVtypeInReg) {
2472 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2473 LLVMValueRef part1, retval;
2476 size = get_vtype_size (sig->ret);
2478 g_assert (addresses [ins->sreg1]);
2480 g_assert (linfo->ret.pair_storage [0] == LLVMArgInIReg);
2481 g_assert (linfo->ret.pair_storage [1] == LLVMArgNone);
2483 part1 = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMIntType (size * 8), 0), ""), ""), IntPtrType ());
2485 retval = LLVMBuildInsertValue (builder, LLVMGetUndef (ret_type), part1, 0, "");
2487 LLVMBuildRet (builder, retval);
2491 if (linfo->ret.storage == LLVMArgVtypeRetAddr) {
2492 LLVMBuildRetVoid (builder);
2496 if (!lhs || ctx->is_dead [ins->sreg1]) {
2498 * The method did not set its return value, probably because it
2499 * ends with a throw.
2502 LLVMBuildRetVoid (builder);
2504 LLVMBuildRet (builder, LLVMConstNull (type_to_llvm_type (ctx, sig->ret)));
2506 LLVMBuildRet (builder, convert (ctx, lhs, type_to_llvm_type (ctx, sig->ret)));
2508 has_terminator = TRUE;
2514 case OP_ICOMPARE_IMM:
2515 case OP_LCOMPARE_IMM:
2516 case OP_COMPARE_IMM: {
2520 if (ins->next->opcode == OP_NOP)
2523 if (ins->next->opcode == OP_BR)
2524 /* The comparison result is not needed */
2527 rel = mono_opcode_to_cond (ins->next->opcode);
2529 if (ins->opcode == OP_ICOMPARE_IMM) {
2530 lhs = convert (ctx, lhs, LLVMInt32Type ());
2531 rhs = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2533 if (ins->opcode == OP_LCOMPARE_IMM) {
2534 lhs = convert (ctx, lhs, LLVMInt64Type ());
2535 rhs = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2537 if (ins->opcode == OP_LCOMPARE) {
2538 lhs = convert (ctx, lhs, LLVMInt64Type ());
2539 rhs = convert (ctx, rhs, LLVMInt64Type ());
2541 if (ins->opcode == OP_ICOMPARE) {
2542 lhs = convert (ctx, lhs, LLVMInt32Type ());
2543 rhs = convert (ctx, rhs, LLVMInt32Type ());
2547 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2548 rhs = convert (ctx, rhs, LLVMTypeOf (lhs));
2549 else if (LLVMGetTypeKind (LLVMTypeOf (rhs)) == LLVMPointerTypeKind)
2550 lhs = convert (ctx, lhs, LLVMTypeOf (rhs));
2553 /* We use COMPARE+SETcc/Bcc, llvm uses SETcc+br cond */
2554 if (ins->opcode == OP_FCOMPARE)
2555 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2556 else if (ins->opcode == OP_COMPARE_IMM) {
2557 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && ins->inst_imm == 0)
2558 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, LLVMConstNull (LLVMTypeOf (lhs)), "");
2560 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), "");
2561 } else if (ins->opcode == OP_LCOMPARE_IMM) {
2562 if (SIZEOF_REGISTER == 4 && COMPILE_LLVM (cfg)) {
2563 /* The immediate is encoded in two fields */
2564 guint64 l = ((guint64)(guint32)ins->inst_offset << 32) | ((guint32)ins->inst_imm);
2565 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), l, FALSE), "");
2567 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), ins->inst_imm, FALSE), "");
2570 else if (ins->opcode == OP_COMPARE) {
2571 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && LLVMTypeOf (lhs) == LLVMTypeOf (rhs))
2572 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2574 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), convert (ctx, rhs, IntPtrType ()), "");
2576 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2578 if (MONO_IS_COND_BRANCH_OP (ins->next)) {
2579 if (ins->next->inst_true_bb == ins->next->inst_false_bb) {
2581 * If the target bb contains PHI instructions, LLVM requires
2582 * two PHI entries for this bblock, while we only generate one.
2583 * So convert this to an unconditional bblock. (bxc #171).
2585 LLVMBuildBr (builder, get_bb (ctx, ins->next->inst_true_bb));
2587 LLVMBuildCondBr (builder, cmp, get_bb (ctx, ins->next->inst_true_bb), get_bb (ctx, ins->next->inst_false_bb));
2589 has_terminator = TRUE;
2590 } else if (MONO_IS_SETCC (ins->next)) {
2591 sprintf (dname_buf, "t%d", ins->next->dreg);
2593 values [ins->next->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2595 /* Add stores for volatile variables */
2596 emit_volatile_store (ctx, ins->next->dreg);
2597 } else if (MONO_IS_COND_EXC (ins->next)) {
2598 emit_cond_system_exception (ctx, bb, ins->next->inst_p1, cmp);
2599 CHECK_FAILURE (ctx);
2600 builder = ctx->builder;
2602 LLVM_FAILURE (ctx, "next");
2616 rel = mono_opcode_to_cond (ins->opcode);
2618 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2619 values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2627 gboolean empty = TRUE;
2629 /* Check that all input bblocks really branch to us */
2630 for (i = 0; i < bb->in_count; ++i) {
2631 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_NOT_REACHED)
2632 ins->inst_phi_args [i + 1] = -1;
2638 /* LLVM doesn't like phi instructions with zero operands */
2639 ctx->is_dead [ins->dreg] = TRUE;
2643 /* Created earlier, insert it now */
2644 LLVMInsertIntoBuilder (builder, values [ins->dreg]);
2646 for (i = 0; i < ins->inst_phi_args [0]; i++) {
2647 int sreg1 = ins->inst_phi_args [i + 1];
2651 * Count the number of times the incoming bblock branches to us,
2652 * since llvm requires a separate entry for each.
2654 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_SWITCH) {
2655 MonoInst *switch_ins = bb->in_bb [i]->last_ins;
2658 for (j = 0; j < GPOINTER_TO_UINT (switch_ins->klass); ++j) {
2659 if (switch_ins->inst_many_bb [j] == bb)
2666 /* Remember for later */
2667 for (j = 0; j < count; ++j) {
2668 PhiNode *node = mono_mempool_alloc0 (ctx->mempool, sizeof (PhiNode));
2671 node->in_bb = bb->in_bb [i];
2673 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);
2683 values [ins->dreg] = lhs;
2686 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
2689 values [ins->dreg] = lhs;
2691 if (var && var->klass->byval_arg.type == MONO_TYPE_R4) {
2693 * This is added by the spilling pass in case of the JIT,
2694 * but we have to do it ourselves.
2696 values [ins->dreg] = convert (ctx, values [ins->dreg], LLVMFloatType ());
2730 lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2731 rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2733 switch (ins->opcode) {
2736 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, dname);
2740 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, dname);
2744 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, dname);
2748 values [ins->dreg] = LLVMBuildSRem (builder, lhs, rhs, dname);
2752 values [ins->dreg] = LLVMBuildURem (builder, lhs, rhs, dname);
2756 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, rhs, dname);
2760 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, rhs, dname);
2763 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
2767 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, dname);
2771 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, dname);
2775 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, dname);
2779 values [ins->dreg] = LLVMBuildShl (builder, lhs, rhs, dname);
2783 values [ins->dreg] = LLVMBuildAShr (builder, lhs, rhs, dname);
2787 values [ins->dreg] = LLVMBuildLShr (builder, lhs, rhs, dname);
2791 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
2794 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
2797 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
2801 g_assert_not_reached ();
2808 case OP_IREM_UN_IMM:
2810 case OP_IDIV_UN_IMM:
2816 case OP_ISHR_UN_IMM:
2825 case OP_LSHR_UN_IMM:
2831 case OP_SHR_UN_IMM: {
2834 if (spec [MONO_INST_SRC1] == 'l') {
2835 imm = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2837 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2840 #if SIZEOF_VOID_P == 4
2841 if (ins->opcode == OP_LSHL_IMM || ins->opcode == OP_LSHR_IMM || ins->opcode == OP_LSHR_UN_IMM)
2842 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2845 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2846 lhs = convert (ctx, lhs, IntPtrType ());
2847 imm = convert (ctx, imm, LLVMTypeOf (lhs));
2848 switch (ins->opcode) {
2852 values [ins->dreg] = LLVMBuildAdd (builder, lhs, imm, dname);
2856 values [ins->dreg] = LLVMBuildSub (builder, lhs, imm, dname);
2860 values [ins->dreg] = LLVMBuildMul (builder, lhs, imm, dname);
2864 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, imm, dname);
2866 case OP_IDIV_UN_IMM:
2867 case OP_LDIV_UN_IMM:
2868 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, imm, dname);
2872 values [ins->dreg] = LLVMBuildSRem (builder, lhs, imm, dname);
2874 case OP_IREM_UN_IMM:
2875 values [ins->dreg] = LLVMBuildURem (builder, lhs, imm, dname);
2880 values [ins->dreg] = LLVMBuildAnd (builder, lhs, imm, dname);
2884 values [ins->dreg] = LLVMBuildOr (builder, lhs, imm, dname);
2888 values [ins->dreg] = LLVMBuildXor (builder, lhs, imm, dname);
2893 values [ins->dreg] = LLVMBuildShl (builder, lhs, imm, dname);
2898 values [ins->dreg] = LLVMBuildAShr (builder, lhs, imm, dname);
2900 case OP_ISHR_UN_IMM:
2901 /* This is used to implement conv.u4, so the lhs could be an i8 */
2902 lhs = convert (ctx, lhs, LLVMInt32Type ());
2903 imm = convert (ctx, imm, LLVMInt32Type ());
2904 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
2906 case OP_LSHR_UN_IMM:
2908 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
2911 g_assert_not_reached ();
2916 values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
2919 values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt64Type (), 0, FALSE), lhs, dname);
2922 lhs = convert (ctx, lhs, LLVMDoubleType ());
2923 values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMDoubleType (), 0.0), lhs, dname);
2926 guint32 v = 0xffffffff;
2927 values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt32Type (), v, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
2931 guint64 v = 0xffffffffffffffffLL;
2932 values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt64Type (), v, FALSE), lhs, dname);
2935 #if defined(TARGET_X86) || defined(TARGET_AMD64)
2937 LLVMValueRef v1, v2;
2939 v1 = LLVMBuildMul (builder, convert (ctx, rhs, IntPtrType ()), LLVMConstInt (IntPtrType (), (1 << ins->backend.shift_amount), FALSE), "");
2940 v2 = LLVMBuildAdd (builder, convert (ctx, lhs, IntPtrType ()), v1, "");
2941 values [ins->dreg] = LLVMBuildAdd (builder, v2, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), dname);
2946 case OP_ICONV_TO_I1:
2947 case OP_ICONV_TO_I2:
2948 case OP_ICONV_TO_I4:
2949 case OP_ICONV_TO_U1:
2950 case OP_ICONV_TO_U2:
2951 case OP_ICONV_TO_U4:
2952 case OP_LCONV_TO_I1:
2953 case OP_LCONV_TO_I2:
2954 case OP_LCONV_TO_U1:
2955 case OP_LCONV_TO_U2:
2956 case OP_LCONV_TO_U4: {
2959 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);
2961 /* Have to do two casts since our vregs have type int */
2962 v = LLVMBuildTrunc (builder, lhs, op_to_llvm_type (ins->opcode), "");
2964 values [ins->dreg] = LLVMBuildSExt (builder, v, LLVMInt32Type (), dname);
2966 values [ins->dreg] = LLVMBuildZExt (builder, v, LLVMInt32Type (), dname);
2969 case OP_ICONV_TO_I8:
2970 values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
2972 case OP_ICONV_TO_U8:
2973 values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
2975 case OP_FCONV_TO_I4:
2976 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt32Type (), dname);
2978 case OP_FCONV_TO_I1:
2979 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
2981 case OP_FCONV_TO_U1:
2982 values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
2984 case OP_FCONV_TO_I2:
2985 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
2987 case OP_FCONV_TO_U2:
2988 values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
2990 case OP_FCONV_TO_I8:
2991 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt64Type (), dname);
2994 values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, IntPtrType (), dname);
2996 case OP_ICONV_TO_R8:
2997 case OP_LCONV_TO_R8:
2998 values [ins->dreg] = LLVMBuildSIToFP (builder, lhs, LLVMDoubleType (), dname);
3000 case OP_LCONV_TO_R_UN:
3001 values [ins->dreg] = LLVMBuildUIToFP (builder, lhs, LLVMDoubleType (), dname);
3003 #if SIZEOF_VOID_P == 4
3006 case OP_LCONV_TO_I4:
3007 values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3009 case OP_ICONV_TO_R4:
3010 case OP_LCONV_TO_R4:
3011 v = LLVMBuildSIToFP (builder, lhs, LLVMFloatType (), "");
3012 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3014 case OP_FCONV_TO_R4:
3015 v = LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), "");
3016 values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3019 values [ins->dreg] = LLVMBuildSExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3022 values [ins->dreg] = LLVMBuildZExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3025 values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3027 case OP_LOCALLOC_IMM: {
3030 guint32 size = ins->inst_imm;
3031 size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
3033 v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
3035 if (ins->flags & MONO_INST_INIT) {
3036 LLVMValueRef args [5];
3039 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3040 args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
3041 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3042 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3043 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3046 values [ins->dreg] = v;
3050 LLVMValueRef v, size;
3052 size = LLVMBuildAnd (builder, LLVMBuildAdd (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT - 1, FALSE), ""), LLVMConstInt (LLVMInt32Type (), ~ (MONO_ARCH_FRAME_ALIGNMENT - 1), FALSE), "");
3054 v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
3056 if (ins->flags & MONO_INST_INIT) {
3057 LLVMValueRef args [5];
3060 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3062 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3063 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3064 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3066 values [ins->dreg] = v;
3070 case OP_LOADI1_MEMBASE:
3071 case OP_LOADU1_MEMBASE:
3072 case OP_LOADI2_MEMBASE:
3073 case OP_LOADU2_MEMBASE:
3074 case OP_LOADI4_MEMBASE:
3075 case OP_LOADU4_MEMBASE:
3076 case OP_LOADI8_MEMBASE:
3077 case OP_LOADR4_MEMBASE:
3078 case OP_LOADR8_MEMBASE:
3079 case OP_LOAD_MEMBASE:
3087 LLVMValueRef base, index, addr;
3089 gboolean sext = FALSE, zext = FALSE;
3090 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3092 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3097 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)) {
3098 addr = LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE);
3103 if (ins->inst_offset == 0) {
3105 } else if (ins->inst_offset % size != 0) {
3106 /* Unaligned load */
3107 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3108 addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3110 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3111 addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (t, 0)), &index, 1, "");
3115 addr = convert (ctx, addr, LLVMPointerType (t, 0));
3117 values [ins->dreg] = emit_load (ctx, bb, &builder, size, addr, dname, is_volatile);
3119 if (!is_volatile && (ins->flags & MONO_INST_INVARIANT_LOAD)) {
3121 * These will signal LLVM that these loads do not alias any stores, and
3122 * they can't fail, allowing them to be hoisted out of loops.
3124 set_invariant_load_flag (values [ins->dreg]);
3125 set_metadata_flag (values [ins->dreg], "mono.nofail.load");
3129 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3131 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3132 else if (ins->opcode == OP_LOADR4_MEMBASE)
3133 values [ins->dreg] = LLVMBuildFPExt (builder, values [ins->dreg], LLVMDoubleType (), dname);
3137 case OP_STOREI1_MEMBASE_REG:
3138 case OP_STOREI2_MEMBASE_REG:
3139 case OP_STOREI4_MEMBASE_REG:
3140 case OP_STOREI8_MEMBASE_REG:
3141 case OP_STORER4_MEMBASE_REG:
3142 case OP_STORER8_MEMBASE_REG:
3143 case OP_STORE_MEMBASE_REG: {
3145 LLVMValueRef index, addr;
3147 gboolean sext = FALSE, zext = FALSE;
3148 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3150 if (!values [ins->inst_destbasereg])
3151 LLVM_FAILURE (ctx, "inst_destbasereg");
3153 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3155 if (ins->inst_offset % size != 0) {
3156 /* Unaligned store */
3157 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3158 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3160 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3161 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3163 emit_store (ctx, bb, &builder, size, convert (ctx, values [ins->sreg1], t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3167 case OP_STOREI1_MEMBASE_IMM:
3168 case OP_STOREI2_MEMBASE_IMM:
3169 case OP_STOREI4_MEMBASE_IMM:
3170 case OP_STOREI8_MEMBASE_IMM:
3171 case OP_STORE_MEMBASE_IMM: {
3173 LLVMValueRef index, addr;
3175 gboolean sext = FALSE, zext = FALSE;
3176 gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3178 t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3180 if (ins->inst_offset % size != 0) {
3181 /* Unaligned store */
3182 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3183 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3185 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3186 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3188 emit_store (ctx, bb, &builder, size, convert (ctx, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3193 emit_load (ctx, bb, &builder, sizeof (gpointer), convert (ctx, lhs, LLVMPointerType (IntPtrType (), 0)), "", TRUE);
3195 case OP_OUTARG_VTRETADDR:
3202 case OP_VOIDCALL_MEMBASE:
3203 case OP_CALL_MEMBASE:
3204 case OP_LCALL_MEMBASE:
3205 case OP_FCALL_MEMBASE:
3206 case OP_VCALL_MEMBASE:
3207 case OP_VOIDCALL_REG:
3211 case OP_VCALL_REG: {
3212 process_call (ctx, bb, &builder, ins);
3213 CHECK_FAILURE (ctx);
3218 LLVMValueRef indexes [2];
3220 LLVMValueRef got_entry_addr;
3223 * FIXME: Can't allocate from the cfg mempool since that is freed if
3224 * the LLVM compile fails.
3226 ji = g_new0 (MonoJumpInfo, 1);
3227 ji->type = (MonoJumpInfoType)ins->inst_i1;
3228 ji->data.target = ins->inst_p0;
3230 ji = mono_aot_patch_info_dup (ji);
3232 ji->next = cfg->patch_info;
3233 cfg->patch_info = ji;
3235 //mono_add_patch_info (cfg, 0, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3236 got_offset = mono_aot_get_got_offset (cfg->patch_info);
3238 indexes [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3239 indexes [1] = LLVMConstInt (LLVMInt32Type (), (gssize)got_offset, FALSE);
3240 got_entry_addr = LLVMBuildGEP (builder, ctx->lmodule->got_var, indexes, 2, "");
3242 values [ins->dreg] = LLVMBuildLoad (builder, got_entry_addr, dname);
3243 set_invariant_load_flag (values [ins->dreg]);
3246 case OP_NOT_REACHED:
3247 LLVMBuildUnreachable (builder);
3248 has_terminator = TRUE;
3249 g_assert (bb->block_num < cfg->max_block_num);
3250 ctx->unreachable [bb->block_num] = TRUE;
3251 /* Might have instructions after this */
3253 MonoInst *next = ins->next;
3255 * FIXME: If later code uses the regs defined by these instructions,
3256 * compilation will fail.
3258 MONO_DELETE_INS (bb, next);
3262 MonoInst *var = ins->inst_p0;
3264 values [ins->dreg] = addresses [var->dreg];
3268 LLVMValueRef args [1];
3270 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3271 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sin.f64"), args, 1, dname);
3275 LLVMValueRef args [1];
3277 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3278 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.cos.f64"), args, 1, dname);
3282 LLVMValueRef args [1];
3285 /* This no longer seems to happen */
3287 * LLVM optimizes sqrt(nan) into undefined in
3288 * lib/Analysis/ConstantFolding.cpp
3289 * Also, sqrt(NegativeInfinity) is optimized into 0.
3291 LLVM_FAILURE (ctx, "sqrt");
3293 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3294 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sqrt.f64"), args, 1, dname);
3298 LLVMValueRef args [1];
3300 args [0] = convert (ctx, lhs, LLVMDoubleType ());
3301 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "fabs"), args, 1, dname);
3315 lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3316 rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3318 switch (ins->opcode) {
3321 v = LLVMBuildICmp (builder, LLVMIntSLE, lhs, rhs, "");
3325 v = LLVMBuildICmp (builder, LLVMIntSGE, lhs, rhs, "");
3329 v = LLVMBuildICmp (builder, LLVMIntULE, lhs, rhs, "");
3333 v = LLVMBuildICmp (builder, LLVMIntUGE, lhs, rhs, "");
3336 g_assert_not_reached ();
3339 values [ins->dreg] = LLVMBuildSelect (builder, v, lhs, rhs, dname);
3342 case OP_ATOMIC_EXCHANGE_I4:
3343 case OP_ATOMIC_EXCHANGE_I8: {
3344 LLVMValueRef args [2];
3347 if (ins->opcode == OP_ATOMIC_EXCHANGE_I4)
3348 t = LLVMInt32Type ();
3350 t = LLVMInt64Type ();
3352 g_assert (ins->inst_offset == 0);
3354 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3355 args [1] = convert (ctx, rhs, t);
3357 values [ins->dreg] = mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_XCHG, args [0], args [1]);
3360 case OP_ATOMIC_ADD_I4:
3361 case OP_ATOMIC_ADD_I8: {
3362 LLVMValueRef args [2];
3365 if (ins->opcode == OP_ATOMIC_ADD_I4)
3366 t = LLVMInt32Type ();
3368 t = LLVMInt64Type ();
3370 g_assert (ins->inst_offset == 0);
3372 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3373 args [1] = convert (ctx, rhs, t);
3374 values [ins->dreg] = LLVMBuildAdd (builder, mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_ADD, args [0], args [1]), args [1], dname);
3377 case OP_ATOMIC_CAS_I4:
3378 case OP_ATOMIC_CAS_I8: {
3379 LLVMValueRef args [3], val;
3382 if (ins->opcode == OP_ATOMIC_CAS_I4)
3383 t = LLVMInt32Type ();
3385 t = LLVMInt64Type ();
3387 args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3389 args [1] = convert (ctx, values [ins->sreg3], t);
3391 args [2] = convert (ctx, values [ins->sreg2], t);
3392 val = mono_llvm_build_cmpxchg (builder, args [0], args [1], args [2]);
3393 #if LLVM_API_VERSION >= 1
3394 /* cmpxchg returns a pair */
3395 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, "");
3397 values [ins->dreg] = val;
3401 case OP_MEMORY_BARRIER: {
3402 mono_llvm_build_fence (builder);
3405 case OP_RELAXED_NOP: {
3406 #if defined(TARGET_AMD64) || defined(TARGET_X86)
3407 emit_call (ctx, bb, &builder, LLVMGetNamedFunction (ctx->module, "llvm.x86.sse2.pause"), NULL, 0);
3414 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(__linux__)
3416 // 257 == FS segment register
3417 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 257);
3419 // 256 == GS segment register
3420 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3423 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), ins->inst_offset, TRUE), ptrtype, ""), "");
3424 #elif defined(TARGET_AMD64) && defined(TARGET_OSX)
3425 /* See mono_amd64_emit_tls_get () */
3426 int offset = mono_amd64_get_tls_gs_offset () + (ins->inst_offset * 8);
3428 // 256 == GS segment register
3429 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3430 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), offset, TRUE), ptrtype, ""), "");
3432 LLVM_FAILURE (ctx, "opcode tls-get");
3437 case OP_TLS_GET_REG: {
3438 #if defined(TARGET_AMD64) && defined(TARGET_OSX)
3439 /* See emit_tls_get_reg () */
3440 // 256 == GS segment register
3441 LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3442 values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, convert (ctx, lhs, LLVMInt32Type ()), ptrtype, ""), "");
3444 LLVM_FAILURE (ctx, "opcode tls-get");
3453 case OP_IADD_OVF_UN:
3455 case OP_ISUB_OVF_UN:
3457 case OP_IMUL_OVF_UN:
3458 #if SIZEOF_VOID_P == 8
3460 case OP_LADD_OVF_UN:
3462 case OP_LSUB_OVF_UN:
3464 case OP_LMUL_OVF_UN:
3467 LLVMValueRef args [2], val, ovf, func;
3469 args [0] = convert (ctx, lhs, op_to_llvm_type (ins->opcode));
3470 args [1] = convert (ctx, rhs, op_to_llvm_type (ins->opcode));
3471 func = LLVMGetNamedFunction (module, ovf_op_to_intrins (ins->opcode));
3473 val = LLVMBuildCall (builder, func, args, 2, "");
3474 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, dname);
3475 ovf = LLVMBuildExtractValue (builder, val, 1, "");
3476 emit_cond_system_exception (ctx, bb, "OverflowException", ovf);
3477 CHECK_FAILURE (ctx);
3478 builder = ctx->builder;
3484 * We currently model them using arrays. Promotion to local vregs is
3485 * disabled for them in mono_handle_global_vregs () in the LLVM case,
3486 * so we always have an entry in cfg->varinfo for them.
3487 * FIXME: Is this needed ?
3490 MonoClass *klass = ins->klass;
3491 LLVMValueRef args [5];
3495 LLVM_FAILURE (ctx, "!klass");
3499 if (!addresses [ins->dreg])
3500 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3501 args [0] = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3502 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3503 args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3505 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3506 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3507 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3510 case OP_DUMMY_VZERO:
3513 case OP_STOREV_MEMBASE:
3514 case OP_LOADV_MEMBASE:
3516 MonoClass *klass = ins->klass;
3517 LLVMValueRef src = NULL, dst, args [5];
3518 gboolean done = FALSE;
3522 LLVM_FAILURE (ctx, "!klass");
3526 if (mini_is_gsharedvt_klass (cfg, klass)) {
3528 LLVM_FAILURE (ctx, "gsharedvt");
3532 switch (ins->opcode) {
3533 case OP_STOREV_MEMBASE:
3534 if (cfg->gen_write_barriers && klass->has_references && ins->inst_destbasereg != cfg->frame_reg &&
3535 LLVMGetInstructionOpcode (values [ins->inst_destbasereg]) != LLVMAlloca) {
3536 /* Decomposed earlier */
3537 g_assert_not_reached ();
3540 if (!addresses [ins->sreg1]) {
3542 g_assert (values [ins->sreg1]);
3543 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));
3544 LLVMBuildStore (builder, values [ins->sreg1], dst);
3547 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3548 dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3551 case OP_LOADV_MEMBASE:
3552 if (!addresses [ins->dreg])
3553 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3554 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3555 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3558 if (!addresses [ins->sreg1])
3559 addresses [ins->sreg1] = build_alloca (ctx, &klass->byval_arg);
3560 if (!addresses [ins->dreg])
3561 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3562 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3563 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3566 g_assert_not_reached ();
3568 CHECK_FAILURE (ctx);
3575 args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3576 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3578 args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3579 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3580 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
3583 case OP_LLVM_OUTARG_VT:
3584 if (!addresses [ins->sreg1]) {
3585 addresses [ins->sreg1] = build_alloca (ctx, &ins->klass->byval_arg);
3586 g_assert (values [ins->sreg1]);
3587 LLVMBuildStore (builder, values [ins->sreg1], addresses [ins->sreg1]);
3589 addresses [ins->dreg] = addresses [ins->sreg1];
3595 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3597 values [ins->dreg] = LLVMConstNull (type_to_llvm_type (ctx, &ins->klass->byval_arg));
3600 case OP_LOADX_MEMBASE: {
3601 LLVMTypeRef t = type_to_llvm_type (ctx, &ins->klass->byval_arg);
3604 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3605 values [ins->dreg] = mono_llvm_build_aligned_load (builder, src, "", FALSE, 1);
3608 case OP_STOREX_MEMBASE: {
3609 LLVMTypeRef t = LLVMTypeOf (values [ins->sreg1]);
3612 dest = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3613 mono_llvm_build_aligned_store (builder, values [ins->sreg1], dest, FALSE, 1);
3620 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, "");
3624 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, "");
3630 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, "");
3634 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, "");
3638 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, "");
3642 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, "");
3645 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, "");
3648 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, "");
3651 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, "");
3655 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, "");
3666 LLVMValueRef v = NULL;
3668 switch (ins->opcode) {
3673 t = LLVMVectorType (LLVMInt32Type (), 4);
3674 rt = LLVMVectorType (LLVMFloatType (), 4);
3680 t = LLVMVectorType (LLVMInt64Type (), 2);
3681 rt = LLVMVectorType (LLVMDoubleType (), 2);
3684 t = LLVMInt32Type ();
3685 rt = LLVMInt32Type ();
3686 g_assert_not_reached ();
3689 lhs = LLVMBuildBitCast (builder, lhs, t, "");
3690 rhs = LLVMBuildBitCast (builder, rhs, t, "");
3691 switch (ins->opcode) {
3694 v = LLVMBuildAnd (builder, lhs, rhs, "");
3698 v = LLVMBuildOr (builder, lhs, rhs, "");
3702 v = LLVMBuildXor (builder, lhs, rhs, "");
3706 v = LLVMBuildAnd (builder, rhs, LLVMBuildNot (builder, lhs, ""), "");
3709 values [ins->dreg] = LLVMBuildBitCast (builder, v, rt, "");
3733 case OP_PADDB_SAT_UN:
3734 case OP_PADDW_SAT_UN:
3735 case OP_PSUBB_SAT_UN:
3736 case OP_PSUBW_SAT_UN:
3744 case OP_PMULW_HIGH_UN: {
3745 LLVMValueRef args [2];
3750 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3757 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntEQ, lhs, rhs, ""), LLVMTypeOf (lhs), "");
3761 values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntSGT, lhs, rhs, ""), LLVMTypeOf (lhs), "");
3769 case OP_EXTRACTX_U2:
3771 case OP_EXTRACT_U1: {
3773 gboolean zext = FALSE;
3775 t = simd_op_to_llvm_type (ins->opcode);
3777 switch (ins->opcode) {
3785 case OP_EXTRACTX_U2:
3790 t = LLVMInt32Type ();
3791 g_assert_not_reached ();
3794 lhs = LLVMBuildBitCast (builder, lhs, t, "");
3795 values [ins->dreg] = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), "");
3797 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), "");
3806 case OP_EXPAND_R8: {
3807 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
3808 LLVMValueRef mask [16], v;
3810 for (i = 0; i < 16; ++i)
3811 mask [i] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3813 v = convert (ctx, values [ins->sreg1], LLVMGetElementType (t));
3815 values [ins->dreg] = LLVMBuildInsertElement (builder, LLVMConstNull (t), v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
3816 values [ins->dreg] = LLVMBuildShuffleVector (builder, values [ins->dreg], LLVMGetUndef (t), LLVMConstVector (mask, LLVMGetVectorSize (t)), "");
3821 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt8Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3824 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt16Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3827 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3830 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt64Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3833 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMFloatType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3836 values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMDoubleType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3847 case OP_EXTRACT_MASK:
3854 v = convert (ctx, values [ins->sreg1], simd_op_to_llvm_type (ins->opcode));
3856 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), &v, 1, dname);
3860 case OP_ICONV_TO_R8_RAW:
3861 /* Same as OP_ICONV_TO_R8 */
3862 values [ins->dreg] = convert (ctx, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType ());
3867 LLVMValueRef args [3];
3871 args [2] = LLVMConstInt (LLVMInt8Type (), ins->inst_c0, FALSE);
3873 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 3, dname);
3878 /* This is only used for implementing shifts by non-immediate */
3879 values [ins->dreg] = lhs;
3890 LLVMValueRef args [3];
3893 args [1] = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3895 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3906 case OP_PSHLQ_REG: {
3907 LLVMValueRef args [3];
3910 args [1] = values [ins->sreg2];
3912 values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3919 case OP_PSHUFLEW_LOW:
3920 case OP_PSHUFLEW_HIGH: {
3922 LLVMValueRef v1 = NULL, v2 = NULL, mask_values [16];
3923 int i, mask_size = 0;
3924 int imask = ins->inst_c0;
3926 /* Convert the x86 shuffle mask to LLVM's */
3927 switch (ins->opcode) {
3930 mask [0] = ((imask >> 0) & 3);
3931 mask [1] = ((imask >> 2) & 3);
3932 mask [2] = ((imask >> 4) & 3) + 4;
3933 mask [3] = ((imask >> 6) & 3) + 4;
3934 v1 = values [ins->sreg1];
3935 v2 = values [ins->sreg2];
3939 mask [0] = ((imask >> 0) & 1);
3940 mask [1] = ((imask >> 1) & 1) + 2;
3941 v1 = values [ins->sreg1];
3942 v2 = values [ins->sreg2];
3944 case OP_PSHUFLEW_LOW:
3946 mask [0] = ((imask >> 0) & 3);
3947 mask [1] = ((imask >> 2) & 3);
3948 mask [2] = ((imask >> 4) & 3);
3949 mask [3] = ((imask >> 6) & 3);
3954 v1 = values [ins->sreg1];
3955 v2 = LLVMGetUndef (LLVMTypeOf (v1));
3957 case OP_PSHUFLEW_HIGH:
3963 mask [4] = 4 + ((imask >> 0) & 3);
3964 mask [5] = 4 + ((imask >> 2) & 3);
3965 mask [6] = 4 + ((imask >> 4) & 3);
3966 mask [7] = 4 + ((imask >> 6) & 3);
3967 v1 = values [ins->sreg1];
3968 v2 = LLVMGetUndef (LLVMTypeOf (v1));
3972 mask [0] = ((imask >> 0) & 3);
3973 mask [1] = ((imask >> 2) & 3);
3974 mask [2] = ((imask >> 4) & 3);
3975 mask [3] = ((imask >> 6) & 3);
3976 v1 = values [ins->sreg1];
3977 v2 = LLVMGetUndef (LLVMTypeOf (v1));
3980 g_assert_not_reached ();
3982 for (i = 0; i < mask_size; ++i)
3983 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
3985 values [ins->dreg] =
3986 LLVMBuildShuffleVector (builder, v1, v2,
3987 LLVMConstVector (mask_values, mask_size), dname);
3991 case OP_UNPACK_LOWB:
3992 case OP_UNPACK_LOWW:
3993 case OP_UNPACK_LOWD:
3994 case OP_UNPACK_LOWQ:
3995 case OP_UNPACK_LOWPS:
3996 case OP_UNPACK_LOWPD:
3997 case OP_UNPACK_HIGHB:
3998 case OP_UNPACK_HIGHW:
3999 case OP_UNPACK_HIGHD:
4000 case OP_UNPACK_HIGHQ:
4001 case OP_UNPACK_HIGHPS:
4002 case OP_UNPACK_HIGHPD: {
4004 LLVMValueRef mask_values [16];
4005 int i, mask_size = 0;
4006 gboolean low = FALSE;
4008 switch (ins->opcode) {
4009 case OP_UNPACK_LOWB:
4013 case OP_UNPACK_LOWW:
4017 case OP_UNPACK_LOWD:
4018 case OP_UNPACK_LOWPS:
4022 case OP_UNPACK_LOWQ:
4023 case OP_UNPACK_LOWPD:
4027 case OP_UNPACK_HIGHB:
4030 case OP_UNPACK_HIGHW:
4033 case OP_UNPACK_HIGHD:
4034 case OP_UNPACK_HIGHPS:
4037 case OP_UNPACK_HIGHQ:
4038 case OP_UNPACK_HIGHPD:
4042 g_assert_not_reached ();
4046 for (i = 0; i < (mask_size / 2); ++i) {
4048 mask [(i * 2) + 1] = mask_size + i;
4051 for (i = 0; i < (mask_size / 2); ++i) {
4052 mask [(i * 2)] = (mask_size / 2) + i;
4053 mask [(i * 2) + 1] = mask_size + (mask_size / 2) + i;
4057 for (i = 0; i < mask_size; ++i)
4058 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4060 values [ins->dreg] =
4061 LLVMBuildShuffleVector (builder, values [ins->sreg1], values [ins->sreg2],
4062 LLVMConstVector (mask_values, mask_size), dname);
4067 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4068 LLVMValueRef v, val;
4070 v = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4071 val = LLVMConstNull (t);
4072 val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4073 val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 1, FALSE), dname);
4075 values [ins->dreg] = val;
4079 case OP_DUPPS_HIGH: {
4080 LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4081 LLVMValueRef v1, v2, val;
4084 if (ins->opcode == OP_DUPPS_LOW) {
4085 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4086 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4088 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4089 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4091 val = LLVMConstNull (t);
4092 val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4093 val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4094 val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4095 val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4097 values [ins->dreg] = val;
4107 * EXCEPTION HANDLING
4109 case OP_IMPLICIT_EXCEPTION:
4110 /* This marks a place where an implicit exception can happen */
4111 if (bb->region != -1)
4112 LLVM_FAILURE (ctx, "implicit-exception");
4116 MonoMethodSignature *throw_sig;
4117 LLVMValueRef callee, arg;
4118 gboolean rethrow = (ins->opcode == OP_RETHROW);
4119 const char *icall_name;
4121 callee = rethrow ? ctx->lmodule->rethrow : ctx->lmodule->throw;
4122 icall_name = rethrow ? "mono_arch_rethrow_exception" : "mono_arch_throw_exception";
4125 throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 1);
4126 throw_sig->ret = &mono_get_void_class ()->byval_arg;
4127 throw_sig->params [0] = &mono_get_object_class ()->byval_arg;
4128 if (cfg->compile_aot) {
4129 callee = get_plt_entry (ctx, sig_to_llvm_sig (ctx, throw_sig), MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
4131 callee = LLVMAddFunction (module, icall_name, sig_to_llvm_sig (ctx, throw_sig));
4135 * LLVM doesn't push the exception argument, so we need a different
4138 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, rethrow ? "llvm_rethrow_exception_trampoline" : "llvm_throw_exception_trampoline"));
4140 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
4144 mono_memory_barrier ();
4146 ctx->lmodule->rethrow = callee;
4148 ctx->lmodule->throw = callee;
4150 arg = convert (ctx, lhs, type_to_llvm_type (ctx, &mono_get_object_class ()->byval_arg));
4151 emit_call (ctx, bb, &builder, callee, &arg, 1);
4154 case OP_CALL_HANDLER: {
4156 * We don't 'call' handlers, but instead simply branch to them.
4157 * The code generated by ENDFINALLY will branch back to us.
4159 LLVMBasicBlockRef noex_bb;
4161 BBInfo *info = &bblocks [ins->inst_target_bb->block_num];
4163 bb_list = info->call_handler_return_bbs;
4166 * Set the indicator variable for the finally clause.
4168 lhs = info->finally_ind;
4170 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), g_slist_length (bb_list) + 1, FALSE), lhs);
4172 /* Branch to the finally clause */
4173 LLVMBuildBr (builder, info->call_handler_target_bb);
4175 noex_bb = gen_bb (ctx, "CALL_HANDLER_CONT_BB");
4176 info->call_handler_return_bbs = g_slist_append_mempool (cfg->mempool, info->call_handler_return_bbs, noex_bb);
4178 builder = ctx->builder = create_builder (ctx);
4179 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
4181 bblocks [bb->block_num].end_bblock = noex_bb;
4184 case OP_START_HANDLER: {
4187 case OP_ENDFINALLY: {
4188 LLVMBasicBlockRef resume_bb;
4189 MonoBasicBlock *handler_bb;
4190 LLVMValueRef val, switch_ins, callee;
4194 handler_bb = g_hash_table_lookup (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)));
4195 g_assert (handler_bb);
4196 info = &bblocks [handler_bb->block_num];
4197 lhs = info->finally_ind;
4200 bb_list = info->call_handler_return_bbs;
4202 resume_bb = gen_bb (ctx, "ENDFINALLY_RESUME_BB");
4204 /* Load the finally variable */
4205 val = LLVMBuildLoad (builder, lhs, "");
4207 /* Reset the variable */
4208 LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), lhs);
4210 /* Branch to either resume_bb, or to the bblocks in bb_list */
4211 switch_ins = LLVMBuildSwitch (builder, val, resume_bb, g_slist_length (bb_list));
4213 * The other targets are added at the end to handle OP_CALL_HANDLER
4214 * opcodes processed later.
4216 info->endfinally_switch_ins_list = g_slist_append_mempool (cfg->mempool, info->endfinally_switch_ins_list, switch_ins);
4218 builder = ctx->builder = create_builder (ctx);
4219 LLVMPositionBuilderAtEnd (ctx->builder, resume_bb);
4221 if (ctx->cfg->compile_aot) {
4222 callee = get_plt_entry (ctx, LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE), MONO_PATCH_INFO_INTERNAL_METHOD, "llvm_resume_unwind_trampoline");
4224 callee = LLVMGetNamedFunction (module, "llvm_resume_unwind_trampoline");
4226 LLVMBuildCall (builder, callee, NULL, 0, "");
4228 LLVMBuildUnreachable (builder);
4229 has_terminator = TRUE;
4235 sprintf (reason, "opcode %s", mono_inst_name (ins->opcode));
4236 LLVM_FAILURE (ctx, reason);
4241 /* Convert the value to the type required by phi nodes */
4242 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
4243 if (!values [ins->dreg])
4245 values [ins->dreg] = addresses [ins->dreg];
4247 values [ins->dreg] = convert (ctx, values [ins->dreg], ctx->vreg_types [ins->dreg]);
4250 /* Add stores for volatile variables */
4251 if (spec [MONO_INST_DEST] != ' ' && spec [MONO_INST_DEST] != 'v' && !MONO_IS_STORE_MEMBASE (ins))
4252 emit_volatile_store (ctx, ins->dreg);
4255 if (!has_terminator && bb->next_bb && (bb == cfg->bb_entry || bb->in_count > 0))
4256 LLVMBuildBr (builder, get_bb (ctx, bb->next_bb));
4258 if (bb == cfg->bb_exit && sig->ret->type == MONO_TYPE_VOID) {
4259 emit_dbg_loc (ctx, builder, cfg->header->code + cfg->header->code_size - 1);
4260 LLVMBuildRetVoid (builder);
4263 if (bb == cfg->bb_entry)
4264 ctx->last_alloca = LLVMGetLastInstruction (get_bb (ctx, cfg->bb_entry));
4273 * mono_llvm_check_method_supported:
4275 * Do some quick checks to decide whenever cfg->method can be compiled by LLVM, to avoid
4276 * compiling a method twice.
4279 mono_llvm_check_method_supported (MonoCompile *cfg)
4281 MonoMethodHeader *header = cfg->header;
4282 MonoExceptionClause *clause;
4285 if (cfg->method->save_lmf) {
4286 cfg->exception_message = g_strdup ("lmf");
4287 cfg->disable_llvm = TRUE;
4289 if (cfg->disable_llvm)
4293 for (i = 0; i < header->num_clauses; ++i) {
4294 clause = &header->clauses [i];
4296 if (i > 0 && clause->try_offset <= header->clauses [i - 1].handler_offset + header->clauses [i - 1].handler_len) {
4298 * FIXME: Some tests still fail with nested clauses.
4300 cfg->exception_message = g_strdup ("nested clauses");
4301 cfg->disable_llvm = TRUE;
4305 if (cfg->disable_llvm)
4310 if (cfg->method->dynamic) {
4311 cfg->exception_message = g_strdup ("dynamic.");
4312 cfg->disable_llvm = TRUE;
4314 if (cfg->disable_llvm)
4319 * mono_llvm_emit_method:
4321 * Emit LLVM IL from the mono IL, and compile it to native code using LLVM.
4324 mono_llvm_emit_method (MonoCompile *cfg)
4327 MonoMethodSignature *sig;
4329 LLVMTypeRef method_type;
4330 LLVMValueRef method = NULL;
4332 LLVMValueRef *values;
4333 int i, max_block_num, bb_index;
4334 gboolean last = FALSE;
4335 GPtrArray *phi_values;
4336 LLVMCallInfo *linfo;
4338 LLVMModuleRef module;
4340 GPtrArray *bblock_list;
4341 MonoMethodHeader *header;
4342 MonoExceptionClause *clause;
4346 /* The code below might acquire the loader lock, so use it for global locking */
4347 mono_loader_lock ();
4349 /* Used to communicate with the callbacks */
4350 mono_native_tls_set_value (current_cfg_tls_id, cfg);
4352 ctx = g_new0 (EmitContext, 1);
4354 ctx->mempool = cfg->mempool;
4357 * This maps vregs to the LLVM instruction defining them
4359 values = g_new0 (LLVMValueRef, cfg->next_vreg);
4361 * This maps vregs for volatile variables to the LLVM instruction defining their
4364 ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
4365 ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
4366 ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
4367 phi_values = g_ptr_array_sized_new (256);
4369 * This signals whenever the vreg was defined by a phi node with no input vars
4370 * (i.e. all its input bblocks end with NOT_REACHABLE).
4372 ctx->is_dead = g_new0 (gboolean, cfg->next_vreg);
4373 /* Whenever the bblock is unreachable */
4374 ctx->unreachable = g_new0 (gboolean, cfg->max_block_num);
4376 bblock_list = g_ptr_array_sized_new (256);
4378 ctx->values = values;
4379 ctx->region_to_handler = g_hash_table_new (NULL, NULL);
4381 if (cfg->compile_aot) {
4382 ctx->lmodule = &aot_module;
4383 method_name = mono_aot_get_method_name (cfg);
4384 cfg->llvm_method_name = g_strdup (method_name);
4386 init_jit_module (cfg->domain);
4387 ctx->lmodule = domain_jit_info (cfg->domain)->llvm_module;
4388 method_name = mono_method_full_name (cfg->method, TRUE);
4391 module = ctx->module = ctx->lmodule->module;
4394 LLVM_FAILURE (ctx, "gsharedvt");
4398 static int count = 0;
4401 if (g_getenv ("LLVM_COUNT")) {
4402 if (count == atoi (g_getenv ("LLVM_COUNT"))) {
4403 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4407 if (count > atoi (g_getenv ("LLVM_COUNT")))
4408 LLVM_FAILURE (ctx, "");
4413 sig = mono_method_signature (cfg->method);
4416 linfo = mono_arch_get_llvm_call_info (cfg, sig);
4418 CHECK_FAILURE (ctx);
4421 linfo->rgctx_arg = TRUE;
4422 method_type = sig_to_llvm_sig_full (ctx, sig, linfo, &sinfo);
4423 CHECK_FAILURE (ctx);
4426 * This maps parameter indexes in the original signature to the indexes in
4427 * the LLVM signature.
4429 ctx->pindexes = sinfo.pindexes;
4431 method = LLVMAddFunction (module, method_name, method_type);
4432 ctx->lmethod = method;
4434 LLVMSetFunctionCallConv (method, LLVMMono1CallConv);
4435 LLVMSetLinkage (method, LLVMPrivateLinkage);
4437 LLVMAddFunctionAttr (method, LLVMUWTable);
4439 if (cfg->compile_aot) {
4440 LLVMSetLinkage (method, LLVMInternalLinkage);
4441 #if LLVM_API_VERSION == 0
4442 /* This causes an assertion in later LLVM versions */
4443 LLVMSetVisibility (method, LLVMHiddenVisibility);
4446 LLVMSetLinkage (method, LLVMPrivateLinkage);
4449 if (cfg->method->save_lmf)
4450 LLVM_FAILURE (ctx, "lmf");
4452 if (sig->pinvoke && cfg->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
4453 LLVM_FAILURE (ctx, "pinvoke signature");
4455 header = cfg->header;
4456 for (i = 0; i < header->num_clauses; ++i) {
4457 clause = &header->clauses [i];
4458 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
4459 LLVM_FAILURE (ctx, "non-finally/catch clause.");
4462 if (linfo->rgctx_arg) {
4463 ctx->rgctx_arg = LLVMGetParam (method, sinfo.rgctx_arg_pindex);
4465 * We mark the rgctx parameter with the inreg attribute, which is mapped to
4466 * MONO_ARCH_RGCTX_REG in the Mono calling convention in llvm, i.e.
4467 * CC_X86_64_Mono in X86CallingConv.td.
4469 LLVMAddAttribute (ctx->rgctx_arg, LLVMInRegAttribute);
4470 LLVMSetValueName (ctx->rgctx_arg, "rgctx");
4472 if (cfg->vret_addr) {
4473 values [cfg->vret_addr->dreg] = LLVMGetParam (method, sinfo.vret_arg_pindex);
4474 LLVMSetValueName (values [cfg->vret_addr->dreg], "vret");
4477 values [cfg->args [0]->dreg] = LLVMGetParam (method, sinfo.this_arg_pindex);
4478 LLVMSetValueName (values [cfg->args [0]->dreg], "this");
4481 names = g_new (char *, sig->param_count);
4482 mono_method_get_param_names (cfg->method, (const char **) names);
4484 for (i = 0; i < sig->param_count; ++i) {
4487 values [cfg->args [i + sig->hasthis]->dreg] = LLVMGetParam (method, sinfo.pindexes [i]);
4488 if (names [i] && names [i][0] != '\0')
4489 name = g_strdup_printf ("arg_%s", names [i]);
4491 name = g_strdup_printf ("arg_%d", i);
4492 LLVMSetValueName (values [cfg->args [i + sig->hasthis]->dreg], name);
4494 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal)
4495 LLVMAddAttribute (LLVMGetParam (method, sinfo.pindexes [i]), LLVMByValAttribute);
4499 // See emit_dbg_info ()
4500 if (FALSE && cfg->compile_aot && mono_debug_enabled ()) {
4501 ctx->minfo = mono_debug_lookup_method (cfg->method);
4502 ctx->dbg_md = emit_dbg_subprogram (ctx, cfg, method, method_name);
4506 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4507 max_block_num = MAX (max_block_num, bb->block_num);
4508 ctx->bblocks = bblocks = g_new0 (BBInfo, max_block_num + 1);
4510 /* Add branches between non-consecutive bblocks */
4511 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4512 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4513 bb->next_bb != bb->last_ins->inst_false_bb) {
4515 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4516 inst->opcode = OP_BR;
4517 inst->inst_target_bb = bb->last_ins->inst_false_bb;
4518 mono_bblock_add_inst (bb, inst);
4523 * The INDIRECT flag added by OP_LDADDR inhibits optimizations, even if the LDADDR
4524 * was later optimized away, so clear these flags, and add them back for the still
4525 * present OP_LDADDR instructions.
4527 for (i = 0; i < cfg->next_vreg; ++i) {
4530 ins = get_vreg_to_inst (cfg, i);
4531 if (ins && ins != cfg->rgctx_var)
4532 ins->flags &= ~MONO_INST_INDIRECT;
4536 * Make a first pass over the code to precreate PHI nodes/set INDIRECT flags.
4538 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4540 LLVMBuilderRef builder;
4542 char dname_buf[128];
4544 builder = create_builder (ctx);
4546 for (ins = bb->code; ins; ins = ins->next) {
4547 switch (ins->opcode) {
4552 LLVMTypeRef phi_type = llvm_type_to_stack_type (type_to_llvm_type (ctx, &ins->klass->byval_arg));
4554 CHECK_FAILURE (ctx);
4556 if (ins->opcode == OP_VPHI) {
4557 /* Treat valuetype PHI nodes as operating on the address itself */
4558 g_assert (ins->klass);
4559 phi_type = LLVMPointerType (type_to_llvm_type (ctx, &ins->klass->byval_arg), 0);
4563 * Have to precreate these, as they can be referenced by
4564 * earlier instructions.
4566 sprintf (dname_buf, "t%d", ins->dreg);
4568 values [ins->dreg] = LLVMBuildPhi (builder, phi_type, dname);
4570 if (ins->opcode == OP_VPHI)
4571 ctx->addresses [ins->dreg] = values [ins->dreg];
4573 g_ptr_array_add (phi_values, values [ins->dreg]);
4576 * Set the expected type of the incoming arguments since these have
4577 * to have the same type.
4579 for (i = 0; i < ins->inst_phi_args [0]; i++) {
4580 int sreg1 = ins->inst_phi_args [i + 1];
4583 ctx->vreg_types [sreg1] = phi_type;
4588 ((MonoInst*)ins->inst_p0)->flags |= MONO_INST_INDIRECT;
4597 * Create an ordering for bblocks, use the depth first order first, then
4598 * put the exception handling bblocks last.
4600 for (bb_index = 0; bb_index < cfg->num_bblocks; ++bb_index) {
4601 bb = cfg->bblocks [bb_index];
4602 if (!(bb->region != -1 && !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))) {
4603 g_ptr_array_add (bblock_list, bb);
4604 bblocks [bb->block_num].added = TRUE;
4608 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4609 if (!bblocks [bb->block_num].added)
4610 g_ptr_array_add (bblock_list, bb);
4614 * Second pass: generate code.
4616 for (bb_index = 0; bb_index < bblock_list->len; ++bb_index) {
4617 bb = g_ptr_array_index (bblock_list, bb_index);
4619 if (!(bb == cfg->bb_entry || bb->in_count > 0))
4622 process_bb (ctx, bb);
4623 CHECK_FAILURE (ctx);
4626 /* Add incoming phi values */
4627 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4628 GSList *l, *ins_list;
4630 ins_list = bblocks [bb->block_num].phi_nodes;
4632 for (l = ins_list; l; l = l->next) {
4633 PhiNode *node = l->data;
4634 MonoInst *phi = node->phi;
4635 int sreg1 = node->sreg;
4636 LLVMBasicBlockRef in_bb;
4641 in_bb = get_end_bb (ctx, node->in_bb);
4643 if (ctx->unreachable [node->in_bb->block_num])
4646 if (!values [sreg1])
4647 /* Can happen with values in EH clauses */
4648 LLVM_FAILURE (ctx, "incoming phi sreg1");
4650 if (phi->opcode == OP_VPHI) {
4651 g_assert (LLVMTypeOf (ctx->addresses [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4652 LLVMAddIncoming (values [phi->dreg], &ctx->addresses [sreg1], &in_bb, 1);
4654 if (LLVMTypeOf (values [sreg1]) != LLVMTypeOf (values [phi->dreg]))
4656 LLVM_FAILURE (ctx, "incoming phi arg type mismatch");
4657 g_assert (LLVMTypeOf (values [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4658 LLVMAddIncoming (values [phi->dreg], &values [sreg1], &in_bb, 1);
4663 /* Create the SWITCH statements for ENDFINALLY instructions */
4664 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4665 BBInfo *info = &bblocks [bb->block_num];
4667 for (l = info->endfinally_switch_ins_list; l; l = l->next) {
4668 LLVMValueRef switch_ins = l->data;
4669 GSList *bb_list = info->call_handler_return_bbs;
4671 for (i = 0; i < g_slist_length (bb_list); ++i)
4672 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), i + 1, FALSE), g_slist_nth (bb_list, i)->data);
4676 if (cfg->verbose_level > 1)
4677 mono_llvm_dump_value (method);
4679 if (cfg->compile_aot)
4680 mark_as_used (ctx->lmodule, method);
4682 if (cfg->compile_aot) {
4683 LLVMValueRef md_args [16];
4684 LLVMValueRef md_node;
4687 method_index = mono_aot_get_method_index (cfg->orig_method);
4688 md_args [0] = LLVMMDString (method_name, strlen (method_name));
4689 md_args [1] = LLVMConstInt (LLVMInt32Type (), method_index, FALSE);
4690 md_node = LLVMMDNode (md_args, 2);
4691 LLVMAddNamedMetadataOperand (module, "mono.function_indexes", md_node);
4692 //LLVMSetMetadata (method, md_kind, LLVMMDNode (&md_arg, 1));
4695 if (cfg->compile_aot) {
4696 /* Don't generate native code, keep the LLVM IR */
4697 if (cfg->compile_aot && cfg->verbose_level)
4698 printf ("%s emitted as %s\n", mono_method_full_name (cfg->method, TRUE), method_name);
4700 //LLVMVerifyFunction(method, 0);
4702 mono_llvm_optimize_method (ctx->lmodule->mono_ee, method);
4704 if (cfg->verbose_level > 1)
4705 mono_llvm_dump_value (method);
4707 cfg->native_code = LLVMGetPointerToGlobal (ctx->lmodule->ee, method);
4709 /* Set by emit_cb */
4710 g_assert (cfg->code_len);
4712 /* FIXME: Free the LLVM IL for the function */
4715 if (ctx->lmodule->method_to_lmethod)
4716 g_hash_table_insert (ctx->lmodule->method_to_lmethod, cfg->method, method);
4723 /* Need to add unused phi nodes as they can be referenced by other values */
4724 LLVMBasicBlockRef phi_bb = LLVMAppendBasicBlock (method, "PHI_BB");
4725 LLVMBuilderRef builder;
4727 builder = create_builder (ctx);
4728 LLVMPositionBuilderAtEnd (builder, phi_bb);
4730 for (i = 0; i < phi_values->len; ++i) {
4731 LLVMValueRef v = g_ptr_array_index (phi_values, i);
4732 if (LLVMGetInstructionParent (v) == NULL)
4733 LLVMInsertIntoBuilder (builder, v);
4736 LLVMDeleteFunction (method);
4741 g_free (ctx->addresses);
4742 g_free (ctx->vreg_types);
4743 g_free (ctx->vreg_cli_types);
4744 g_free (ctx->pindexes);
4745 g_free (ctx->is_dead);
4746 g_free (ctx->unreachable);
4747 g_ptr_array_free (phi_values, TRUE);
4748 g_free (ctx->bblocks);
4749 g_hash_table_destroy (ctx->region_to_handler);
4750 g_free (method_name);
4751 g_ptr_array_free (bblock_list, TRUE);
4753 for (l = ctx->builders; l; l = l->next) {
4754 LLVMBuilderRef builder = l->data;
4755 LLVMDisposeBuilder (builder);
4760 mono_native_tls_set_value (current_cfg_tls_id, NULL);
4762 mono_loader_unlock ();
4766 * mono_llvm_emit_call:
4768 * Same as mono_arch_emit_call () for LLVM.
4771 mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
4774 MonoMethodSignature *sig;
4775 int i, n, stack_size;
4780 sig = call->signature;
4781 n = sig->param_count + sig->hasthis;
4783 call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4785 if (cfg->disable_llvm)
4788 if (sig->call_convention == MONO_CALL_VARARG) {
4789 cfg->exception_message = g_strdup ("varargs");
4790 cfg->disable_llvm = TRUE;
4793 for (i = 0; i < n; ++i) {
4796 ainfo = call->cinfo->args + i;
4798 in = call->args [i];
4800 /* Simply remember the arguments */
4801 switch (ainfo->storage) {
4803 case LLVMArgInFPReg: {
4804 MonoType *t = (sig->hasthis && i == 0) ? &mono_get_intptr_class ()->byval_arg : sig->params [i - sig->hasthis];
4807 opcode = mono_type_to_regmove (cfg, t);
4808 if (opcode == OP_FMOVE) {
4809 MONO_INST_NEW (cfg, ins, OP_FMOVE);
4810 ins->dreg = mono_alloc_freg (cfg);
4811 } else if (opcode == OP_LMOVE) {
4812 MONO_INST_NEW (cfg, ins, OP_LMOVE);
4813 ins->dreg = mono_alloc_lreg (cfg);
4815 MONO_INST_NEW (cfg, ins, OP_MOVE);
4816 ins->dreg = mono_alloc_ireg (cfg);
4818 ins->sreg1 = in->dreg;
4821 case LLVMArgVtypeByVal:
4822 case LLVMArgVtypeInReg:
4823 MONO_INST_NEW (cfg, ins, OP_LLVM_OUTARG_VT);
4824 ins->dreg = mono_alloc_ireg (cfg);
4825 ins->sreg1 = in->dreg;
4826 ins->klass = mono_class_from_mono_type (sig->params [i - sig->hasthis]);
4829 call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4830 cfg->exception_message = g_strdup ("ainfo->storage");
4831 cfg->disable_llvm = TRUE;
4835 if (!cfg->disable_llvm) {
4836 MONO_ADD_INS (cfg->cbb, ins);
4837 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, 0, FALSE);
4842 static unsigned char*
4843 alloc_cb (LLVMValueRef function, int size)
4847 cfg = mono_native_tls_get_value (current_cfg_tls_id);
4851 return mono_domain_code_reserve (cfg->domain, size);
4853 return mono_domain_code_reserve (mono_domain_get (), size);
4858 emitted_cb (LLVMValueRef function, void *start, void *end)
4862 cfg = mono_native_tls_get_value (current_cfg_tls_id);
4864 cfg->code_len = (guint8*)end - (guint8*)start;
4868 exception_cb (void *data)
4871 MonoJitExceptionInfo *ei;
4872 guint32 ei_len, i, j, nested_len, nindex;
4873 gpointer *type_info;
4874 int this_reg, this_offset;
4876 cfg = mono_native_tls_get_value (current_cfg_tls_id);
4880 * data points to a DWARF FDE structure, convert it to our unwind format and
4882 * An alternative would be to save it directly, and modify our unwinder to work
4885 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);
4886 if (cfg->verbose_level > 1)
4887 mono_print_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
4889 /* Count nested clauses */
4891 for (i = 0; i < ei_len; ++i) {
4892 for (j = 0; j < ei_len; ++j) {
4893 gint32 cindex1 = *(gint32*)type_info [i];
4894 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
4895 gint32 cindex2 = *(gint32*)type_info [j];
4896 MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
4898 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
4904 cfg->llvm_ex_info = mono_mempool_alloc0 (cfg->mempool, (ei_len + nested_len) * sizeof (MonoJitExceptionInfo));
4905 cfg->llvm_ex_info_len = ei_len + nested_len;
4906 memcpy (cfg->llvm_ex_info, ei, ei_len * sizeof (MonoJitExceptionInfo));
4907 /* Fill the rest of the information from the type info */
4908 for (i = 0; i < ei_len; ++i) {
4909 gint32 clause_index = *(gint32*)type_info [i];
4910 MonoExceptionClause *clause = &cfg->header->clauses [clause_index];
4912 cfg->llvm_ex_info [i].flags = clause->flags;
4913 cfg->llvm_ex_info [i].data.catch_class = clause->data.catch_class;
4917 * For nested clauses, the LLVM produced exception info associates the try interval with
4918 * the innermost handler, while mono expects it to be associated with all nesting clauses.
4920 /* FIXME: These should be order with the normal clauses */
4922 for (i = 0; i < ei_len; ++i) {
4923 for (j = 0; j < ei_len; ++j) {
4924 gint32 cindex1 = *(gint32*)type_info [i];
4925 MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
4926 gint32 cindex2 = *(gint32*)type_info [j];
4927 MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
4929 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
4931 * The try interval comes from the nested clause, everything else from the
4934 memcpy (&cfg->llvm_ex_info [nindex], &cfg->llvm_ex_info [j], sizeof (MonoJitExceptionInfo));
4935 cfg->llvm_ex_info [nindex].try_start = cfg->llvm_ex_info [i].try_start;
4936 cfg->llvm_ex_info [nindex].try_end = cfg->llvm_ex_info [i].try_end;
4941 g_assert (nindex == ei_len + nested_len);
4942 cfg->llvm_this_reg = this_reg;
4943 cfg->llvm_this_offset = this_offset;
4945 /* type_info [i] is cfg mempool allocated, no need to free it */
4952 dlsym_cb (const char *name, void **symbol)
4958 if (!strcmp (name, "__bzero")) {
4959 *symbol = (void*)bzero;
4961 current = mono_dl_open (NULL, 0, NULL);
4964 err = mono_dl_symbol (current, name, symbol);
4966 mono_dl_close (current);
4968 #ifdef MONO_ARCH_HAVE_CREATE_LLVM_NATIVE_THUNK
4969 *symbol = (char*)mono_arch_create_llvm_native_thunk (mono_domain_get (), (guint8*)(*symbol));
4975 AddFunc (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef *param_types, int nparams)
4977 LLVMAddFunction (module, name, LLVMFunctionType (ret_type, param_types, nparams, FALSE));
4981 AddFunc2 (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef param_type1, LLVMTypeRef param_type2)
4983 LLVMTypeRef param_types [4];
4985 param_types [0] = param_type1;
4986 param_types [1] = param_type2;
4988 AddFunc (module, name, ret_type, param_types, 2);
4992 add_intrinsics (LLVMModuleRef module)
4994 /* Emit declarations of instrinsics */
4996 * It would be nicer to emit only the intrinsics actually used, but LLVM's Module
4997 * type doesn't seem to do any locking.
5000 LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5002 memset_param_count = 5;
5003 memset_func_name = "llvm.memset.p0i8.i32";
5005 LLVMAddFunction (module, memset_func_name, LLVMFunctionType (LLVMVoidType (), memset_params, memset_param_count, FALSE));
5009 LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5011 memcpy_param_count = 5;
5012 memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
5014 LLVMAddFunction (module, memcpy_func_name, LLVMFunctionType (LLVMVoidType (), memcpy_params, memcpy_param_count, FALSE));
5018 LLVMTypeRef params [] = { LLVMDoubleType () };
5020 LLVMAddFunction (module, "llvm.sin.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5021 LLVMAddFunction (module, "llvm.cos.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5022 LLVMAddFunction (module, "llvm.sqrt.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5024 /* This isn't an intrinsic, instead llvm seems to special case it by name */
5025 LLVMAddFunction (module, "fabs", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5029 LLVMTypeRef ovf_res_i32 [] = { LLVMInt32Type (), LLVMInt1Type () };
5030 LLVMTypeRef ovf_params_i32 [] = { LLVMInt32Type (), LLVMInt32Type () };
5032 LLVMAddFunction (module, "llvm.sadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5033 LLVMAddFunction (module, "llvm.uadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5034 LLVMAddFunction (module, "llvm.ssub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5035 LLVMAddFunction (module, "llvm.usub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5036 LLVMAddFunction (module, "llvm.smul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5037 LLVMAddFunction (module, "llvm.umul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5041 LLVMTypeRef ovf_res_i64 [] = { LLVMInt64Type (), LLVMInt1Type () };
5042 LLVMTypeRef ovf_params_i64 [] = { LLVMInt64Type (), LLVMInt64Type () };
5044 LLVMAddFunction (module, "llvm.sadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5045 LLVMAddFunction (module, "llvm.uadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5046 LLVMAddFunction (module, "llvm.ssub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5047 LLVMAddFunction (module, "llvm.usub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5048 LLVMAddFunction (module, "llvm.smul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5049 LLVMAddFunction (module, "llvm.umul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5054 LLVMTypeRef arg_types [2];
5055 LLVMTypeRef ret_type;
5057 arg_types [0] = LLVMPointerType (LLVMInt8Type (), 0);
5058 arg_types [1] = LLVMPointerType (LLVMInt8Type (), 0);
5059 ret_type = LLVMInt32Type ();
5061 LLVMAddFunction (module, "mono_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5063 LLVMAddFunction (module, "llvm_resume_unwind_trampoline", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5066 /* SSE intrinsics */
5067 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5069 LLVMTypeRef ret_type, arg_types [16];
5072 ret_type = type_to_simd_type (MONO_TYPE_I4);
5073 arg_types [0] = ret_type;
5074 arg_types [1] = ret_type;
5075 AddFunc (module, "llvm.x86.sse41.pminud", ret_type, arg_types, 2);
5076 AddFunc (module, "llvm.x86.sse41.pmaxud", ret_type, arg_types, 2);
5078 ret_type = type_to_simd_type (MONO_TYPE_I2);
5079 arg_types [0] = ret_type;
5080 arg_types [1] = ret_type;
5081 AddFunc (module, "llvm.x86.sse41.pminuw", ret_type, arg_types, 2);
5082 AddFunc (module, "llvm.x86.sse2.pmins.w", ret_type, arg_types, 2);
5083 AddFunc (module, "llvm.x86.sse41.pmaxuw", ret_type, arg_types, 2);
5084 AddFunc (module, "llvm.x86.sse2.padds.w", ret_type, arg_types, 2);
5085 AddFunc (module, "llvm.x86.sse2.psubs.w", ret_type, arg_types, 2);
5086 AddFunc (module, "llvm.x86.sse2.paddus.w", ret_type, arg_types, 2);
5087 AddFunc (module, "llvm.x86.sse2.psubus.w", ret_type, arg_types, 2);
5088 AddFunc (module, "llvm.x86.sse2.pavg.w", ret_type, arg_types, 2);
5089 AddFunc (module, "llvm.x86.sse2.pmulh.w", ret_type, arg_types, 2);
5090 AddFunc (module, "llvm.x86.sse2.pmulhu.w", ret_type, arg_types, 2);
5092 ret_type = type_to_simd_type (MONO_TYPE_I1);
5093 arg_types [0] = ret_type;
5094 arg_types [1] = ret_type;
5095 AddFunc (module, "llvm.x86.sse2.pminu.b", ret_type, arg_types, 2);
5096 AddFunc (module, "llvm.x86.sse2.pmaxu.b", ret_type, arg_types, 2);
5097 AddFunc (module, "llvm.x86.sse2.padds.b", ret_type, arg_types, 2);
5098 AddFunc (module, "llvm.x86.sse2.psubs.b", ret_type, arg_types, 2);
5099 AddFunc (module, "llvm.x86.sse2.paddus.b", ret_type, arg_types, 2);
5100 AddFunc (module, "llvm.x86.sse2.psubus.b", ret_type, arg_types, 2);
5101 AddFunc (module, "llvm.x86.sse2.pavg.b", ret_type, arg_types, 2);
5103 ret_type = type_to_simd_type (MONO_TYPE_R8);
5104 arg_types [0] = ret_type;
5105 arg_types [1] = ret_type;
5106 AddFunc (module, "llvm.x86.sse2.min.pd", ret_type, arg_types, 2);
5107 AddFunc (module, "llvm.x86.sse2.max.pd", ret_type, arg_types, 2);
5108 AddFunc (module, "llvm.x86.sse3.hadd.pd", ret_type, arg_types, 2);
5109 AddFunc (module, "llvm.x86.sse3.hsub.pd", ret_type, arg_types, 2);
5110 AddFunc (module, "llvm.x86.sse3.addsub.pd", ret_type, arg_types, 2);
5112 ret_type = type_to_simd_type (MONO_TYPE_R4);
5113 arg_types [0] = ret_type;
5114 arg_types [1] = ret_type;
5115 AddFunc (module, "llvm.x86.sse.min.ps", ret_type, arg_types, 2);
5116 AddFunc (module, "llvm.x86.sse.max.ps", ret_type, arg_types, 2);
5117 AddFunc (module, "llvm.x86.sse3.hadd.ps", ret_type, arg_types, 2);
5118 AddFunc (module, "llvm.x86.sse3.hsub.ps", ret_type, arg_types, 2);
5119 AddFunc (module, "llvm.x86.sse3.addsub.ps", ret_type, arg_types, 2);
5122 ret_type = type_to_simd_type (MONO_TYPE_I1);
5123 arg_types [0] = type_to_simd_type (MONO_TYPE_I2);
5124 arg_types [1] = type_to_simd_type (MONO_TYPE_I2);
5125 AddFunc (module, "llvm.x86.sse2.packsswb.128", ret_type, arg_types, 2);
5126 AddFunc (module, "llvm.x86.sse2.packuswb.128", ret_type, arg_types, 2);
5127 ret_type = type_to_simd_type (MONO_TYPE_I2);
5128 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5129 arg_types [1] = type_to_simd_type (MONO_TYPE_I4);
5130 AddFunc (module, "llvm.x86.sse2.packssdw.128", ret_type, arg_types, 2);
5131 AddFunc (module, "llvm.x86.sse41.packusdw", ret_type, arg_types, 2);
5134 ret_type = type_to_simd_type (MONO_TYPE_R8);
5135 arg_types [0] = ret_type;
5136 arg_types [1] = ret_type;
5137 arg_types [2] = LLVMInt8Type ();
5138 AddFunc (module, "llvm.x86.sse2.cmp.pd", ret_type, arg_types, 3);
5139 ret_type = type_to_simd_type (MONO_TYPE_R4);
5140 arg_types [0] = ret_type;
5141 arg_types [1] = ret_type;
5142 arg_types [2] = LLVMInt8Type ();
5143 AddFunc (module, "llvm.x86.sse.cmp.ps", ret_type, arg_types, 3);
5145 /* Conversion ops */
5146 ret_type = type_to_simd_type (MONO_TYPE_R8);
5147 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5148 AddFunc (module, "llvm.x86.sse2.cvtdq2pd", ret_type, arg_types, 1);
5149 ret_type = type_to_simd_type (MONO_TYPE_R4);
5150 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5151 AddFunc (module, "llvm.x86.sse2.cvtdq2ps", ret_type, arg_types, 1);
5152 ret_type = type_to_simd_type (MONO_TYPE_I4);
5153 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5154 AddFunc (module, "llvm.x86.sse2.cvtpd2dq", ret_type, arg_types, 1);
5155 ret_type = type_to_simd_type (MONO_TYPE_I4);
5156 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5157 AddFunc (module, "llvm.x86.sse2.cvtps2dq", ret_type, arg_types, 1);
5158 ret_type = type_to_simd_type (MONO_TYPE_R4);
5159 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5160 AddFunc (module, "llvm.x86.sse2.cvtpd2ps", ret_type, arg_types, 1);
5161 ret_type = type_to_simd_type (MONO_TYPE_R8);
5162 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5163 AddFunc (module, "llvm.x86.sse2.cvtps2pd", ret_type, arg_types, 1);
5165 ret_type = type_to_simd_type (MONO_TYPE_I4);
5166 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5167 AddFunc (module, "llvm.x86.sse2.cvttpd2dq", ret_type, arg_types, 1);
5168 ret_type = type_to_simd_type (MONO_TYPE_I4);
5169 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5170 AddFunc (module, "llvm.x86.sse2.cvttps2dq", ret_type, arg_types, 1);
5173 ret_type = type_to_simd_type (MONO_TYPE_R8);
5174 arg_types [0] = ret_type;
5175 AddFunc (module, "llvm.x86.sse2.sqrt.pd", ret_type, arg_types, 1);
5176 ret_type = type_to_simd_type (MONO_TYPE_R4);
5177 arg_types [0] = ret_type;
5178 AddFunc (module, "llvm.x86.sse.sqrt.ps", ret_type, arg_types, 1);
5179 ret_type = type_to_simd_type (MONO_TYPE_R4);
5180 arg_types [0] = ret_type;
5181 AddFunc (module, "llvm.x86.sse.rsqrt.ps", ret_type, arg_types, 1);
5182 ret_type = type_to_simd_type (MONO_TYPE_R4);
5183 arg_types [0] = ret_type;
5184 AddFunc (module, "llvm.x86.sse.rcp.ps", ret_type, arg_types, 1);
5187 ret_type = type_to_simd_type (MONO_TYPE_I2);
5188 arg_types [0] = ret_type;
5189 arg_types [1] = LLVMInt32Type ();
5190 AddFunc (module, "llvm.x86.sse2.psrli.w", ret_type, arg_types, 2);
5191 AddFunc (module, "llvm.x86.sse2.psrai.w", ret_type, arg_types, 2);
5192 AddFunc (module, "llvm.x86.sse2.pslli.w", ret_type, arg_types, 2);
5193 ret_type = type_to_simd_type (MONO_TYPE_I4);
5194 arg_types [0] = ret_type;
5195 arg_types [1] = LLVMInt32Type ();
5196 AddFunc (module, "llvm.x86.sse2.psrli.d", ret_type, arg_types, 2);
5197 AddFunc (module, "llvm.x86.sse2.psrai.d", ret_type, arg_types, 2);
5198 AddFunc (module, "llvm.x86.sse2.pslli.d", ret_type, arg_types, 2);
5199 ret_type = type_to_simd_type (MONO_TYPE_I8);
5200 arg_types [0] = ret_type;
5201 arg_types [1] = LLVMInt32Type ();
5202 AddFunc (module, "llvm.x86.sse2.psrli.q", ret_type, arg_types, 2);
5203 AddFunc (module, "llvm.x86.sse2.pslli.q", ret_type, arg_types, 2);
5206 ret_type = LLVMInt32Type ();
5207 arg_types [0] = type_to_simd_type (MONO_TYPE_I1);
5208 AddFunc (module, "llvm.x86.sse2.pmovmskb.128", ret_type, arg_types, 1);
5211 AddFunc (module, "llvm.x86.sse2.pause", LLVMVoidType (), NULL, 0);
5214 /* Load/Store intrinsics */
5216 LLVMTypeRef arg_types [5];
5220 for (i = 1; i <= 8; i *= 2) {
5221 arg_types [0] = LLVMPointerType (LLVMIntType (i * 8), 0);
5222 arg_types [1] = LLVMInt32Type ();
5223 arg_types [2] = LLVMInt1Type ();
5224 sprintf (name, "llvm.mono.load.i%d.p0i%d", i * 8, i * 8);
5225 LLVMAddFunction (module, name, LLVMFunctionType (LLVMIntType (i * 8), arg_types, 3, FALSE));
5227 arg_types [0] = LLVMIntType (i * 8);
5228 arg_types [1] = LLVMPointerType (LLVMIntType (i * 8), 0);
5229 arg_types [2] = LLVMInt32Type ();
5230 arg_types [3] = LLVMInt1Type ();
5231 sprintf (name, "llvm.mono.store.i%d.p0i%d", i * 8, i * 8);
5232 LLVMAddFunction (module, name, LLVMFunctionType (LLVMVoidType (), arg_types, 4, FALSE));
5238 add_types (MonoLLVMModule *lmodule)
5240 lmodule->ptr_type = LLVMPointerType (sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type (), 0);
5244 mono_llvm_init (void)
5246 mono_native_tls_alloc (¤t_cfg_tls_id, NULL);
5250 init_jit_module (MonoDomain *domain)
5252 MonoJitICallInfo *info;
5253 MonoJitDomainInfo *dinfo;
5254 MonoLLVMModule *module;
5257 dinfo = domain_jit_info (domain);
5258 if (dinfo->llvm_module)
5261 mono_loader_lock ();
5263 if (dinfo->llvm_module) {
5264 mono_loader_unlock ();
5268 module = g_new0 (MonoLLVMModule, 1);
5270 name = g_strdup_printf ("mono-%s", domain->friendly_name);
5271 module->module = LLVMModuleCreateWithName (name);
5273 module->mono_ee = mono_llvm_create_ee (LLVMCreateModuleProviderForExistingModule (module->module), alloc_cb, emitted_cb, exception_cb, dlsym_cb, &module->ee);
5275 add_intrinsics (module->module);
5278 module->llvm_types = g_hash_table_new (NULL, NULL);
5280 info = mono_find_jit_icall_by_name ("llvm_resume_unwind_trampoline");
5282 LLVMAddGlobalMapping (module->ee, LLVMGetNamedFunction (module->module, "llvm_resume_unwind_trampoline"), (void*)info->func);
5284 mono_memory_barrier ();
5286 dinfo->llvm_module = module;
5288 mono_loader_unlock ();
5292 mono_llvm_cleanup (void)
5294 if (aot_module.module)
5295 LLVMDisposeModule (aot_module.module);
5297 LLVMContextDispose (LLVMGetGlobalContext ());
5301 mono_llvm_free_domain_info (MonoDomain *domain)
5303 MonoJitDomainInfo *info = domain_jit_info (domain);
5304 MonoLLVMModule *module = info->llvm_module;
5310 if (module->llvm_types)
5311 g_hash_table_destroy (module->llvm_types);
5313 mono_llvm_dispose_ee (module->mono_ee);
5315 if (module->bb_names) {
5316 for (i = 0; i < module->bb_names_len; ++i)
5317 g_free (module->bb_names [i]);
5318 g_free (module->bb_names);
5320 //LLVMDisposeModule (module->module);
5324 info->llvm_module = NULL;
5328 mono_llvm_create_aot_module (const char *got_symbol)
5330 /* Delete previous module */
5331 if (aot_module.plt_entries)
5332 g_hash_table_destroy (aot_module.plt_entries);
5333 if (aot_module.module)
5334 LLVMDisposeModule (aot_module.module);
5336 memset (&aot_module, 0, sizeof (aot_module));
5338 aot_module.module = LLVMModuleCreateWithName ("aot");
5339 aot_module.got_symbol = got_symbol;
5341 add_intrinsics (aot_module.module);
5342 add_types (&aot_module);
5346 * We couldn't compute the type of the LLVM global representing the got because
5347 * its size is only known after all the methods have been emitted. So create
5348 * a dummy variable, and replace all uses it with the real got variable when
5349 * its size is known in mono_llvm_emit_aot_module ().
5352 LLVMTypeRef got_type = LLVMArrayType (aot_module.ptr_type, 0);
5354 aot_module.got_var = LLVMAddGlobal (aot_module.module, got_type, "mono_dummy_got");
5355 LLVMSetInitializer (aot_module.got_var, LLVMConstNull (got_type));
5358 /* Add a dummy personality function */
5360 LLVMBasicBlockRef lbb;
5361 LLVMBuilderRef lbuilder;
5362 LLVMValueRef personality;
5364 personality = LLVMAddFunction (aot_module.module, "mono_aot_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5365 LLVMSetLinkage (personality, LLVMInternalLinkage);
5366 lbb = LLVMAppendBasicBlock (personality, "BB0");
5367 lbuilder = LLVMCreateBuilder ();
5368 LLVMPositionBuilderAtEnd (lbuilder, lbb);
5369 LLVMBuildRetVoid (lbuilder);
5372 aot_module.llvm_types = g_hash_table_new (NULL, NULL);
5373 aot_module.plt_entries = g_hash_table_new (g_str_hash, g_str_equal);
5374 aot_module.plt_entries_ji = g_hash_table_new (NULL, NULL);
5375 aot_module.method_to_lmethod = g_hash_table_new (NULL, NULL);
5379 * Emit the aot module into the LLVM bitcode file FILENAME.
5382 mono_llvm_emit_aot_module (const char *filename, const char *cu_name, int got_size)
5384 LLVMTypeRef got_type;
5385 LLVMValueRef real_got;
5386 MonoLLVMModule *module = &aot_module;
5389 * Create the real got variable and replace all uses of the dummy variable with
5392 got_type = LLVMArrayType (aot_module.ptr_type, got_size);
5393 real_got = LLVMAddGlobal (aot_module.module, got_type, aot_module.got_symbol);
5394 LLVMSetInitializer (real_got, LLVMConstNull (got_type));
5395 LLVMSetLinkage (real_got, LLVMInternalLinkage);
5397 mono_llvm_replace_uses_of (aot_module.got_var, real_got);
5399 mark_as_used (&aot_module, real_got);
5401 /* Delete the dummy got so it doesn't become a global */
5402 LLVMDeleteGlobal (aot_module.got_var);
5404 emit_llvm_used (&aot_module);
5405 emit_dbg_info (&aot_module, filename, cu_name);
5407 /* Replace PLT entries for directly callable methods with the methods themselves */
5409 GHashTableIter iter;
5411 LLVMValueRef callee;
5413 g_hash_table_iter_init (&iter, aot_module.plt_entries_ji);
5414 while (g_hash_table_iter_next (&iter, (void**)&ji, (void**)&callee)) {
5415 if (mono_aot_is_direct_callable (ji)) {
5416 LLVMValueRef lmethod;
5418 lmethod = g_hash_table_lookup (module->method_to_lmethod, ji->data.method);
5419 /* The types might not match because the caller might pass an rgctx */
5420 if (lmethod && LLVMTypeOf (callee) == LLVMTypeOf (lmethod)) {
5421 mono_llvm_replace_uses_of (callee, lmethod);
5422 mono_aot_mark_unused_llvm_plt_entry (ji);
5432 if (LLVMVerifyModule (aot_module.module, LLVMReturnStatusAction, &verifier_err)) {
5433 g_assert_not_reached ();
5438 LLVMWriteBitcodeToFile (aot_module.module, filename);
5443 md_string (const char *s)
5445 return LLVMMDString (s, strlen (s));
5448 /* Debugging support */
5451 emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name)
5453 LLVMModuleRef module = lmodule->module;
5454 LLVMValueRef args [16], cu_args [16], cu, ver;
5456 char *build_info, *s, *dir;
5459 // FIXME: This cannot be enabled, since the AOT compiler also emits dwarf info,
5460 // and the abbrev indexes will not be correct since llvm has added its own
5466 * Emit dwarf info in the form of LLVM metadata. There is some
5467 * out-of-date documentation at:
5468 * http://llvm.org/docs/SourceLevelDebugging.html
5469 * but most of this was gathered from the llvm and
5474 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_TAG_compile_unit, FALSE);
5475 /* CU name/compilation dir */
5476 dir = g_path_get_dirname (filename);
5477 args [0] = LLVMMDString (cu_name, strlen (cu_name));
5478 args [1] = LLVMMDString (dir, strlen (dir));
5479 cu_args [n_cuargs ++] = LLVMMDNode (args, 2);
5482 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_LANG_C99, FALSE);
5484 build_info = mono_get_runtime_build_info ();
5485 s = g_strdup_printf ("Mono AOT Compiler %s (LLVM)", build_info);
5486 cu_args [n_cuargs ++] = LLVMMDString (s, strlen (s));
5487 g_free (build_info);
5489 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5491 cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5492 /* Runtime version */
5493 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5495 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5496 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5498 if (lmodule->subprogram_mds) {
5502 mds = g_new0 (LLVMValueRef, lmodule->subprogram_mds->len);
5503 for (i = 0; i < lmodule->subprogram_mds->len; ++i)
5504 mds [i] = g_ptr_array_index (lmodule->subprogram_mds, i);
5505 cu_args [n_cuargs ++] = LLVMMDNode (mds, lmodule->subprogram_mds->len);
5507 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5510 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5511 /* Imported modules */
5512 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5514 cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5515 /* DebugEmissionKind = FullDebug */
5516 cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5517 cu = LLVMMDNode (cu_args, n_cuargs);
5518 LLVMAddNamedMetadataOperand (module, "llvm.dbg.cu", cu);
5520 args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5521 args [1] = LLVMMDString ("Dwarf Version", strlen ("Dwarf Version"));
5522 args [2] = LLVMConstInt (LLVMInt32Type (), 2, FALSE);
5523 ver = LLVMMDNode (args, 3);
5524 LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5526 args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5527 args [1] = LLVMMDString ("Debug Info Version", strlen ("Debug Info Version"));
5528 args [2] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5529 ver = LLVMMDNode (args, 3);
5530 LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5534 emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name)
5536 MonoLLVMModule *module = ctx->lmodule;
5537 MonoDebugMethodInfo *minfo = ctx->minfo;
5538 char *source_file, *dir, *filename;
5539 LLVMValueRef md, args [16], ctx_args [16], md_args [64], type_args [16], ctx_md, type_md;
5547 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, NULL, &n_il_offsets, &il_offsets, &line_numbers, NULL, NULL, NULL, NULL);
5549 source_file = g_strdup ("<unknown>");
5550 dir = g_path_get_dirname (source_file);
5551 filename = g_path_get_basename (source_file);
5553 ctx_args [0] = LLVMConstInt (LLVMInt32Type (), 0x29, FALSE);
5554 args [0] = md_string (filename);
5555 args [1] = md_string (dir);
5556 ctx_args [1] = LLVMMDNode (args, 2);
5557 ctx_md = LLVMMDNode (ctx_args, 2);
5559 type_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subroutine_type, FALSE);
5560 type_args [1] = NULL;
5561 type_args [2] = NULL;
5562 type_args [3] = LLVMMDString ("", 0);
5563 type_args [4] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5564 type_args [5] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5565 type_args [6] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5566 type_args [7] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5567 type_args [8] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5568 type_args [9] = NULL;
5569 type_args [10] = NULL;
5570 type_args [11] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5571 type_args [12] = NULL;
5572 type_args [13] = NULL;
5573 type_args [14] = NULL;
5574 type_md = LLVMMDNode (type_args, 14);
5576 /* http://llvm.org/docs/SourceLevelDebugging.html#subprogram-descriptors */
5577 md_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subprogram, FALSE);
5578 /* Source directory + file pair */
5579 args [0] = md_string (filename);
5580 args [1] = md_string (dir);
5581 md_args [1] = LLVMMDNode (args ,2);
5582 md_args [2] = ctx_md;
5583 md_args [3] = md_string (cfg->method->name);
5584 md_args [4] = md_string (name);
5585 md_args [5] = md_string (name);
5588 md_args [6] = LLVMConstInt (LLVMInt32Type (), line_numbers [0], FALSE);
5590 md_args [6] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5592 md_args [7] = type_md;
5594 md_args [8] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5596 md_args [9] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5598 md_args [10] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5599 /* Index into a virtual function */
5600 md_args [11] = NULL;
5601 md_args [12] = NULL;
5603 md_args [13] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5605 md_args [14] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5606 /* Pointer to LLVM function */
5607 md_args [15] = method;
5608 /* Function template parameter */
5609 md_args [16] = NULL;
5610 /* Function declaration descriptor */
5611 md_args [17] = NULL;
5612 /* List of function variables */
5613 md_args [18] = LLVMMDNode (args, 0);
5615 md_args [19] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5616 md = LLVMMDNode (md_args, 20);
5618 if (!module->subprogram_mds)
5619 module->subprogram_mds = g_ptr_array_new ();
5620 g_ptr_array_add (module->subprogram_mds, md);
5624 g_free (source_file);
5625 g_free (il_offsets);
5626 g_free (line_numbers);
5632 emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code)
5634 MonoCompile *cfg = ctx->cfg;
5636 if (ctx->minfo && cil_code && cil_code >= cfg->header->code && cil_code < cfg->header->code + cfg->header->code_size) {
5637 MonoDebugSourceLocation *loc;
5638 LLVMValueRef loc_md, md_args [16];
5641 loc = mono_debug_symfile_lookup_location (ctx->minfo, cil_code - cfg->header->code);
5645 md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->row, FALSE);
5646 md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->column, FALSE);
5647 md_args [nmd_args ++] = ctx->dbg_md;
5648 md_args [nmd_args ++] = NULL;
5649 loc_md = LLVMMDNode (md_args, nmd_args);
5650 LLVMSetCurrentDebugLocation (builder, loc_md);
5651 mono_debug_symfile_free_location (loc);
5658 - Emit LLVM IR from the mono IR using the LLVM C API.
5659 - The original arch specific code remains, so we can fall back to it if we run
5660 into something we can't handle.
5664 A partial list of issues:
5665 - Handling of opcodes which can throw exceptions.
5667 In the mono JIT, these are implemented using code like this:
5674 push throw_pos - method
5675 call <exception trampoline>
5677 The problematic part is push throw_pos - method, which cannot be represented
5678 in the LLVM IR, since it does not support label values.
5679 -> this can be implemented in AOT mode using inline asm + labels, but cannot
5680 be implemented in JIT mode ?
5681 -> a possible but slower implementation would use the normal exception
5682 throwing code but it would need to control the placement of the throw code
5683 (it needs to be exactly after the compare+branch).
5684 -> perhaps add a PC offset intrinsics ?
5686 - efficient implementation of .ovf opcodes.
5688 These are currently implemented as:
5689 <ins which sets the condition codes>
5692 Some overflow opcodes are now supported by LLVM SVN.
5694 - exception handling, unwinding.
5695 - SSA is disabled for methods with exception handlers
5696 - How to obtain unwind info for LLVM compiled methods ?
5697 -> this is now solved by converting the unwind info generated by LLVM
5699 - LLVM uses the c++ exception handling framework, while we use our home grown
5700 code, and couldn't use the c++ one:
5701 - its not supported under VC++, other exotic platforms.
5702 - it might be impossible to support filter clauses with it.
5706 The trampolines need a predictable call sequence, since they need to disasm
5707 the calling code to obtain register numbers / offsets.
5709 LLVM currently generates this code in non-JIT mode:
5710 mov -0x98(%rax),%eax
5712 Here, the vtable pointer is lost.
5713 -> solution: use one vtable trampoline per class.
5715 - passing/receiving the IMT pointer/RGCTX.
5716 -> solution: pass them as normal arguments ?
5720 LLVM does not allow the specification of argument registers etc. This means
5721 that all calls are made according to the platform ABI.
5723 - passing/receiving vtypes.
5725 Vtypes passed/received in registers are handled by the front end by using
5726 a signature with scalar arguments, and loading the parts of the vtype into those
5729 Vtypes passed on the stack are handled using the 'byval' attribute.
5733 Supported though alloca, we need to emit the load/store code.
5737 The mono JIT uses pointer sized iregs/double fregs, while LLVM uses precisely
5738 typed registers, so we have to keep track of the precise LLVM type of each vreg.
5739 This is made easier because the IR is already in SSA form.
5740 An additional problem is that our IR is not consistent with types, i.e. i32/ia64
5741 types are frequently used incorrectly.
5746 Emit LLVM bytecode into a .bc file, compile it using llc into a .s file, then
5747 append the AOT data structures to that file. For methods which cannot be
5748 handled by LLVM, the normal JIT compiled versions are used.
5751 /* FIXME: Normalize some aspects of the mono IR to allow easier translation, like:
5752 * - each bblock should end with a branch
5753 * - setting the return value, making cfg->ret non-volatile
5754 * - avoid some transformations in the JIT which make it harder for us to generate
5756 * - use pointer types to help optimizations.