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::ExprKind;
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 if self.tcx.sess.opts.debugging_opts.instrument_coverage {
97 // If the intrinsic is from the local MIR, add the coverage information to the Codegen
98 // context, to be encoded into the local crate's coverage map.
99 if caller_instance.def_id().is_local() {
100 // FIXME(richkadel): Make sure to add coverage analysis tests on a crate with
101 // external crate dependencies, where:
102 // 1. Both binary and dependent crates are compiled with `-Zinstrument-coverage`
103 // 2. Only binary is compiled with `-Zinstrument-coverage`
104 // 3. Only dependent crates are compiled with `-Zinstrument-coverage`
106 sym::count_code_region => {
107 use coverage::count_code_region_args::*;
108 self.add_counter_region(
110 op_to_u64(&args[FUNCTION_SOURCE_HASH]),
111 op_to_u32(&args[COUNTER_ID]),
112 op_to_u32(&args[START_BYTE_POS]),
113 op_to_u32(&args[END_BYTE_POS]),
116 sym::coverage_counter_add | sym::coverage_counter_subtract => {
117 use coverage::coverage_counter_expression_args::*;
118 self.add_counter_expression_region(
120 op_to_u32(&args[EXPRESSION_ID]),
121 op_to_u32(&args[LEFT_ID]),
122 if intrinsic == sym::coverage_counter_add {
127 op_to_u32(&args[RIGHT_ID]),
128 op_to_u32(&args[START_BYTE_POS]),
129 op_to_u32(&args[END_BYTE_POS]),
132 sym::coverage_unreachable => {
133 use coverage::coverage_unreachable_args::*;
134 self.add_unreachable_region(
136 op_to_u32(&args[START_BYTE_POS]),
137 op_to_u32(&args[END_BYTE_POS]),
144 // Only the `count_code_region` coverage intrinsic is translated into an actual LLVM
145 // intrinsic call (local or not); otherwise, set `is_codegen_intrinsic` to `false`.
147 sym::coverage_counter_add
148 | sym::coverage_counter_subtract
149 | sym::coverage_unreachable => {
150 is_codegen_intrinsic = false;
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 // FIXME(richkadel): The current implementation assumes the MIR for the given
219 // caller_instance represents a single function. Validate and/or correct if inlining
220 // and/or monomorphization invalidates these assumptions.
221 let coverageinfo = tcx.coverageinfo(caller_instance.def_id());
222 let mangled_fn = tcx.symbol_name(caller_instance);
223 let (mangled_fn_name, _len_val) = self.const_str(Symbol::intern(mangled_fn.name));
224 let num_counters = self.const_u32(coverageinfo.num_counters);
225 use coverage::count_code_region_args::*;
226 let hash = args[FUNCTION_SOURCE_HASH].immediate();
227 let index = args[COUNTER_ID].immediate();
229 "translating Rust intrinsic `count_code_region()` to LLVM intrinsic: \
230 instrprof.increment(fn_name={}, hash={:?}, num_counters={:?}, index={:?})",
231 mangled_fn.name, hash, num_counters, index,
233 self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
235 sym::va_start => self.va_start(args[0].immediate()),
236 sym::va_end => self.va_end(args[0].immediate()),
238 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
239 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
242 match fn_abi.ret.layout.abi {
243 abi::Abi::Scalar(ref scalar) => {
245 Primitive::Int(..) => {
246 if self.cx().size_of(ret_ty).bytes() < 4 {
247 // `va_arg` should not be called on a integer type
248 // less than 4 bytes in length. If it is, promote
249 // the integer to a `i32` and truncate the result
250 // back to the smaller type.
251 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
252 self.trunc(promoted_result, llret_ty)
254 emit_va_arg(self, args[0], ret_ty)
257 Primitive::F64 | Primitive::Pointer => {
258 emit_va_arg(self, args[0], ret_ty)
260 // `va_arg` should never be used with the return type f32.
261 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
264 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
267 sym::size_of_val => {
268 let tp_ty = substs.type_at(0);
269 if let OperandValue::Pair(_, meta) = args[0].val {
270 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
273 self.const_usize(self.size_of(tp_ty).bytes())
276 sym::min_align_of_val => {
277 let tp_ty = substs.type_at(0);
278 if let OperandValue::Pair(_, meta) = args[0].val {
279 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
282 self.const_usize(self.align_of(tp_ty).bytes())
291 | sym::variant_count => {
294 .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
296 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
303 let ptr = args[0].immediate();
304 let offset = args[1].immediate();
305 self.inbounds_gep(ptr, &[offset])
307 sym::arith_offset => {
308 let ptr = args[0].immediate();
309 let offset = args[1].immediate();
310 self.gep(ptr, &[offset])
313 sym::copy_nonoverlapping => {
337 sym::write_bytes => {
349 sym::volatile_copy_nonoverlapping_memory => {
361 sym::volatile_copy_memory => {
373 sym::volatile_set_memory => {
384 sym::volatile_load | sym::unaligned_volatile_load => {
385 let tp_ty = substs.type_at(0);
386 let mut ptr = args[0].immediate();
387 if let PassMode::Cast(ty) = fn_abi.ret.mode {
388 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
390 let load = self.volatile_load(ptr);
391 let align = if name == sym::unaligned_volatile_load {
394 self.align_of(tp_ty).bytes() as u32
397 llvm::LLVMSetAlignment(load, align);
399 to_immediate(self, load, self.layout_of(tp_ty))
401 sym::volatile_store => {
402 let dst = args[0].deref(self.cx());
403 args[1].val.volatile_store(self, dst);
406 sym::unaligned_volatile_store => {
407 let dst = args[0].deref(self.cx());
408 args[1].val.unaligned_volatile_store(self, dst);
411 sym::prefetch_read_data
412 | sym::prefetch_write_data
413 | sym::prefetch_read_instruction
414 | sym::prefetch_write_instruction => {
415 let expect = self.get_intrinsic(&("llvm.prefetch"));
416 let (rw, cache_type) = match name {
417 sym::prefetch_read_data => (0, 1),
418 sym::prefetch_write_data => (1, 1),
419 sym::prefetch_read_instruction => (0, 0),
420 sym::prefetch_write_instruction => (1, 0),
429 self.const_i32(cache_type),
441 | sym::add_with_overflow
442 | sym::sub_with_overflow
443 | sym::mul_with_overflow
457 | sym::saturating_add
458 | sym::saturating_sub => {
460 match int_type_width_signed(ty, self) {
461 Some((width, signed)) => match name {
462 sym::ctlz | sym::cttz => {
463 let y = self.const_bool(false);
464 let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
465 self.call(llfn, &[args[0].immediate(), y], None)
467 sym::ctlz_nonzero | sym::cttz_nonzero => {
468 let y = self.const_bool(true);
469 let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
470 let llfn = self.get_intrinsic(llvm_name);
471 self.call(llfn, &[args[0].immediate(), y], None)
473 sym::ctpop => self.call(
474 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
475 &[args[0].immediate()],
480 args[0].immediate() // byte swap a u8/i8 is just a no-op
483 self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
484 &[args[0].immediate()],
489 sym::bitreverse => self.call(
490 self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
491 &[args[0].immediate()],
494 sym::add_with_overflow
495 | sym::sub_with_overflow
496 | sym::mul_with_overflow => {
497 let intrinsic = format!(
498 "llvm.{}{}.with.overflow.i{}",
499 if signed { 's' } else { 'u' },
503 let llfn = self.get_intrinsic(&intrinsic);
505 // Convert `i1` to a `bool`, and write it to the out parameter
507 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
508 let val = self.extract_value(pair, 0);
509 let overflow = self.extract_value(pair, 1);
510 let overflow = self.zext(overflow, self.type_bool());
512 let dest = result.project_field(self, 0);
513 self.store(val, dest.llval, dest.align);
514 let dest = result.project_field(self, 1);
515 self.store(overflow, dest.llval, dest.align);
519 sym::wrapping_add => self.add(args[0].immediate(), args[1].immediate()),
520 sym::wrapping_sub => self.sub(args[0].immediate(), args[1].immediate()),
521 sym::wrapping_mul => self.mul(args[0].immediate(), args[1].immediate()),
524 self.exactsdiv(args[0].immediate(), args[1].immediate())
526 self.exactudiv(args[0].immediate(), args[1].immediate())
529 sym::unchecked_div => {
531 self.sdiv(args[0].immediate(), args[1].immediate())
533 self.udiv(args[0].immediate(), args[1].immediate())
536 sym::unchecked_rem => {
538 self.srem(args[0].immediate(), args[1].immediate())
540 self.urem(args[0].immediate(), args[1].immediate())
543 sym::unchecked_shl => self.shl(args[0].immediate(), args[1].immediate()),
544 sym::unchecked_shr => {
546 self.ashr(args[0].immediate(), args[1].immediate())
548 self.lshr(args[0].immediate(), args[1].immediate())
551 sym::unchecked_add => {
553 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
555 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
558 sym::unchecked_sub => {
560 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
562 self.unchecked_usub(args[0].immediate(), args[1].immediate())
565 sym::unchecked_mul => {
567 self.unchecked_smul(args[0].immediate(), args[1].immediate())
569 self.unchecked_umul(args[0].immediate(), args[1].immediate())
572 sym::rotate_left | sym::rotate_right => {
573 let is_left = name == sym::rotate_left;
574 let val = args[0].immediate();
575 let raw_shift = args[1].immediate();
576 // rotate = funnel shift with first two args the same
578 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
579 let llfn = self.get_intrinsic(llvm_name);
580 self.call(llfn, &[val, val, raw_shift], None)
582 sym::saturating_add | sym::saturating_sub => {
583 let is_add = name == sym::saturating_add;
584 let lhs = args[0].immediate();
585 let rhs = args[1].immediate();
586 let llvm_name = &format!(
588 if signed { 's' } else { 'u' },
589 if is_add { "add" } else { "sub" },
592 let llfn = self.get_intrinsic(llvm_name);
593 self.call(llfn, &[lhs, rhs], None)
598 span_invalid_monomorphization_error(
602 "invalid monomorphization of `{}` intrinsic: \
603 expected basic integer type, found `{}`",
611 sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
612 match float_type_width(arg_tys[0]) {
613 Some(_width) => match name {
614 sym::fadd_fast => self.fadd_fast(args[0].immediate(), args[1].immediate()),
615 sym::fsub_fast => self.fsub_fast(args[0].immediate(), args[1].immediate()),
616 sym::fmul_fast => self.fmul_fast(args[0].immediate(), args[1].immediate()),
617 sym::fdiv_fast => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
618 sym::frem_fast => self.frem_fast(args[0].immediate(), args[1].immediate()),
622 span_invalid_monomorphization_error(
626 "invalid monomorphization of `{}` intrinsic: \
627 expected basic float type, found `{}`",
636 sym::float_to_int_unchecked => {
637 if float_type_width(arg_tys[0]).is_none() {
638 span_invalid_monomorphization_error(
642 "invalid monomorphization of `float_to_int_unchecked` \
643 intrinsic: expected basic float type, \
650 let (width, signed) = match int_type_width_signed(ret_ty, self.cx) {
653 span_invalid_monomorphization_error(
657 "invalid monomorphization of `float_to_int_unchecked` \
658 intrinsic: expected basic integer type, \
667 self.fptosi(args[0].immediate(), self.cx.type_ix(width))
669 self.fptoui(args[0].immediate(), self.cx.type_ix(width))
673 sym::discriminant_value => {
674 if ret_ty.is_integral() {
675 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
677 span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
681 _ if name_str.starts_with("simd_") => {
682 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
687 // This requires that atomic intrinsics follow a specific naming pattern:
688 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
689 name if name_str.starts_with("atomic_") => {
690 use rustc_codegen_ssa::common::AtomicOrdering::*;
691 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
693 let split: Vec<&str> = name_str.split('_').collect();
695 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
696 let (order, failorder) = match split.len() {
697 2 => (SequentiallyConsistent, SequentiallyConsistent),
698 3 => match split[2] {
699 "unordered" => (Unordered, Unordered),
700 "relaxed" => (Monotonic, Monotonic),
701 "acq" => (Acquire, Acquire),
702 "rel" => (Release, Monotonic),
703 "acqrel" => (AcquireRelease, Acquire),
704 "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
705 "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
706 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
708 4 => match (split[2], split[3]) {
709 ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
710 ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
711 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
713 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
716 let invalid_monomorphization = |ty| {
717 span_invalid_monomorphization_error(
721 "invalid monomorphization of `{}` intrinsic: \
722 expected basic integer type, found `{}`",
729 "cxchg" | "cxchgweak" => {
730 let ty = substs.type_at(0);
731 if int_type_width_signed(ty, self).is_some() {
732 let weak = split[1] == "cxchgweak";
733 let pair = self.atomic_cmpxchg(
741 let val = self.extract_value(pair, 0);
742 let success = self.extract_value(pair, 1);
743 let success = self.zext(success, self.type_bool());
745 let dest = result.project_field(self, 0);
746 self.store(val, dest.llval, dest.align);
747 let dest = result.project_field(self, 1);
748 self.store(success, dest.llval, dest.align);
751 return invalid_monomorphization(ty);
756 let ty = substs.type_at(0);
757 if int_type_width_signed(ty, self).is_some() {
758 let size = self.size_of(ty);
759 self.atomic_load(args[0].immediate(), order, size)
761 return invalid_monomorphization(ty);
766 let ty = substs.type_at(0);
767 if int_type_width_signed(ty, self).is_some() {
768 let size = self.size_of(ty);
777 return invalid_monomorphization(ty);
782 self.atomic_fence(order, SynchronizationScope::CrossThread);
786 "singlethreadfence" => {
787 self.atomic_fence(order, SynchronizationScope::SingleThread);
791 // These are all AtomicRMW ops
793 let atom_op = match op {
794 "xchg" => AtomicRmwBinOp::AtomicXchg,
795 "xadd" => AtomicRmwBinOp::AtomicAdd,
796 "xsub" => AtomicRmwBinOp::AtomicSub,
797 "and" => AtomicRmwBinOp::AtomicAnd,
798 "nand" => AtomicRmwBinOp::AtomicNand,
799 "or" => AtomicRmwBinOp::AtomicOr,
800 "xor" => AtomicRmwBinOp::AtomicXor,
801 "max" => AtomicRmwBinOp::AtomicMax,
802 "min" => AtomicRmwBinOp::AtomicMin,
803 "umax" => AtomicRmwBinOp::AtomicUMax,
804 "umin" => AtomicRmwBinOp::AtomicUMin,
805 _ => self.sess().fatal("unknown atomic operation"),
808 let ty = substs.type_at(0);
809 if int_type_width_signed(ty, self).is_some() {
817 return invalid_monomorphization(ty);
823 sym::nontemporal_store => {
824 let dst = args[0].deref(self.cx());
825 args[1].val.nontemporal_store(self, dst);
829 sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
830 let a = args[0].immediate();
831 let b = args[1].immediate();
832 if name == sym::ptr_guaranteed_eq {
833 self.icmp(IntPredicate::IntEQ, a, b)
835 self.icmp(IntPredicate::IntNE, a, b)
839 sym::ptr_offset_from => {
840 let ty = substs.type_at(0);
841 let pointee_size = self.size_of(ty);
843 // This is the same sequence that Clang emits for pointer subtraction.
844 // It can be neither `nsw` nor `nuw` because the input is treated as
845 // unsigned but then the output is treated as signed, so neither works.
846 let a = args[0].immediate();
847 let b = args[1].immediate();
848 let a = self.ptrtoint(a, self.type_isize());
849 let b = self.ptrtoint(b, self.type_isize());
850 let d = self.sub(a, b);
851 let pointee_size = self.const_usize(pointee_size.bytes());
852 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
853 self.exactsdiv(d, pointee_size)
856 _ => bug!("unknown intrinsic '{}'", name),
859 if !fn_abi.ret.is_ignore() {
860 if let PassMode::Cast(ty) = fn_abi.ret.mode {
861 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
862 let ptr = self.pointercast(result.llval, ptr_llty);
863 self.store(llval, ptr, result.align);
865 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
867 .store(self, result);
872 fn abort(&mut self) {
873 let fnname = self.get_intrinsic(&("llvm.trap"));
874 self.call(fnname, &[], None);
877 fn assume(&mut self, val: Self::Value) {
878 let assume_intrinsic = self.get_intrinsic("llvm.assume");
879 self.call(assume_intrinsic, &[val], None);
882 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
883 let expect = self.get_intrinsic(&"llvm.expect.i1");
884 self.call(expect, &[cond, self.const_bool(expected)], None)
887 fn sideeffect(&mut self) {
888 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
889 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
890 self.call(fnname, &[], None);
894 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
895 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
896 self.call(intrinsic, &[va_list], None)
899 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
900 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
901 self.call(intrinsic, &[va_list], None)
906 bx: &mut Builder<'a, 'll, 'tcx>,
914 let (size, align) = bx.size_and_align_of(ty);
915 let size = bx.mul(bx.const_usize(size.bytes()), count);
916 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
918 bx.memmove(dst, align, src, align, size, flags);
920 bx.memcpy(dst, align, src, align, size, flags);
925 bx: &mut Builder<'a, 'll, 'tcx>,
932 let (size, align) = bx.size_and_align_of(ty);
933 let size = bx.mul(bx.const_usize(size.bytes()), count);
934 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
935 bx.memset(dst, val, size, align, flags);
939 bx: &mut Builder<'a, 'll, 'tcx>,
940 try_func: &'ll Value,
942 catch_func: &'ll Value,
945 if bx.sess().panic_strategy() == PanicStrategy::Abort {
946 bx.call(try_func, &[data], None);
947 // Return 0 unconditionally from the intrinsic call;
948 // we can never unwind.
949 let ret_align = bx.tcx().data_layout.i32_align.abi;
950 bx.store(bx.const_i32(0), dest, ret_align);
951 } else if wants_msvc_seh(bx.sess()) {
952 codegen_msvc_try(bx, try_func, data, catch_func, dest);
954 codegen_gnu_try(bx, try_func, data, catch_func, dest);
958 // MSVC's definition of the `rust_try` function.
960 // This implementation uses the new exception handling instructions in LLVM
961 // which have support in LLVM for SEH on MSVC targets. Although these
962 // instructions are meant to work for all targets, as of the time of this
963 // writing, however, LLVM does not recommend the usage of these new instructions
964 // as the old ones are still more optimized.
966 bx: &mut Builder<'a, 'll, 'tcx>,
967 try_func: &'ll Value,
969 catch_func: &'ll Value,
972 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
973 bx.set_personality_fn(bx.eh_personality());
976 let mut normal = bx.build_sibling_block("normal");
977 let mut catchswitch = bx.build_sibling_block("catchswitch");
978 let mut catchpad = bx.build_sibling_block("catchpad");
979 let mut caught = bx.build_sibling_block("caught");
981 let try_func = llvm::get_param(bx.llfn(), 0);
982 let data = llvm::get_param(bx.llfn(), 1);
983 let catch_func = llvm::get_param(bx.llfn(), 2);
985 // We're generating an IR snippet that looks like:
987 // declare i32 @rust_try(%try_func, %data, %catch_func) {
988 // %slot = alloca u8*
989 // invoke %try_func(%data) to label %normal unwind label %catchswitch
995 // %cs = catchswitch within none [%catchpad] unwind to caller
998 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
1000 // call %catch_func(%data, %ptr)
1001 // catchret from %tok to label %caught
1007 // This structure follows the basic usage of throw/try/catch in LLVM.
1008 // For example, compile this C++ snippet to see what LLVM generates:
1010 // #include <stdint.h>
1012 // struct rust_panic {
1013 // rust_panic(const rust_panic&);
1020 // void (*try_func)(void*),
1022 // void (*catch_func)(void*, void*) noexcept
1027 // } catch(rust_panic& a) {
1028 // catch_func(data, &a);
1033 // More information can be found in libstd's seh.rs implementation.
1034 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
1035 let slot = bx.alloca(bx.type_i8p(), ptr_align);
1036 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
1038 normal.ret(bx.const_i32(0));
1040 let cs = catchswitch.catch_switch(None, None, 1);
1041 catchswitch.add_handler(cs, catchpad.llbb());
1043 // We can't use the TypeDescriptor defined in libpanic_unwind because it
1044 // might be in another DLL and the SEH encoding only supports specifying
1045 // a TypeDescriptor from the current module.
1047 // However this isn't an issue since the MSVC runtime uses string
1048 // comparison on the type name to match TypeDescriptors rather than
1049 // pointer equality.
1051 // So instead we generate a new TypeDescriptor in each module that uses
1052 // `try` and let the linker merge duplicate definitions in the same
1055 // When modifying, make sure that the type_name string exactly matches
1056 // the one used in src/libpanic_unwind/seh.rs.
1057 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
1058 let type_name = bx.const_bytes(b"rust_panic\0");
1060 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
1061 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
1063 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1064 llvm::SetUniqueComdat(bx.llmod, tydesc);
1065 llvm::LLVMSetInitializer(tydesc, type_info);
1068 // The flag value of 8 indicates that we are catching the exception by
1069 // reference instead of by value. We can't use catch by value because
1070 // that requires copying the exception object, which we don't support
1071 // since our exception object effectively contains a Box.
1073 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1074 let flags = bx.const_i32(8);
1075 let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
1076 let ptr = catchpad.load(slot, ptr_align);
1077 catchpad.call(catch_func, &[data, ptr], Some(&funclet));
1079 catchpad.catch_ret(&funclet, caught.llbb());
1081 caught.ret(bx.const_i32(1));
1084 // Note that no invoke is used here because by definition this function
1085 // can't panic (that's what it's catching).
1086 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1087 let i32_align = bx.tcx().data_layout.i32_align.abi;
1088 bx.store(ret, dest, i32_align);
1091 // Definition of the standard `try` function for Rust using the GNU-like model
1092 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1095 // This codegen is a little surprising because we always call a shim
1096 // function instead of inlining the call to `invoke` manually here. This is done
1097 // because in LLVM we're only allowed to have one personality per function
1098 // definition. The call to the `try` intrinsic is being inlined into the
1099 // function calling it, and that function may already have other personality
1100 // functions in play. By calling a shim we're guaranteed that our shim will have
1101 // the right personality function.
1103 bx: &mut Builder<'a, 'll, 'tcx>,
1104 try_func: &'ll Value,
1106 catch_func: &'ll Value,
1109 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1110 // Codegens the shims described above:
1113 // invoke %try_func(%data) normal %normal unwind %catch
1119 // (%ptr, _) = landingpad
1120 // call %catch_func(%data, %ptr)
1125 let mut then = bx.build_sibling_block("then");
1126 let mut catch = bx.build_sibling_block("catch");
1128 let try_func = llvm::get_param(bx.llfn(), 0);
1129 let data = llvm::get_param(bx.llfn(), 1);
1130 let catch_func = llvm::get_param(bx.llfn(), 2);
1131 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1132 then.ret(bx.const_i32(0));
1134 // Type indicator for the exception being thrown.
1136 // The first value in this tuple is a pointer to the exception object
1137 // being thrown. The second value is a "selector" indicating which of
1138 // the landing pad clauses the exception's type had been matched to.
1139 // rust_try ignores the selector.
1140 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1141 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1142 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1144 let tydesc = bx.get_static(tydesc);
1145 bx.bitcast(tydesc, bx.type_i8p())
1147 None => bx.const_null(bx.type_i8p()),
1149 catch.add_clause(vals, tydesc);
1150 let ptr = catch.extract_value(vals, 0);
1151 catch.call(catch_func, &[data, ptr], None);
1152 catch.ret(bx.const_i32(1));
1155 // Note that no invoke is used here because by definition this function
1156 // can't panic (that's what it's catching).
1157 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1158 let i32_align = bx.tcx().data_layout.i32_align.abi;
1159 bx.store(ret, dest, i32_align);
1162 // Helper function to give a Block to a closure to codegen a shim function.
1163 // This is currently primarily used for the `try` intrinsic functions above.
1164 fn gen_fn<'ll, 'tcx>(
1165 cx: &CodegenCx<'ll, 'tcx>,
1167 inputs: Vec<Ty<'tcx>>,
1169 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1171 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1175 hir::Unsafety::Unsafe,
1178 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1179 let llfn = cx.declare_fn(name, &fn_abi);
1180 cx.set_frame_pointer_elimination(llfn);
1181 cx.apply_target_cpu_attr(llfn);
1182 // FIXME(eddyb) find a nicer way to do this.
1183 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1184 let bx = Builder::new_block(cx, llfn, "entry-block");
1189 // Helper function used to get a handle to the `__rust_try` function used to
1190 // catch exceptions.
1192 // This function is only generated once and is then cached.
1193 fn get_rust_try_fn<'ll, 'tcx>(
1194 cx: &CodegenCx<'ll, 'tcx>,
1195 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1197 if let Some(llfn) = cx.rust_try_fn.get() {
1201 // Define the type up front for the signature of the rust_try function.
1203 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1204 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1208 hir::Unsafety::Unsafe,
1211 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1212 [i8p, i8p].iter().cloned(),
1215 hir::Unsafety::Unsafe,
1218 let output = tcx.types.i32;
1219 let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1220 cx.rust_try_fn.set(Some(rust_try));
1224 fn generic_simd_intrinsic(
1225 bx: &mut Builder<'a, 'll, 'tcx>,
1227 callee_ty: Ty<'tcx>,
1228 args: &[OperandRef<'tcx, &'ll Value>],
1230 llret_ty: &'ll Type,
1232 ) -> Result<&'ll Value, ()> {
1233 // macros for error handling:
1234 macro_rules! emit_error {
1238 ($msg: tt, $($fmt: tt)*) => {
1239 span_invalid_monomorphization_error(
1241 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1246 macro_rules! return_error {
1249 emit_error!($($fmt)*);
1255 macro_rules! require {
1256 ($cond: expr, $($fmt: tt)*) => {
1258 return_error!($($fmt)*);
1263 macro_rules! require_simd {
1264 ($ty: expr, $position: expr) => {
1265 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1271 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1272 let arg_tys = sig.inputs();
1273 let name_str = &*name.as_str();
1275 if name == sym::simd_select_bitmask {
1276 let in_ty = arg_tys[0];
1277 let m_len = match in_ty.kind {
1278 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1279 // of intentional as there's not currently a use case for that.
1280 ty::Int(i) => i.bit_width().unwrap(),
1281 ty::Uint(i) => i.bit_width().unwrap(),
1282 _ => return_error!("`{}` is not an integral type", in_ty),
1284 require_simd!(arg_tys[1], "argument");
1285 let v_len = arg_tys[1].simd_size(tcx);
1288 "mismatched lengths: mask length `{}` != other vector length `{}`",
1292 let i1 = bx.type_i1();
1293 let i1xn = bx.type_vector(i1, m_len);
1294 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1295 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1298 // every intrinsic below takes a SIMD vector as its first argument
1299 require_simd!(arg_tys[0], "input");
1300 let in_ty = arg_tys[0];
1301 let in_elem = arg_tys[0].simd_type(tcx);
1302 let in_len = arg_tys[0].simd_size(tcx);
1304 let comparison = match name {
1305 sym::simd_eq => Some(hir::BinOpKind::Eq),
1306 sym::simd_ne => Some(hir::BinOpKind::Ne),
1307 sym::simd_lt => Some(hir::BinOpKind::Lt),
1308 sym::simd_le => Some(hir::BinOpKind::Le),
1309 sym::simd_gt => Some(hir::BinOpKind::Gt),
1310 sym::simd_ge => Some(hir::BinOpKind::Ge),
1314 if let Some(cmp_op) = comparison {
1315 require_simd!(ret_ty, "return");
1317 let out_len = ret_ty.simd_size(tcx);
1320 "expected return type with length {} (same as input type `{}`), \
1321 found `{}` with length {}",
1328 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1329 "expected return type with integer elements, found `{}` with non-integer `{}`",
1331 ret_ty.simd_type(tcx)
1334 return Ok(compare_simd_types(
1336 args[0].immediate(),
1337 args[1].immediate(),
1344 if name_str.starts_with("simd_shuffle") {
1345 let n: u64 = name_str["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1346 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1349 require_simd!(ret_ty, "return");
1351 let out_len = ret_ty.simd_size(tcx);
1354 "expected return type of length {}, found `{}` with length {}",
1360 in_elem == ret_ty.simd_type(tcx),
1361 "expected return element type `{}` (element of input `{}`), \
1362 found `{}` with element type `{}`",
1366 ret_ty.simd_type(tcx)
1369 let total_len = u128::from(in_len) * 2;
1371 let vector = args[2].immediate();
1373 let indices: Option<Vec<_>> = (0..n)
1376 let val = bx.const_get_elt(vector, i as u64);
1377 match bx.const_to_opt_u128(val, true) {
1379 emit_error!("shuffle index #{} is not a constant", arg_idx);
1382 Some(idx) if idx >= total_len => {
1384 "shuffle index #{} is out of bounds (limit {})",
1390 Some(idx) => Some(bx.const_i32(idx as i32)),
1394 let indices = match indices {
1396 None => return Ok(bx.const_null(llret_ty)),
1399 return Ok(bx.shuffle_vector(
1400 args[0].immediate(),
1401 args[1].immediate(),
1402 bx.const_vector(&indices),
1406 if name == sym::simd_insert {
1408 in_elem == arg_tys[2],
1409 "expected inserted type `{}` (element of input `{}`), found `{}`",
1414 return Ok(bx.insert_element(
1415 args[0].immediate(),
1416 args[2].immediate(),
1417 args[1].immediate(),
1420 if name == sym::simd_extract {
1423 "expected return type `{}` (element of input `{}`), found `{}`",
1428 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1431 if name == sym::simd_select {
1432 let m_elem_ty = in_elem;
1434 require_simd!(arg_tys[1], "argument");
1435 let v_len = arg_tys[1].simd_size(tcx);
1438 "mismatched lengths: mask length `{}` != other vector length `{}`",
1442 match m_elem_ty.kind {
1444 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1446 // truncate the mask to a vector of i1s
1447 let i1 = bx.type_i1();
1448 let i1xn = bx.type_vector(i1, m_len as u64);
1449 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1450 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1453 if name == sym::simd_bitmask {
1454 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1455 // vector mask and returns an unsigned integer containing the most
1456 // significant bit (MSB) of each lane.
1458 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1460 let expected_int_bits = in_len.max(8);
1462 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1463 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1466 // Integer vector <i{in_bitwidth} x in_len>:
1467 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1469 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1472 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1475 "vector argument `{}`'s element type `{}`, expected integer element type",
1481 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1484 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1487 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1488 // Truncate vector to an <i1 x N>
1489 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1490 // Bitcast <i1 x N> to iN:
1491 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1492 // Zero-extend iN to the bitmask type:
1493 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1496 fn simd_simple_float_intrinsic(
1498 in_elem: &::rustc_middle::ty::TyS<'_>,
1499 in_ty: &::rustc_middle::ty::TyS<'_>,
1501 bx: &mut Builder<'a, 'll, 'tcx>,
1503 args: &[OperandRef<'tcx, &'ll Value>],
1504 ) -> Result<&'ll Value, ()> {
1505 macro_rules! emit_error {
1509 ($msg: tt, $($fmt: tt)*) => {
1510 span_invalid_monomorphization_error(
1512 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1516 macro_rules! return_error {
1519 emit_error!($($fmt)*);
1524 let ety = match in_elem.kind {
1525 ty::Float(f) if f.bit_width() == 32 => {
1526 if in_len < 2 || in_len > 16 {
1528 "unsupported floating-point vector `{}` with length `{}` \
1529 out-of-range [2, 16]",
1536 ty::Float(f) if f.bit_width() == 64 => {
1537 if in_len < 2 || in_len > 8 {
1539 "unsupported floating-point vector `{}` with length `{}` \
1540 out-of-range [2, 8]",
1549 "unsupported element type `{}` of floating-point vector `{}`",
1555 return_error!("`{}` is not a floating-point type", in_ty);
1559 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1560 let intrinsic = bx.get_intrinsic(&llvm_name);
1562 bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1563 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1568 sym::simd_fsqrt => {
1569 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1572 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1575 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1578 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1580 sym::simd_floor => {
1581 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1584 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1587 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1589 sym::simd_fexp2 => {
1590 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1592 sym::simd_flog10 => {
1593 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1595 sym::simd_flog2 => {
1596 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1599 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1601 sym::simd_fpowi => {
1602 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1605 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1608 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1610 _ => { /* fallthrough */ }
1614 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1615 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1616 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1617 let p0s: String = "p0".repeat(no_pointers);
1618 match elem_ty.kind {
1619 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1620 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1621 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1622 _ => unreachable!(),
1627 cx: &CodegenCx<'ll, '_>,
1630 mut no_pointers: usize,
1632 // FIXME: use cx.layout_of(ty).llvm_type() ?
1633 let mut elem_ty = match elem_ty.kind {
1634 ty::Int(v) => cx.type_int_from_ty(v),
1635 ty::Uint(v) => cx.type_uint_from_ty(v),
1636 ty::Float(v) => cx.type_float_from_ty(v),
1637 _ => unreachable!(),
1639 while no_pointers > 0 {
1640 elem_ty = cx.type_ptr_to(elem_ty);
1643 cx.type_vector(elem_ty, vec_len)
1646 if name == sym::simd_gather {
1647 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1648 // mask: <N x i{M}>) -> <N x T>
1649 // * N: number of elements in the input vectors
1650 // * T: type of the element to load
1651 // * M: any integer width is supported, will be truncated to i1
1653 // All types must be simd vector types
1654 require_simd!(in_ty, "first");
1655 require_simd!(arg_tys[1], "second");
1656 require_simd!(arg_tys[2], "third");
1657 require_simd!(ret_ty, "return");
1659 // Of the same length:
1661 in_len == arg_tys[1].simd_size(tcx),
1662 "expected {} argument with length {} (same as input type `{}`), \
1663 found `{}` with length {}",
1668 arg_tys[1].simd_size(tcx)
1671 in_len == arg_tys[2].simd_size(tcx),
1672 "expected {} argument with length {} (same as input type `{}`), \
1673 found `{}` with length {}",
1678 arg_tys[2].simd_size(tcx)
1681 // The return type must match the first argument type
1682 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1684 // This counts how many pointers
1685 fn ptr_count(t: Ty<'_>) -> usize {
1687 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1693 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1695 ty::RawPtr(p) => non_ptr(p.ty),
1700 // The second argument must be a simd vector with an element type that's a pointer
1701 // to the element type of the first argument
1702 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1703 ty::RawPtr(p) if p.ty == in_elem => {
1704 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1709 "expected element type `{}` of second argument `{}` \
1710 to be a pointer to the element type `{}` of the first \
1711 argument `{}`, found `{}` != `*_ {}`",
1712 arg_tys[1].simd_type(tcx),
1716 arg_tys[1].simd_type(tcx),
1722 assert!(pointer_count > 0);
1723 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1724 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1726 // The element type of the third argument must be a signed integer type of any width:
1727 match arg_tys[2].simd_type(tcx).kind {
1732 "expected element type `{}` of third argument `{}` \
1733 to be a signed integer type",
1734 arg_tys[2].simd_type(tcx),
1740 // Alignment of T, must be a constant integer value:
1741 let alignment_ty = bx.type_i32();
1742 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1744 // Truncate the mask vector to a vector of i1s:
1745 let (mask, mask_ty) = {
1746 let i1 = bx.type_i1();
1747 let i1xn = bx.type_vector(i1, in_len);
1748 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1751 // Type of the vector of pointers:
1752 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1753 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1755 // Type of the vector of elements:
1756 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1757 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1759 let llvm_intrinsic =
1760 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1761 let f = bx.declare_cfn(
1764 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1768 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1769 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1773 if name == sym::simd_scatter {
1774 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1775 // mask: <N x i{M}>) -> ()
1776 // * N: number of elements in the input vectors
1777 // * T: type of the element to load
1778 // * M: any integer width is supported, will be truncated to i1
1780 // All types must be simd vector types
1781 require_simd!(in_ty, "first");
1782 require_simd!(arg_tys[1], "second");
1783 require_simd!(arg_tys[2], "third");
1785 // Of the same length:
1787 in_len == arg_tys[1].simd_size(tcx),
1788 "expected {} argument with length {} (same as input type `{}`), \
1789 found `{}` with length {}",
1794 arg_tys[1].simd_size(tcx)
1797 in_len == arg_tys[2].simd_size(tcx),
1798 "expected {} argument with length {} (same as input type `{}`), \
1799 found `{}` with length {}",
1804 arg_tys[2].simd_size(tcx)
1807 // This counts how many pointers
1808 fn ptr_count(t: Ty<'_>) -> usize {
1810 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1816 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1818 ty::RawPtr(p) => non_ptr(p.ty),
1823 // The second argument must be a simd vector with an element type that's a pointer
1824 // to the element type of the first argument
1825 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1826 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1827 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1832 "expected element type `{}` of second argument `{}` \
1833 to be a pointer to the element type `{}` of the first \
1834 argument `{}`, found `{}` != `*mut {}`",
1835 arg_tys[1].simd_type(tcx),
1839 arg_tys[1].simd_type(tcx),
1845 assert!(pointer_count > 0);
1846 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1847 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1849 // The element type of the third argument must be a signed integer type of any width:
1850 match arg_tys[2].simd_type(tcx).kind {
1855 "expected element type `{}` of third argument `{}` \
1856 to be a signed integer type",
1857 arg_tys[2].simd_type(tcx),
1863 // Alignment of T, must be a constant integer value:
1864 let alignment_ty = bx.type_i32();
1865 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1867 // Truncate the mask vector to a vector of i1s:
1868 let (mask, mask_ty) = {
1869 let i1 = bx.type_i1();
1870 let i1xn = bx.type_vector(i1, in_len);
1871 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1874 let ret_t = bx.type_void();
1876 // Type of the vector of pointers:
1877 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1878 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1880 // Type of the vector of elements:
1881 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1882 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1884 let llvm_intrinsic =
1885 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1886 let f = bx.declare_cfn(
1888 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1890 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1891 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1895 macro_rules! arith_red {
1896 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1897 $identity:expr) => {
1898 if name == sym::$name {
1901 "expected return type `{}` (element of input `{}`), found `{}`",
1906 return match in_elem.kind {
1907 ty::Int(_) | ty::Uint(_) => {
1908 let r = bx.$integer_reduce(args[0].immediate());
1910 // if overflow occurs, the result is the
1911 // mathematical result modulo 2^n:
1912 Ok(bx.$op(args[1].immediate(), r))
1914 Ok(bx.$integer_reduce(args[0].immediate()))
1918 let acc = if $ordered {
1919 // ordered arithmetic reductions take an accumulator
1922 // unordered arithmetic reductions use the identity accumulator
1923 match f.bit_width() {
1924 32 => bx.const_real(bx.type_f32(), $identity),
1925 64 => bx.const_real(bx.type_f64(), $identity),
1928 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1937 Ok(bx.$float_reduce(acc, args[0].immediate()))
1940 "unsupported {} from `{}` with element `{}` to `{}`",
1951 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1952 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1954 simd_reduce_add_unordered: vector_reduce_add,
1955 vector_reduce_fadd_fast,
1961 simd_reduce_mul_unordered: vector_reduce_mul,
1962 vector_reduce_fmul_fast,
1968 macro_rules! minmax_red {
1969 ($name:ident: $int_red:ident, $float_red:ident) => {
1970 if name == sym::$name {
1973 "expected return type `{}` (element of input `{}`), found `{}`",
1978 return match in_elem.kind {
1979 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1980 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1981 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1983 "unsupported {} from `{}` with element `{}` to `{}`",
1994 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1995 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1997 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1998 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
2000 macro_rules! bitwise_red {
2001 ($name:ident : $red:ident, $boolean:expr) => {
2002 if name == sym::$name {
2003 let input = if !$boolean {
2006 "expected return type `{}` (element of input `{}`), found `{}`",
2013 match in_elem.kind {
2014 ty::Int(_) | ty::Uint(_) => {}
2016 "unsupported {} from `{}` with element `{}` to `{}`",
2024 // boolean reductions operate on vectors of i1s:
2025 let i1 = bx.type_i1();
2026 let i1xn = bx.type_vector(i1, in_len as u64);
2027 bx.trunc(args[0].immediate(), i1xn)
2029 return match in_elem.kind {
2030 ty::Int(_) | ty::Uint(_) => {
2031 let r = bx.$red(input);
2032 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2035 "unsupported {} from `{}` with element `{}` to `{}`",
2046 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2047 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2048 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2049 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2050 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2052 if name == sym::simd_cast {
2053 require_simd!(ret_ty, "return");
2054 let out_len = ret_ty.simd_size(tcx);
2057 "expected return type with length {} (same as input type `{}`), \
2058 found `{}` with length {}",
2064 // casting cares about nominal type, not just structural type
2065 let out_elem = ret_ty.simd_type(tcx);
2067 if in_elem == out_elem {
2068 return Ok(args[0].immediate());
2073 Int(/* is signed? */ bool),
2077 let (in_style, in_width) = match in_elem.kind {
2078 // vectors of pointer-sized integers should've been
2079 // disallowed before here, so this unwrap is safe.
2080 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2081 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2082 ty::Float(f) => (Style::Float, f.bit_width()),
2083 _ => (Style::Unsupported, 0),
2085 let (out_style, out_width) = match out_elem.kind {
2086 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2087 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2088 ty::Float(f) => (Style::Float, f.bit_width()),
2089 _ => (Style::Unsupported, 0),
2092 match (in_style, out_style) {
2093 (Style::Int(in_is_signed), Style::Int(_)) => {
2094 return Ok(match in_width.cmp(&out_width) {
2095 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2096 Ordering::Equal => args[0].immediate(),
2099 bx.sext(args[0].immediate(), llret_ty)
2101 bx.zext(args[0].immediate(), llret_ty)
2106 (Style::Int(in_is_signed), Style::Float) => {
2107 return Ok(if in_is_signed {
2108 bx.sitofp(args[0].immediate(), llret_ty)
2110 bx.uitofp(args[0].immediate(), llret_ty)
2113 (Style::Float, Style::Int(out_is_signed)) => {
2114 return Ok(if out_is_signed {
2115 bx.fptosi(args[0].immediate(), llret_ty)
2117 bx.fptoui(args[0].immediate(), llret_ty)
2120 (Style::Float, Style::Float) => {
2121 return Ok(match in_width.cmp(&out_width) {
2122 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2123 Ordering::Equal => args[0].immediate(),
2124 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2127 _ => { /* Unsupported. Fallthrough. */ }
2131 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2138 macro_rules! arith {
2139 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2140 $(if name == sym::$name {
2141 match in_elem.kind {
2142 $($(ty::$p(_))|* => {
2143 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2148 "unsupported operation on `{}` with element `{}`",
2155 simd_add: Uint, Int => add, Float => fadd;
2156 simd_sub: Uint, Int => sub, Float => fsub;
2157 simd_mul: Uint, Int => mul, Float => fmul;
2158 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2159 simd_rem: Uint => urem, Int => srem, Float => frem;
2160 simd_shl: Uint, Int => shl;
2161 simd_shr: Uint => lshr, Int => ashr;
2162 simd_and: Uint, Int => and;
2163 simd_or: Uint, Int => or;
2164 simd_xor: Uint, Int => xor;
2165 simd_fmax: Float => maxnum;
2166 simd_fmin: Float => minnum;
2170 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2171 let lhs = args[0].immediate();
2172 let rhs = args[1].immediate();
2173 let is_add = name == sym::simd_saturating_add;
2174 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2175 let (signed, elem_width, elem_ty) = match in_elem.kind {
2176 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2177 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2180 "expected element type `{}` of vector type `{}` \
2181 to be a signed or unsigned integer type",
2182 arg_tys[0].simd_type(tcx),
2187 let llvm_intrinsic = &format!(
2188 "llvm.{}{}.sat.v{}i{}",
2189 if signed { 's' } else { 'u' },
2190 if is_add { "add" } else { "sub" },
2194 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2196 let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2197 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2198 let v = bx.call(f, &[lhs, rhs], None);
2202 span_bug!(span, "unknown SIMD intrinsic");
2205 // Returns the width of an int Ty, and if it's signed or not
2206 // Returns None if the type is not an integer
2207 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2209 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2211 ty::Int(t) => Some((
2213 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2214 ast::IntTy::I8 => 8,
2215 ast::IntTy::I16 => 16,
2216 ast::IntTy::I32 => 32,
2217 ast::IntTy::I64 => 64,
2218 ast::IntTy::I128 => 128,
2222 ty::Uint(t) => Some((
2224 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2225 ast::UintTy::U8 => 8,
2226 ast::UintTy::U16 => 16,
2227 ast::UintTy::U32 => 32,
2228 ast::UintTy::U64 => 64,
2229 ast::UintTy::U128 => 128,
2237 // Returns the width of a float Ty
2238 // Returns None if the type is not a float
2239 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2241 ty::Float(t) => Some(t.bit_width()),
2246 fn op_to_u32<'tcx>(op: &Operand<'tcx>) -> u32 {
2247 Operand::scalar_from_const(op).to_u32().expect("Scalar is u32")
2250 fn op_to_u64<'tcx>(op: &Operand<'tcx>) -> u64 {
2251 Operand::scalar_from_const(op).to_u64().expect("Scalar is u64")