1 use crate::abi::{Abi, FnAbi, LlvmType, PassMode};
2 use crate::builder::Builder;
3 use crate::context::CodegenCx;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::va_arg::emit_va_arg;
8 use crate::value::Value;
13 use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh};
14 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
15 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
16 use rustc_codegen_ssa::coverageinfo;
17 use rustc_codegen_ssa::glue;
18 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
19 use rustc_codegen_ssa::mir::place::PlaceRef;
20 use rustc_codegen_ssa::traits::*;
21 use rustc_codegen_ssa::MemFlags;
23 use rustc_middle::mir::coverage;
24 use rustc_middle::mir::Operand;
25 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
26 use rustc_middle::ty::{self, Ty};
27 use rustc_middle::{bug, span_bug};
28 use rustc_span::{sym, symbol::kw, Span, Symbol};
29 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
30 use rustc_target::spec::PanicStrategy;
32 use std::cmp::Ordering;
35 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<&'ll Value> {
36 let llvm_name = match name {
37 sym::sqrtf32 => "llvm.sqrt.f32",
38 sym::sqrtf64 => "llvm.sqrt.f64",
39 sym::powif32 => "llvm.powi.f32",
40 sym::powif64 => "llvm.powi.f64",
41 sym::sinf32 => "llvm.sin.f32",
42 sym::sinf64 => "llvm.sin.f64",
43 sym::cosf32 => "llvm.cos.f32",
44 sym::cosf64 => "llvm.cos.f64",
45 sym::powf32 => "llvm.pow.f32",
46 sym::powf64 => "llvm.pow.f64",
47 sym::expf32 => "llvm.exp.f32",
48 sym::expf64 => "llvm.exp.f64",
49 sym::exp2f32 => "llvm.exp2.f32",
50 sym::exp2f64 => "llvm.exp2.f64",
51 sym::logf32 => "llvm.log.f32",
52 sym::logf64 => "llvm.log.f64",
53 sym::log10f32 => "llvm.log10.f32",
54 sym::log10f64 => "llvm.log10.f64",
55 sym::log2f32 => "llvm.log2.f32",
56 sym::log2f64 => "llvm.log2.f64",
57 sym::fmaf32 => "llvm.fma.f32",
58 sym::fmaf64 => "llvm.fma.f64",
59 sym::fabsf32 => "llvm.fabs.f32",
60 sym::fabsf64 => "llvm.fabs.f64",
61 sym::minnumf32 => "llvm.minnum.f32",
62 sym::minnumf64 => "llvm.minnum.f64",
63 sym::maxnumf32 => "llvm.maxnum.f32",
64 sym::maxnumf64 => "llvm.maxnum.f64",
65 sym::copysignf32 => "llvm.copysign.f32",
66 sym::copysignf64 => "llvm.copysign.f64",
67 sym::floorf32 => "llvm.floor.f32",
68 sym::floorf64 => "llvm.floor.f64",
69 sym::ceilf32 => "llvm.ceil.f32",
70 sym::ceilf64 => "llvm.ceil.f64",
71 sym::truncf32 => "llvm.trunc.f32",
72 sym::truncf64 => "llvm.trunc.f64",
73 sym::rintf32 => "llvm.rint.f32",
74 sym::rintf64 => "llvm.rint.f64",
75 sym::nearbyintf32 => "llvm.nearbyint.f32",
76 sym::nearbyintf64 => "llvm.nearbyint.f64",
77 sym::roundf32 => "llvm.round.f32",
78 sym::roundf64 => "llvm.round.f64",
79 sym::assume => "llvm.assume",
80 sym::abort => "llvm.trap",
83 Some(cx.get_intrinsic(&llvm_name))
86 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
87 fn is_codegen_intrinsic(
90 args: &Vec<Operand<'tcx>>,
91 caller_instance: ty::Instance<'tcx>,
93 let mut is_codegen_intrinsic = true;
94 // Set `is_codegen_intrinsic` to `false` to bypass `codegen_intrinsic_call()`.
96 // FIXME(richkadel): Make sure to add coverage analysis tests on a crate with
97 // external crate dependencies, where:
98 // 1. Both binary and dependent crates are compiled with `-Zinstrument-coverage`
99 // 2. Only binary is compiled with `-Zinstrument-coverage`
100 // 3. Only dependent crates are compiled with `-Zinstrument-coverage`
102 sym::count_code_region => {
103 use coverage::count_code_region_args::*;
104 self.add_counter_region(
106 op_to_u64(&args[FUNCTION_SOURCE_HASH]),
107 op_to_u32(&args[COUNTER_ID]),
108 coverageinfo::Region::new(
109 op_to_str_slice(&args[FILE_NAME]),
110 op_to_u32(&args[START_LINE]),
111 op_to_u32(&args[START_COL]),
112 op_to_u32(&args[END_LINE]),
113 op_to_u32(&args[END_COL]),
117 sym::coverage_counter_add | sym::coverage_counter_subtract => {
118 is_codegen_intrinsic = false;
119 use coverage::coverage_counter_expression_args::*;
120 self.add_counter_expression_region(
122 op_to_u32(&args[EXPRESSION_ID]),
123 op_to_u32(&args[LEFT_ID]),
124 if intrinsic == sym::coverage_counter_add {
125 coverageinfo::ExprKind::Add
127 coverageinfo::ExprKind::Subtract
129 op_to_u32(&args[RIGHT_ID]),
130 coverageinfo::Region::new(
131 op_to_str_slice(&args[FILE_NAME]),
132 op_to_u32(&args[START_LINE]),
133 op_to_u32(&args[START_COL]),
134 op_to_u32(&args[END_LINE]),
135 op_to_u32(&args[END_COL]),
139 sym::coverage_unreachable => {
140 is_codegen_intrinsic = false;
141 use coverage::coverage_unreachable_args::*;
142 self.add_unreachable_region(
144 coverageinfo::Region::new(
145 op_to_str_slice(&args[FILE_NAME]),
146 op_to_u32(&args[START_LINE]),
147 op_to_u32(&args[START_COL]),
148 op_to_u32(&args[END_LINE]),
149 op_to_u32(&args[END_COL]),
158 fn codegen_intrinsic_call(
160 instance: ty::Instance<'tcx>,
161 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
162 args: &[OperandRef<'tcx, &'ll Value>],
163 llresult: &'ll Value,
165 caller_instance: ty::Instance<'tcx>,
168 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
170 let (def_id, substs) = match callee_ty.kind {
171 ty::FnDef(def_id, substs) => (def_id, substs),
172 _ => bug!("expected fn item type, found {}", callee_ty),
175 let sig = callee_ty.fn_sig(tcx);
176 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
177 let arg_tys = sig.inputs();
178 let ret_ty = sig.output();
179 let name = tcx.item_name(def_id);
180 let name_str = &*name.as_str();
182 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
183 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
185 let simple = get_simple_intrinsic(self, name);
186 let llval = match name {
187 _ if simple.is_some() => self.call(
189 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
192 sym::unreachable => {
196 let expect = self.get_intrinsic(&("llvm.expect.i1"));
197 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
200 let expect = self.get_intrinsic(&("llvm.expect.i1"));
201 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
214 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
215 self.call(llfn, &[], None)
217 sym::count_code_region => {
218 let coverageinfo = tcx.coverageinfo(caller_instance.def_id());
219 let mangled_fn = tcx.symbol_name(caller_instance);
220 let (mangled_fn_name, _len_val) = self.const_str(Symbol::intern(mangled_fn.name));
221 let num_counters = self.const_u32(coverageinfo.num_counters);
222 use coverage::count_code_region_args::*;
223 let hash = args[FUNCTION_SOURCE_HASH].immediate();
224 let index = args[COUNTER_ID].immediate();
226 "translating Rust intrinsic `count_code_region()` to LLVM intrinsic: \
227 instrprof.increment(fn_name={}, hash={:?}, num_counters={:?}, index={:?})",
228 mangled_fn.name, hash, num_counters, index,
230 self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
232 sym::va_start => self.va_start(args[0].immediate()),
233 sym::va_end => self.va_end(args[0].immediate()),
235 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
236 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
239 match fn_abi.ret.layout.abi {
240 abi::Abi::Scalar(ref scalar) => {
242 Primitive::Int(..) => {
243 if self.cx().size_of(ret_ty).bytes() < 4 {
244 // `va_arg` should not be called on a integer type
245 // less than 4 bytes in length. If it is, promote
246 // the integer to a `i32` and truncate the result
247 // back to the smaller type.
248 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
249 self.trunc(promoted_result, llret_ty)
251 emit_va_arg(self, args[0], ret_ty)
254 Primitive::F64 | Primitive::Pointer => {
255 emit_va_arg(self, args[0], ret_ty)
257 // `va_arg` should never be used with the return type f32.
258 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
261 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
264 sym::size_of_val => {
265 let tp_ty = substs.type_at(0);
266 if let OperandValue::Pair(_, meta) = args[0].val {
267 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
270 self.const_usize(self.size_of(tp_ty).bytes())
273 sym::min_align_of_val => {
274 let tp_ty = substs.type_at(0);
275 if let OperandValue::Pair(_, meta) = args[0].val {
276 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
279 self.const_usize(self.align_of(tp_ty).bytes())
288 | sym::variant_count => {
291 .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
293 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
300 let ptr = args[0].immediate();
301 let offset = args[1].immediate();
302 self.inbounds_gep(ptr, &[offset])
304 sym::arith_offset => {
305 let ptr = args[0].immediate();
306 let offset = args[1].immediate();
307 self.gep(ptr, &[offset])
310 sym::copy_nonoverlapping => {
334 sym::write_bytes => {
346 sym::volatile_copy_nonoverlapping_memory => {
358 sym::volatile_copy_memory => {
370 sym::volatile_set_memory => {
381 sym::volatile_load | sym::unaligned_volatile_load => {
382 let tp_ty = substs.type_at(0);
383 let mut ptr = args[0].immediate();
384 if let PassMode::Cast(ty) = fn_abi.ret.mode {
385 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
387 let load = self.volatile_load(ptr);
388 let align = if name == sym::unaligned_volatile_load {
391 self.align_of(tp_ty).bytes() as u32
394 llvm::LLVMSetAlignment(load, align);
396 to_immediate(self, load, self.layout_of(tp_ty))
398 sym::volatile_store => {
399 let dst = args[0].deref(self.cx());
400 args[1].val.volatile_store(self, dst);
403 sym::unaligned_volatile_store => {
404 let dst = args[0].deref(self.cx());
405 args[1].val.unaligned_volatile_store(self, dst);
408 sym::prefetch_read_data
409 | sym::prefetch_write_data
410 | sym::prefetch_read_instruction
411 | sym::prefetch_write_instruction => {
412 let expect = self.get_intrinsic(&("llvm.prefetch"));
413 let (rw, cache_type) = match name {
414 sym::prefetch_read_data => (0, 1),
415 sym::prefetch_write_data => (1, 1),
416 sym::prefetch_read_instruction => (0, 0),
417 sym::prefetch_write_instruction => (1, 0),
426 self.const_i32(cache_type),
438 | sym::add_with_overflow
439 | sym::sub_with_overflow
440 | sym::mul_with_overflow
454 | sym::saturating_add
455 | sym::saturating_sub => {
457 match int_type_width_signed(ty, self) {
458 Some((width, signed)) => match name {
459 sym::ctlz | sym::cttz => {
460 let y = self.const_bool(false);
461 let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
462 self.call(llfn, &[args[0].immediate(), y], None)
464 sym::ctlz_nonzero | sym::cttz_nonzero => {
465 let y = self.const_bool(true);
466 let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
467 let llfn = self.get_intrinsic(llvm_name);
468 self.call(llfn, &[args[0].immediate(), y], None)
470 sym::ctpop => self.call(
471 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
472 &[args[0].immediate()],
477 args[0].immediate() // byte swap a u8/i8 is just a no-op
480 self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
481 &[args[0].immediate()],
486 sym::bitreverse => self.call(
487 self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
488 &[args[0].immediate()],
491 sym::add_with_overflow
492 | sym::sub_with_overflow
493 | sym::mul_with_overflow => {
494 let intrinsic = format!(
495 "llvm.{}{}.with.overflow.i{}",
496 if signed { 's' } else { 'u' },
500 let llfn = self.get_intrinsic(&intrinsic);
502 // Convert `i1` to a `bool`, and write it to the out parameter
504 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
505 let val = self.extract_value(pair, 0);
506 let overflow = self.extract_value(pair, 1);
507 let overflow = self.zext(overflow, self.type_bool());
509 let dest = result.project_field(self, 0);
510 self.store(val, dest.llval, dest.align);
511 let dest = result.project_field(self, 1);
512 self.store(overflow, dest.llval, dest.align);
516 sym::wrapping_add => self.add(args[0].immediate(), args[1].immediate()),
517 sym::wrapping_sub => self.sub(args[0].immediate(), args[1].immediate()),
518 sym::wrapping_mul => self.mul(args[0].immediate(), args[1].immediate()),
521 self.exactsdiv(args[0].immediate(), args[1].immediate())
523 self.exactudiv(args[0].immediate(), args[1].immediate())
526 sym::unchecked_div => {
528 self.sdiv(args[0].immediate(), args[1].immediate())
530 self.udiv(args[0].immediate(), args[1].immediate())
533 sym::unchecked_rem => {
535 self.srem(args[0].immediate(), args[1].immediate())
537 self.urem(args[0].immediate(), args[1].immediate())
540 sym::unchecked_shl => self.shl(args[0].immediate(), args[1].immediate()),
541 sym::unchecked_shr => {
543 self.ashr(args[0].immediate(), args[1].immediate())
545 self.lshr(args[0].immediate(), args[1].immediate())
548 sym::unchecked_add => {
550 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
552 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
555 sym::unchecked_sub => {
557 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
559 self.unchecked_usub(args[0].immediate(), args[1].immediate())
562 sym::unchecked_mul => {
564 self.unchecked_smul(args[0].immediate(), args[1].immediate())
566 self.unchecked_umul(args[0].immediate(), args[1].immediate())
569 sym::rotate_left | sym::rotate_right => {
570 let is_left = name == sym::rotate_left;
571 let val = args[0].immediate();
572 let raw_shift = args[1].immediate();
573 // rotate = funnel shift with first two args the same
575 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
576 let llfn = self.get_intrinsic(llvm_name);
577 self.call(llfn, &[val, val, raw_shift], None)
579 sym::saturating_add | sym::saturating_sub => {
580 let is_add = name == sym::saturating_add;
581 let lhs = args[0].immediate();
582 let rhs = args[1].immediate();
583 let llvm_name = &format!(
585 if signed { 's' } else { 'u' },
586 if is_add { "add" } else { "sub" },
589 let llfn = self.get_intrinsic(llvm_name);
590 self.call(llfn, &[lhs, rhs], None)
595 span_invalid_monomorphization_error(
599 "invalid monomorphization of `{}` intrinsic: \
600 expected basic integer type, found `{}`",
608 sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
609 match float_type_width(arg_tys[0]) {
610 Some(_width) => match name {
611 sym::fadd_fast => self.fadd_fast(args[0].immediate(), args[1].immediate()),
612 sym::fsub_fast => self.fsub_fast(args[0].immediate(), args[1].immediate()),
613 sym::fmul_fast => self.fmul_fast(args[0].immediate(), args[1].immediate()),
614 sym::fdiv_fast => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
615 sym::frem_fast => self.frem_fast(args[0].immediate(), args[1].immediate()),
619 span_invalid_monomorphization_error(
623 "invalid monomorphization of `{}` intrinsic: \
624 expected basic float type, found `{}`",
633 sym::float_to_int_unchecked => {
634 if float_type_width(arg_tys[0]).is_none() {
635 span_invalid_monomorphization_error(
639 "invalid monomorphization of `float_to_int_unchecked` \
640 intrinsic: expected basic float type, \
647 let (width, signed) = match int_type_width_signed(ret_ty, self.cx) {
650 span_invalid_monomorphization_error(
654 "invalid monomorphization of `float_to_int_unchecked` \
655 intrinsic: expected basic integer type, \
664 self.fptosi(args[0].immediate(), self.cx.type_ix(width))
666 self.fptoui(args[0].immediate(), self.cx.type_ix(width))
670 sym::discriminant_value => {
671 if ret_ty.is_integral() {
672 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
674 span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
678 _ if name_str.starts_with("simd_") => {
679 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
684 // This requires that atomic intrinsics follow a specific naming pattern:
685 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
686 name if name_str.starts_with("atomic_") => {
687 use rustc_codegen_ssa::common::AtomicOrdering::*;
688 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
690 let split: Vec<&str> = name_str.split('_').collect();
692 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
693 let (order, failorder) = match split.len() {
694 2 => (SequentiallyConsistent, SequentiallyConsistent),
695 3 => match split[2] {
696 "unordered" => (Unordered, Unordered),
697 "relaxed" => (Monotonic, Monotonic),
698 "acq" => (Acquire, Acquire),
699 "rel" => (Release, Monotonic),
700 "acqrel" => (AcquireRelease, Acquire),
701 "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
702 "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
703 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
705 4 => match (split[2], split[3]) {
706 ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
707 ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
708 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
710 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
713 let invalid_monomorphization = |ty| {
714 span_invalid_monomorphization_error(
718 "invalid monomorphization of `{}` intrinsic: \
719 expected basic integer type, found `{}`",
726 "cxchg" | "cxchgweak" => {
727 let ty = substs.type_at(0);
728 if int_type_width_signed(ty, self).is_some() {
729 let weak = split[1] == "cxchgweak";
730 let pair = self.atomic_cmpxchg(
738 let val = self.extract_value(pair, 0);
739 let success = self.extract_value(pair, 1);
740 let success = self.zext(success, self.type_bool());
742 let dest = result.project_field(self, 0);
743 self.store(val, dest.llval, dest.align);
744 let dest = result.project_field(self, 1);
745 self.store(success, dest.llval, dest.align);
748 return invalid_monomorphization(ty);
753 let ty = substs.type_at(0);
754 if int_type_width_signed(ty, self).is_some() {
755 let size = self.size_of(ty);
756 self.atomic_load(args[0].immediate(), order, size)
758 return invalid_monomorphization(ty);
763 let ty = substs.type_at(0);
764 if int_type_width_signed(ty, self).is_some() {
765 let size = self.size_of(ty);
774 return invalid_monomorphization(ty);
779 self.atomic_fence(order, SynchronizationScope::CrossThread);
783 "singlethreadfence" => {
784 self.atomic_fence(order, SynchronizationScope::SingleThread);
788 // These are all AtomicRMW ops
790 let atom_op = match op {
791 "xchg" => AtomicRmwBinOp::AtomicXchg,
792 "xadd" => AtomicRmwBinOp::AtomicAdd,
793 "xsub" => AtomicRmwBinOp::AtomicSub,
794 "and" => AtomicRmwBinOp::AtomicAnd,
795 "nand" => AtomicRmwBinOp::AtomicNand,
796 "or" => AtomicRmwBinOp::AtomicOr,
797 "xor" => AtomicRmwBinOp::AtomicXor,
798 "max" => AtomicRmwBinOp::AtomicMax,
799 "min" => AtomicRmwBinOp::AtomicMin,
800 "umax" => AtomicRmwBinOp::AtomicUMax,
801 "umin" => AtomicRmwBinOp::AtomicUMin,
802 _ => self.sess().fatal("unknown atomic operation"),
805 let ty = substs.type_at(0);
806 if int_type_width_signed(ty, self).is_some() {
814 return invalid_monomorphization(ty);
820 sym::nontemporal_store => {
821 let dst = args[0].deref(self.cx());
822 args[1].val.nontemporal_store(self, dst);
826 sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
827 let a = args[0].immediate();
828 let b = args[1].immediate();
829 if name == sym::ptr_guaranteed_eq {
830 self.icmp(IntPredicate::IntEQ, a, b)
832 self.icmp(IntPredicate::IntNE, a, b)
836 sym::ptr_offset_from => {
837 let ty = substs.type_at(0);
838 let pointee_size = self.size_of(ty);
840 // This is the same sequence that Clang emits for pointer subtraction.
841 // It can be neither `nsw` nor `nuw` because the input is treated as
842 // unsigned but then the output is treated as signed, so neither works.
843 let a = args[0].immediate();
844 let b = args[1].immediate();
845 let a = self.ptrtoint(a, self.type_isize());
846 let b = self.ptrtoint(b, self.type_isize());
847 let d = self.sub(a, b);
848 let pointee_size = self.const_usize(pointee_size.bytes());
849 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
850 self.exactsdiv(d, pointee_size)
853 _ => bug!("unknown intrinsic '{}'", name),
856 if !fn_abi.ret.is_ignore() {
857 if let PassMode::Cast(ty) = fn_abi.ret.mode {
858 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
859 let ptr = self.pointercast(result.llval, ptr_llty);
860 self.store(llval, ptr, result.align);
862 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
864 .store(self, result);
869 fn abort(&mut self) {
870 let fnname = self.get_intrinsic(&("llvm.trap"));
871 self.call(fnname, &[], None);
874 fn assume(&mut self, val: Self::Value) {
875 let assume_intrinsic = self.get_intrinsic("llvm.assume");
876 self.call(assume_intrinsic, &[val], None);
879 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
880 let expect = self.get_intrinsic(&"llvm.expect.i1");
881 self.call(expect, &[cond, self.const_bool(expected)], None)
884 fn sideeffect(&mut self) {
885 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
886 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
887 self.call(fnname, &[], None);
891 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
892 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
893 self.call(intrinsic, &[va_list], None)
896 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
897 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
898 self.call(intrinsic, &[va_list], None)
903 bx: &mut Builder<'a, 'll, 'tcx>,
911 let (size, align) = bx.size_and_align_of(ty);
912 let size = bx.mul(bx.const_usize(size.bytes()), count);
913 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
915 bx.memmove(dst, align, src, align, size, flags);
917 bx.memcpy(dst, align, src, align, size, flags);
922 bx: &mut Builder<'a, 'll, 'tcx>,
929 let (size, align) = bx.size_and_align_of(ty);
930 let size = bx.mul(bx.const_usize(size.bytes()), count);
931 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
932 bx.memset(dst, val, size, align, flags);
936 bx: &mut Builder<'a, 'll, 'tcx>,
937 try_func: &'ll Value,
939 catch_func: &'ll Value,
942 if bx.sess().panic_strategy() == PanicStrategy::Abort {
943 bx.call(try_func, &[data], None);
944 // Return 0 unconditionally from the intrinsic call;
945 // we can never unwind.
946 let ret_align = bx.tcx().data_layout.i32_align.abi;
947 bx.store(bx.const_i32(0), dest, ret_align);
948 } else if wants_msvc_seh(bx.sess()) {
949 codegen_msvc_try(bx, try_func, data, catch_func, dest);
951 codegen_gnu_try(bx, try_func, data, catch_func, dest);
955 // MSVC's definition of the `rust_try` function.
957 // This implementation uses the new exception handling instructions in LLVM
958 // which have support in LLVM for SEH on MSVC targets. Although these
959 // instructions are meant to work for all targets, as of the time of this
960 // writing, however, LLVM does not recommend the usage of these new instructions
961 // as the old ones are still more optimized.
963 bx: &mut Builder<'a, 'll, 'tcx>,
964 try_func: &'ll Value,
966 catch_func: &'ll Value,
969 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
970 bx.set_personality_fn(bx.eh_personality());
973 let mut normal = bx.build_sibling_block("normal");
974 let mut catchswitch = bx.build_sibling_block("catchswitch");
975 let mut catchpad = bx.build_sibling_block("catchpad");
976 let mut caught = bx.build_sibling_block("caught");
978 let try_func = llvm::get_param(bx.llfn(), 0);
979 let data = llvm::get_param(bx.llfn(), 1);
980 let catch_func = llvm::get_param(bx.llfn(), 2);
982 // We're generating an IR snippet that looks like:
984 // declare i32 @rust_try(%try_func, %data, %catch_func) {
985 // %slot = alloca u8*
986 // invoke %try_func(%data) to label %normal unwind label %catchswitch
992 // %cs = catchswitch within none [%catchpad] unwind to caller
995 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
997 // call %catch_func(%data, %ptr)
998 // catchret from %tok to label %caught
1004 // This structure follows the basic usage of throw/try/catch in LLVM.
1005 // For example, compile this C++ snippet to see what LLVM generates:
1007 // #include <stdint.h>
1009 // struct rust_panic {
1010 // rust_panic(const rust_panic&);
1017 // void (*try_func)(void*),
1019 // void (*catch_func)(void*, void*) noexcept
1024 // } catch(rust_panic& a) {
1025 // catch_func(data, &a);
1030 // More information can be found in libstd's seh.rs implementation.
1031 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
1032 let slot = bx.alloca(bx.type_i8p(), ptr_align);
1033 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
1035 normal.ret(bx.const_i32(0));
1037 let cs = catchswitch.catch_switch(None, None, 1);
1038 catchswitch.add_handler(cs, catchpad.llbb());
1040 // We can't use the TypeDescriptor defined in libpanic_unwind because it
1041 // might be in another DLL and the SEH encoding only supports specifying
1042 // a TypeDescriptor from the current module.
1044 // However this isn't an issue since the MSVC runtime uses string
1045 // comparison on the type name to match TypeDescriptors rather than
1046 // pointer equality.
1048 // So instead we generate a new TypeDescriptor in each module that uses
1049 // `try` and let the linker merge duplicate definitions in the same
1052 // When modifying, make sure that the type_name string exactly matches
1053 // the one used in src/libpanic_unwind/seh.rs.
1054 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
1055 let type_name = bx.const_bytes(b"rust_panic\0");
1057 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
1058 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
1060 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1061 llvm::SetUniqueComdat(bx.llmod, tydesc);
1062 llvm::LLVMSetInitializer(tydesc, type_info);
1065 // The flag value of 8 indicates that we are catching the exception by
1066 // reference instead of by value. We can't use catch by value because
1067 // that requires copying the exception object, which we don't support
1068 // since our exception object effectively contains a Box.
1070 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1071 let flags = bx.const_i32(8);
1072 let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
1073 let ptr = catchpad.load(slot, ptr_align);
1074 catchpad.call(catch_func, &[data, ptr], Some(&funclet));
1076 catchpad.catch_ret(&funclet, caught.llbb());
1078 caught.ret(bx.const_i32(1));
1081 // Note that no invoke is used here because by definition this function
1082 // can't panic (that's what it's catching).
1083 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1084 let i32_align = bx.tcx().data_layout.i32_align.abi;
1085 bx.store(ret, dest, i32_align);
1088 // Definition of the standard `try` function for Rust using the GNU-like model
1089 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1092 // This codegen is a little surprising because we always call a shim
1093 // function instead of inlining the call to `invoke` manually here. This is done
1094 // because in LLVM we're only allowed to have one personality per function
1095 // definition. The call to the `try` intrinsic is being inlined into the
1096 // function calling it, and that function may already have other personality
1097 // functions in play. By calling a shim we're guaranteed that our shim will have
1098 // the right personality function.
1100 bx: &mut Builder<'a, 'll, 'tcx>,
1101 try_func: &'ll Value,
1103 catch_func: &'ll Value,
1106 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1107 // Codegens the shims described above:
1110 // invoke %try_func(%data) normal %normal unwind %catch
1116 // (%ptr, _) = landingpad
1117 // call %catch_func(%data, %ptr)
1122 let mut then = bx.build_sibling_block("then");
1123 let mut catch = bx.build_sibling_block("catch");
1125 let try_func = llvm::get_param(bx.llfn(), 0);
1126 let data = llvm::get_param(bx.llfn(), 1);
1127 let catch_func = llvm::get_param(bx.llfn(), 2);
1128 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1129 then.ret(bx.const_i32(0));
1131 // Type indicator for the exception being thrown.
1133 // The first value in this tuple is a pointer to the exception object
1134 // being thrown. The second value is a "selector" indicating which of
1135 // the landing pad clauses the exception's type had been matched to.
1136 // rust_try ignores the selector.
1137 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1138 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1139 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1141 let tydesc = bx.get_static(tydesc);
1142 bx.bitcast(tydesc, bx.type_i8p())
1144 None => bx.const_null(bx.type_i8p()),
1146 catch.add_clause(vals, tydesc);
1147 let ptr = catch.extract_value(vals, 0);
1148 catch.call(catch_func, &[data, ptr], None);
1149 catch.ret(bx.const_i32(1));
1152 // Note that no invoke is used here because by definition this function
1153 // can't panic (that's what it's catching).
1154 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1155 let i32_align = bx.tcx().data_layout.i32_align.abi;
1156 bx.store(ret, dest, i32_align);
1159 // Helper function to give a Block to a closure to codegen a shim function.
1160 // This is currently primarily used for the `try` intrinsic functions above.
1161 fn gen_fn<'ll, 'tcx>(
1162 cx: &CodegenCx<'ll, 'tcx>,
1164 inputs: Vec<Ty<'tcx>>,
1166 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1168 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1172 hir::Unsafety::Unsafe,
1175 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1176 let llfn = cx.declare_fn(name, &fn_abi);
1177 cx.set_frame_pointer_elimination(llfn);
1178 cx.apply_target_cpu_attr(llfn);
1179 // FIXME(eddyb) find a nicer way to do this.
1180 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1181 let bx = Builder::new_block(cx, llfn, "entry-block");
1186 // Helper function used to get a handle to the `__rust_try` function used to
1187 // catch exceptions.
1189 // This function is only generated once and is then cached.
1190 fn get_rust_try_fn<'ll, 'tcx>(
1191 cx: &CodegenCx<'ll, 'tcx>,
1192 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1194 if let Some(llfn) = cx.rust_try_fn.get() {
1198 // Define the type up front for the signature of the rust_try function.
1200 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1201 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1205 hir::Unsafety::Unsafe,
1208 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1209 [i8p, i8p].iter().cloned(),
1212 hir::Unsafety::Unsafe,
1215 let output = tcx.types.i32;
1216 let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1217 cx.rust_try_fn.set(Some(rust_try));
1221 fn generic_simd_intrinsic(
1222 bx: &mut Builder<'a, 'll, 'tcx>,
1224 callee_ty: Ty<'tcx>,
1225 args: &[OperandRef<'tcx, &'ll Value>],
1227 llret_ty: &'ll Type,
1229 ) -> Result<&'ll Value, ()> {
1230 // macros for error handling:
1231 macro_rules! emit_error {
1235 ($msg: tt, $($fmt: tt)*) => {
1236 span_invalid_monomorphization_error(
1238 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1243 macro_rules! return_error {
1246 emit_error!($($fmt)*);
1252 macro_rules! require {
1253 ($cond: expr, $($fmt: tt)*) => {
1255 return_error!($($fmt)*);
1260 macro_rules! require_simd {
1261 ($ty: expr, $position: expr) => {
1262 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1268 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1269 let arg_tys = sig.inputs();
1270 let name_str = &*name.as_str();
1272 if name == sym::simd_select_bitmask {
1273 let in_ty = arg_tys[0];
1274 let m_len = match in_ty.kind {
1275 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1276 // of intentional as there's not currently a use case for that.
1277 ty::Int(i) => i.bit_width().unwrap(),
1278 ty::Uint(i) => i.bit_width().unwrap(),
1279 _ => return_error!("`{}` is not an integral type", in_ty),
1281 require_simd!(arg_tys[1], "argument");
1282 let v_len = arg_tys[1].simd_size(tcx);
1285 "mismatched lengths: mask length `{}` != other vector length `{}`",
1289 let i1 = bx.type_i1();
1290 let i1xn = bx.type_vector(i1, m_len);
1291 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1292 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1295 // every intrinsic below takes a SIMD vector as its first argument
1296 require_simd!(arg_tys[0], "input");
1297 let in_ty = arg_tys[0];
1298 let in_elem = arg_tys[0].simd_type(tcx);
1299 let in_len = arg_tys[0].simd_size(tcx);
1301 let comparison = match name {
1302 sym::simd_eq => Some(hir::BinOpKind::Eq),
1303 sym::simd_ne => Some(hir::BinOpKind::Ne),
1304 sym::simd_lt => Some(hir::BinOpKind::Lt),
1305 sym::simd_le => Some(hir::BinOpKind::Le),
1306 sym::simd_gt => Some(hir::BinOpKind::Gt),
1307 sym::simd_ge => Some(hir::BinOpKind::Ge),
1311 if let Some(cmp_op) = comparison {
1312 require_simd!(ret_ty, "return");
1314 let out_len = ret_ty.simd_size(tcx);
1317 "expected return type with length {} (same as input type `{}`), \
1318 found `{}` with length {}",
1325 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1326 "expected return type with integer elements, found `{}` with non-integer `{}`",
1328 ret_ty.simd_type(tcx)
1331 return Ok(compare_simd_types(
1333 args[0].immediate(),
1334 args[1].immediate(),
1341 if name_str.starts_with("simd_shuffle") {
1342 let n: u64 = name_str["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1343 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1346 require_simd!(ret_ty, "return");
1348 let out_len = ret_ty.simd_size(tcx);
1351 "expected return type of length {}, found `{}` with length {}",
1357 in_elem == ret_ty.simd_type(tcx),
1358 "expected return element type `{}` (element of input `{}`), \
1359 found `{}` with element type `{}`",
1363 ret_ty.simd_type(tcx)
1366 let total_len = u128::from(in_len) * 2;
1368 let vector = args[2].immediate();
1370 let indices: Option<Vec<_>> = (0..n)
1373 let val = bx.const_get_elt(vector, i as u64);
1374 match bx.const_to_opt_u128(val, true) {
1376 emit_error!("shuffle index #{} is not a constant", arg_idx);
1379 Some(idx) if idx >= total_len => {
1381 "shuffle index #{} is out of bounds (limit {})",
1387 Some(idx) => Some(bx.const_i32(idx as i32)),
1391 let indices = match indices {
1393 None => return Ok(bx.const_null(llret_ty)),
1396 return Ok(bx.shuffle_vector(
1397 args[0].immediate(),
1398 args[1].immediate(),
1399 bx.const_vector(&indices),
1403 if name == sym::simd_insert {
1405 in_elem == arg_tys[2],
1406 "expected inserted type `{}` (element of input `{}`), found `{}`",
1411 return Ok(bx.insert_element(
1412 args[0].immediate(),
1413 args[2].immediate(),
1414 args[1].immediate(),
1417 if name == sym::simd_extract {
1420 "expected return type `{}` (element of input `{}`), found `{}`",
1425 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1428 if name == sym::simd_select {
1429 let m_elem_ty = in_elem;
1431 require_simd!(arg_tys[1], "argument");
1432 let v_len = arg_tys[1].simd_size(tcx);
1435 "mismatched lengths: mask length `{}` != other vector length `{}`",
1439 match m_elem_ty.kind {
1441 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1443 // truncate the mask to a vector of i1s
1444 let i1 = bx.type_i1();
1445 let i1xn = bx.type_vector(i1, m_len as u64);
1446 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1447 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1450 if name == sym::simd_bitmask {
1451 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1452 // vector mask and returns an unsigned integer containing the most
1453 // significant bit (MSB) of each lane.
1455 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1457 let expected_int_bits = in_len.max(8);
1459 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1460 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1463 // Integer vector <i{in_bitwidth} x in_len>:
1464 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1466 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1469 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1472 "vector argument `{}`'s element type `{}`, expected integer element type",
1478 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1481 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1484 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1485 // Truncate vector to an <i1 x N>
1486 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1487 // Bitcast <i1 x N> to iN:
1488 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1489 // Zero-extend iN to the bitmask type:
1490 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1493 fn simd_simple_float_intrinsic(
1495 in_elem: &::rustc_middle::ty::TyS<'_>,
1496 in_ty: &::rustc_middle::ty::TyS<'_>,
1498 bx: &mut Builder<'a, 'll, 'tcx>,
1500 args: &[OperandRef<'tcx, &'ll Value>],
1501 ) -> Result<&'ll Value, ()> {
1502 macro_rules! emit_error {
1506 ($msg: tt, $($fmt: tt)*) => {
1507 span_invalid_monomorphization_error(
1509 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1513 macro_rules! return_error {
1516 emit_error!($($fmt)*);
1521 let ety = match in_elem.kind {
1522 ty::Float(f) if f.bit_width() == 32 => {
1523 if in_len < 2 || in_len > 16 {
1525 "unsupported floating-point vector `{}` with length `{}` \
1526 out-of-range [2, 16]",
1533 ty::Float(f) if f.bit_width() == 64 => {
1534 if in_len < 2 || in_len > 8 {
1536 "unsupported floating-point vector `{}` with length `{}` \
1537 out-of-range [2, 8]",
1546 "unsupported element type `{}` of floating-point vector `{}`",
1552 return_error!("`{}` is not a floating-point type", in_ty);
1556 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1557 let intrinsic = bx.get_intrinsic(&llvm_name);
1559 bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1560 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1565 sym::simd_fsqrt => {
1566 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1569 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1572 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1575 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1577 sym::simd_floor => {
1578 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1581 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1584 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1586 sym::simd_fexp2 => {
1587 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1589 sym::simd_flog10 => {
1590 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1592 sym::simd_flog2 => {
1593 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1596 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1598 sym::simd_fpowi => {
1599 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1602 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1605 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1607 _ => { /* fallthrough */ }
1611 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1612 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1613 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1614 let p0s: String = "p0".repeat(no_pointers);
1615 match elem_ty.kind {
1616 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1617 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1618 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1619 _ => unreachable!(),
1624 cx: &CodegenCx<'ll, '_>,
1627 mut no_pointers: usize,
1629 // FIXME: use cx.layout_of(ty).llvm_type() ?
1630 let mut elem_ty = match elem_ty.kind {
1631 ty::Int(v) => cx.type_int_from_ty(v),
1632 ty::Uint(v) => cx.type_uint_from_ty(v),
1633 ty::Float(v) => cx.type_float_from_ty(v),
1634 _ => unreachable!(),
1636 while no_pointers > 0 {
1637 elem_ty = cx.type_ptr_to(elem_ty);
1640 cx.type_vector(elem_ty, vec_len)
1643 if name == sym::simd_gather {
1644 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1645 // mask: <N x i{M}>) -> <N x T>
1646 // * N: number of elements in the input vectors
1647 // * T: type of the element to load
1648 // * M: any integer width is supported, will be truncated to i1
1650 // All types must be simd vector types
1651 require_simd!(in_ty, "first");
1652 require_simd!(arg_tys[1], "second");
1653 require_simd!(arg_tys[2], "third");
1654 require_simd!(ret_ty, "return");
1656 // Of the same length:
1658 in_len == arg_tys[1].simd_size(tcx),
1659 "expected {} argument with length {} (same as input type `{}`), \
1660 found `{}` with length {}",
1665 arg_tys[1].simd_size(tcx)
1668 in_len == arg_tys[2].simd_size(tcx),
1669 "expected {} argument with length {} (same as input type `{}`), \
1670 found `{}` with length {}",
1675 arg_tys[2].simd_size(tcx)
1678 // The return type must match the first argument type
1679 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1681 // This counts how many pointers
1682 fn ptr_count(t: Ty<'_>) -> usize {
1684 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1690 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1692 ty::RawPtr(p) => non_ptr(p.ty),
1697 // The second argument must be a simd vector with an element type that's a pointer
1698 // to the element type of the first argument
1699 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1700 ty::RawPtr(p) if p.ty == in_elem => {
1701 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1706 "expected element type `{}` of second argument `{}` \
1707 to be a pointer to the element type `{}` of the first \
1708 argument `{}`, found `{}` != `*_ {}`",
1709 arg_tys[1].simd_type(tcx),
1713 arg_tys[1].simd_type(tcx),
1719 assert!(pointer_count > 0);
1720 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1721 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1723 // The element type of the third argument must be a signed integer type of any width:
1724 match arg_tys[2].simd_type(tcx).kind {
1729 "expected element type `{}` of third argument `{}` \
1730 to be a signed integer type",
1731 arg_tys[2].simd_type(tcx),
1737 // Alignment of T, must be a constant integer value:
1738 let alignment_ty = bx.type_i32();
1739 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1741 // Truncate the mask vector to a vector of i1s:
1742 let (mask, mask_ty) = {
1743 let i1 = bx.type_i1();
1744 let i1xn = bx.type_vector(i1, in_len);
1745 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1748 // Type of the vector of pointers:
1749 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1750 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1752 // Type of the vector of elements:
1753 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1754 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1756 let llvm_intrinsic =
1757 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1758 let f = bx.declare_cfn(
1761 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1765 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1766 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1770 if name == sym::simd_scatter {
1771 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1772 // mask: <N x i{M}>) -> ()
1773 // * N: number of elements in the input vectors
1774 // * T: type of the element to load
1775 // * M: any integer width is supported, will be truncated to i1
1777 // All types must be simd vector types
1778 require_simd!(in_ty, "first");
1779 require_simd!(arg_tys[1], "second");
1780 require_simd!(arg_tys[2], "third");
1782 // Of the same length:
1784 in_len == arg_tys[1].simd_size(tcx),
1785 "expected {} argument with length {} (same as input type `{}`), \
1786 found `{}` with length {}",
1791 arg_tys[1].simd_size(tcx)
1794 in_len == arg_tys[2].simd_size(tcx),
1795 "expected {} argument with length {} (same as input type `{}`), \
1796 found `{}` with length {}",
1801 arg_tys[2].simd_size(tcx)
1804 // This counts how many pointers
1805 fn ptr_count(t: Ty<'_>) -> usize {
1807 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1813 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1815 ty::RawPtr(p) => non_ptr(p.ty),
1820 // The second argument must be a simd vector with an element type that's a pointer
1821 // to the element type of the first argument
1822 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1823 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1824 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1829 "expected element type `{}` of second argument `{}` \
1830 to be a pointer to the element type `{}` of the first \
1831 argument `{}`, found `{}` != `*mut {}`",
1832 arg_tys[1].simd_type(tcx),
1836 arg_tys[1].simd_type(tcx),
1842 assert!(pointer_count > 0);
1843 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1844 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1846 // The element type of the third argument must be a signed integer type of any width:
1847 match arg_tys[2].simd_type(tcx).kind {
1852 "expected element type `{}` of third argument `{}` \
1853 to be a signed integer type",
1854 arg_tys[2].simd_type(tcx),
1860 // Alignment of T, must be a constant integer value:
1861 let alignment_ty = bx.type_i32();
1862 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1864 // Truncate the mask vector to a vector of i1s:
1865 let (mask, mask_ty) = {
1866 let i1 = bx.type_i1();
1867 let i1xn = bx.type_vector(i1, in_len);
1868 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1871 let ret_t = bx.type_void();
1873 // Type of the vector of pointers:
1874 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1875 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1877 // Type of the vector of elements:
1878 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1879 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1881 let llvm_intrinsic =
1882 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1883 let f = bx.declare_cfn(
1885 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1887 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1888 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1892 macro_rules! arith_red {
1893 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1894 $identity:expr) => {
1895 if name == sym::$name {
1898 "expected return type `{}` (element of input `{}`), found `{}`",
1903 return match in_elem.kind {
1904 ty::Int(_) | ty::Uint(_) => {
1905 let r = bx.$integer_reduce(args[0].immediate());
1907 // if overflow occurs, the result is the
1908 // mathematical result modulo 2^n:
1909 Ok(bx.$op(args[1].immediate(), r))
1911 Ok(bx.$integer_reduce(args[0].immediate()))
1915 let acc = if $ordered {
1916 // ordered arithmetic reductions take an accumulator
1919 // unordered arithmetic reductions use the identity accumulator
1920 match f.bit_width() {
1921 32 => bx.const_real(bx.type_f32(), $identity),
1922 64 => bx.const_real(bx.type_f64(), $identity),
1925 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1934 Ok(bx.$float_reduce(acc, args[0].immediate()))
1937 "unsupported {} from `{}` with element `{}` to `{}`",
1948 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1949 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1951 simd_reduce_add_unordered: vector_reduce_add,
1952 vector_reduce_fadd_fast,
1958 simd_reduce_mul_unordered: vector_reduce_mul,
1959 vector_reduce_fmul_fast,
1965 macro_rules! minmax_red {
1966 ($name:ident: $int_red:ident, $float_red:ident) => {
1967 if name == sym::$name {
1970 "expected return type `{}` (element of input `{}`), found `{}`",
1975 return match in_elem.kind {
1976 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1977 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1978 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1980 "unsupported {} from `{}` with element `{}` to `{}`",
1991 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1992 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1994 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1995 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1997 macro_rules! bitwise_red {
1998 ($name:ident : $red:ident, $boolean:expr) => {
1999 if name == sym::$name {
2000 let input = if !$boolean {
2003 "expected return type `{}` (element of input `{}`), found `{}`",
2010 match in_elem.kind {
2011 ty::Int(_) | ty::Uint(_) => {}
2013 "unsupported {} from `{}` with element `{}` to `{}`",
2021 // boolean reductions operate on vectors of i1s:
2022 let i1 = bx.type_i1();
2023 let i1xn = bx.type_vector(i1, in_len as u64);
2024 bx.trunc(args[0].immediate(), i1xn)
2026 return match in_elem.kind {
2027 ty::Int(_) | ty::Uint(_) => {
2028 let r = bx.$red(input);
2029 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2032 "unsupported {} from `{}` with element `{}` to `{}`",
2043 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2044 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2045 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2046 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2047 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2049 if name == sym::simd_cast {
2050 require_simd!(ret_ty, "return");
2051 let out_len = ret_ty.simd_size(tcx);
2054 "expected return type with length {} (same as input type `{}`), \
2055 found `{}` with length {}",
2061 // casting cares about nominal type, not just structural type
2062 let out_elem = ret_ty.simd_type(tcx);
2064 if in_elem == out_elem {
2065 return Ok(args[0].immediate());
2070 Int(/* is signed? */ bool),
2074 let (in_style, in_width) = match in_elem.kind {
2075 // vectors of pointer-sized integers should've been
2076 // disallowed before here, so this unwrap is safe.
2077 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2078 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2079 ty::Float(f) => (Style::Float, f.bit_width()),
2080 _ => (Style::Unsupported, 0),
2082 let (out_style, out_width) = match out_elem.kind {
2083 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2084 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2085 ty::Float(f) => (Style::Float, f.bit_width()),
2086 _ => (Style::Unsupported, 0),
2089 match (in_style, out_style) {
2090 (Style::Int(in_is_signed), Style::Int(_)) => {
2091 return Ok(match in_width.cmp(&out_width) {
2092 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2093 Ordering::Equal => args[0].immediate(),
2096 bx.sext(args[0].immediate(), llret_ty)
2098 bx.zext(args[0].immediate(), llret_ty)
2103 (Style::Int(in_is_signed), Style::Float) => {
2104 return Ok(if in_is_signed {
2105 bx.sitofp(args[0].immediate(), llret_ty)
2107 bx.uitofp(args[0].immediate(), llret_ty)
2110 (Style::Float, Style::Int(out_is_signed)) => {
2111 return Ok(if out_is_signed {
2112 bx.fptosi(args[0].immediate(), llret_ty)
2114 bx.fptoui(args[0].immediate(), llret_ty)
2117 (Style::Float, Style::Float) => {
2118 return Ok(match in_width.cmp(&out_width) {
2119 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2120 Ordering::Equal => args[0].immediate(),
2121 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2124 _ => { /* Unsupported. Fallthrough. */ }
2128 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2135 macro_rules! arith {
2136 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2137 $(if name == sym::$name {
2138 match in_elem.kind {
2139 $($(ty::$p(_))|* => {
2140 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2145 "unsupported operation on `{}` with element `{}`",
2152 simd_add: Uint, Int => add, Float => fadd;
2153 simd_sub: Uint, Int => sub, Float => fsub;
2154 simd_mul: Uint, Int => mul, Float => fmul;
2155 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2156 simd_rem: Uint => urem, Int => srem, Float => frem;
2157 simd_shl: Uint, Int => shl;
2158 simd_shr: Uint => lshr, Int => ashr;
2159 simd_and: Uint, Int => and;
2160 simd_or: Uint, Int => or;
2161 simd_xor: Uint, Int => xor;
2162 simd_fmax: Float => maxnum;
2163 simd_fmin: Float => minnum;
2167 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2168 let lhs = args[0].immediate();
2169 let rhs = args[1].immediate();
2170 let is_add = name == sym::simd_saturating_add;
2171 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2172 let (signed, elem_width, elem_ty) = match in_elem.kind {
2173 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2174 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2177 "expected element type `{}` of vector type `{}` \
2178 to be a signed or unsigned integer type",
2179 arg_tys[0].simd_type(tcx),
2184 let llvm_intrinsic = &format!(
2185 "llvm.{}{}.sat.v{}i{}",
2186 if signed { 's' } else { 'u' },
2187 if is_add { "add" } else { "sub" },
2191 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2193 let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2194 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2195 let v = bx.call(f, &[lhs, rhs], None);
2199 span_bug!(span, "unknown SIMD intrinsic");
2202 // Returns the width of an int Ty, and if it's signed or not
2203 // Returns None if the type is not an integer
2204 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2206 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2208 ty::Int(t) => Some((
2210 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2211 ast::IntTy::I8 => 8,
2212 ast::IntTy::I16 => 16,
2213 ast::IntTy::I32 => 32,
2214 ast::IntTy::I64 => 64,
2215 ast::IntTy::I128 => 128,
2219 ty::Uint(t) => Some((
2221 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2222 ast::UintTy::U8 => 8,
2223 ast::UintTy::U16 => 16,
2224 ast::UintTy::U32 => 32,
2225 ast::UintTy::U64 => 64,
2226 ast::UintTy::U128 => 128,
2234 // Returns the width of a float Ty
2235 // Returns None if the type is not a float
2236 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2238 ty::Float(t) => Some(t.bit_width()),
2243 fn op_to_str_slice<'tcx>(op: &Operand<'tcx>) -> &'tcx str {
2244 Operand::value_from_const(op).try_to_str_slice().expect("Value is &str")
2247 fn op_to_u32<'tcx>(op: &Operand<'tcx>) -> u32 {
2248 Operand::scalar_from_const(op).to_u32().expect("Scalar is u32")
2251 fn op_to_u64<'tcx>(op: &Operand<'tcx>) -> u64 {
2252 Operand::scalar_from_const(op).to_u64().expect("Scalar is u64")