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 let float_width = match float_type_width(arg_tys[0]) {
638 Some(width) => width,
640 span_invalid_monomorphization_error(
644 "invalid monomorphization of `float_to_int_unchecked` \
645 intrinsic: expected basic float type, \
653 let (width, signed) = match int_type_width_signed(ret_ty, self.cx) {
656 span_invalid_monomorphization_error(
660 "invalid monomorphization of `float_to_int_unchecked` \
661 intrinsic: expected basic integer type, \
670 // The LLVM backend can reorder and speculate `fptosi` and
671 // `fptoui`, so on WebAssembly the codegen for this instruction
672 // is quite heavyweight. To avoid this heavyweight codegen we
673 // instead use the raw wasm intrinsics which will lower to one
674 // instruction in WebAssembly (`iNN.trunc_fMM_{s,u}`). This one
675 // instruction will trap if the operand is out of bounds, but
676 // that's ok since this intrinsic is UB if the operands are out
677 // of bounds, so the behavior can be different on WebAssembly
678 // than other targets.
680 // Note, however, that when the `nontrapping-fptoint` feature is
681 // enabled in LLVM then LLVM will lower `fptosi` to
682 // `iNN.trunc_sat_fMM_{s,u}`, so if that's the case we don't
683 // bother with intrinsics.
684 let mut result = None;
685 if self.sess().target.target.arch == "wasm32"
686 && !self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
688 let name = match (width, float_width, signed) {
689 (32, 32, true) => Some("llvm.wasm.trunc.signed.i32.f32"),
690 (32, 64, true) => Some("llvm.wasm.trunc.signed.i32.f64"),
691 (64, 32, true) => Some("llvm.wasm.trunc.signed.i64.f32"),
692 (64, 64, true) => Some("llvm.wasm.trunc.signed.i64.f64"),
693 (32, 32, false) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
694 (32, 64, false) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
695 (64, 32, false) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
696 (64, 64, false) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
699 if let Some(name) = name {
700 let intrinsic = self.get_intrinsic(name);
701 result = Some(self.call(intrinsic, &[args[0].immediate()], None));
704 result.unwrap_or_else(|| {
706 self.fptosi(args[0].immediate(), self.cx.type_ix(width))
708 self.fptoui(args[0].immediate(), self.cx.type_ix(width))
713 sym::discriminant_value => {
714 if ret_ty.is_integral() {
715 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
717 span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
721 _ if name_str.starts_with("simd_") => {
722 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
727 // This requires that atomic intrinsics follow a specific naming pattern:
728 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
729 name if name_str.starts_with("atomic_") => {
730 use rustc_codegen_ssa::common::AtomicOrdering::*;
731 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
733 let split: Vec<&str> = name_str.split('_').collect();
735 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
736 let (order, failorder) = match split.len() {
737 2 => (SequentiallyConsistent, SequentiallyConsistent),
738 3 => match split[2] {
739 "unordered" => (Unordered, Unordered),
740 "relaxed" => (Monotonic, Monotonic),
741 "acq" => (Acquire, Acquire),
742 "rel" => (Release, Monotonic),
743 "acqrel" => (AcquireRelease, Acquire),
744 "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
745 "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
746 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
748 4 => match (split[2], split[3]) {
749 ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
750 ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
751 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
753 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
756 let invalid_monomorphization = |ty| {
757 span_invalid_monomorphization_error(
761 "invalid monomorphization of `{}` intrinsic: \
762 expected basic integer type, found `{}`",
769 "cxchg" | "cxchgweak" => {
770 let ty = substs.type_at(0);
771 if int_type_width_signed(ty, self).is_some() {
772 let weak = split[1] == "cxchgweak";
773 let pair = self.atomic_cmpxchg(
781 let val = self.extract_value(pair, 0);
782 let success = self.extract_value(pair, 1);
783 let success = self.zext(success, self.type_bool());
785 let dest = result.project_field(self, 0);
786 self.store(val, dest.llval, dest.align);
787 let dest = result.project_field(self, 1);
788 self.store(success, dest.llval, dest.align);
791 return invalid_monomorphization(ty);
796 let ty = substs.type_at(0);
797 if int_type_width_signed(ty, self).is_some() {
798 let size = self.size_of(ty);
799 self.atomic_load(args[0].immediate(), order, size)
801 return invalid_monomorphization(ty);
806 let ty = substs.type_at(0);
807 if int_type_width_signed(ty, self).is_some() {
808 let size = self.size_of(ty);
817 return invalid_monomorphization(ty);
822 self.atomic_fence(order, SynchronizationScope::CrossThread);
826 "singlethreadfence" => {
827 self.atomic_fence(order, SynchronizationScope::SingleThread);
831 // These are all AtomicRMW ops
833 let atom_op = match op {
834 "xchg" => AtomicRmwBinOp::AtomicXchg,
835 "xadd" => AtomicRmwBinOp::AtomicAdd,
836 "xsub" => AtomicRmwBinOp::AtomicSub,
837 "and" => AtomicRmwBinOp::AtomicAnd,
838 "nand" => AtomicRmwBinOp::AtomicNand,
839 "or" => AtomicRmwBinOp::AtomicOr,
840 "xor" => AtomicRmwBinOp::AtomicXor,
841 "max" => AtomicRmwBinOp::AtomicMax,
842 "min" => AtomicRmwBinOp::AtomicMin,
843 "umax" => AtomicRmwBinOp::AtomicUMax,
844 "umin" => AtomicRmwBinOp::AtomicUMin,
845 _ => self.sess().fatal("unknown atomic operation"),
848 let ty = substs.type_at(0);
849 if int_type_width_signed(ty, self).is_some() {
857 return invalid_monomorphization(ty);
863 sym::nontemporal_store => {
864 let dst = args[0].deref(self.cx());
865 args[1].val.nontemporal_store(self, dst);
869 sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
870 let a = args[0].immediate();
871 let b = args[1].immediate();
872 if name == sym::ptr_guaranteed_eq {
873 self.icmp(IntPredicate::IntEQ, a, b)
875 self.icmp(IntPredicate::IntNE, a, b)
879 sym::ptr_offset_from => {
880 let ty = substs.type_at(0);
881 let pointee_size = self.size_of(ty);
883 // This is the same sequence that Clang emits for pointer subtraction.
884 // It can be neither `nsw` nor `nuw` because the input is treated as
885 // unsigned but then the output is treated as signed, so neither works.
886 let a = args[0].immediate();
887 let b = args[1].immediate();
888 let a = self.ptrtoint(a, self.type_isize());
889 let b = self.ptrtoint(b, self.type_isize());
890 let d = self.sub(a, b);
891 let pointee_size = self.const_usize(pointee_size.bytes());
892 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
893 self.exactsdiv(d, pointee_size)
896 _ => bug!("unknown intrinsic '{}'", name),
899 if !fn_abi.ret.is_ignore() {
900 if let PassMode::Cast(ty) = fn_abi.ret.mode {
901 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
902 let ptr = self.pointercast(result.llval, ptr_llty);
903 self.store(llval, ptr, result.align);
905 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
907 .store(self, result);
912 fn abort(&mut self) {
913 let fnname = self.get_intrinsic(&("llvm.trap"));
914 self.call(fnname, &[], None);
917 fn assume(&mut self, val: Self::Value) {
918 let assume_intrinsic = self.get_intrinsic("llvm.assume");
919 self.call(assume_intrinsic, &[val], None);
922 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
923 let expect = self.get_intrinsic(&"llvm.expect.i1");
924 self.call(expect, &[cond, self.const_bool(expected)], None)
927 fn sideeffect(&mut self) {
928 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
929 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
930 self.call(fnname, &[], None);
934 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
935 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
936 self.call(intrinsic, &[va_list], None)
939 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
940 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
941 self.call(intrinsic, &[va_list], None)
946 bx: &mut Builder<'a, 'll, 'tcx>,
954 let (size, align) = bx.size_and_align_of(ty);
955 let size = bx.mul(bx.const_usize(size.bytes()), count);
956 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
958 bx.memmove(dst, align, src, align, size, flags);
960 bx.memcpy(dst, align, src, align, size, flags);
965 bx: &mut Builder<'a, 'll, 'tcx>,
972 let (size, align) = bx.size_and_align_of(ty);
973 let size = bx.mul(bx.const_usize(size.bytes()), count);
974 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
975 bx.memset(dst, val, size, align, flags);
979 bx: &mut Builder<'a, 'll, 'tcx>,
980 try_func: &'ll Value,
982 catch_func: &'ll Value,
985 if bx.sess().panic_strategy() == PanicStrategy::Abort {
986 bx.call(try_func, &[data], None);
987 // Return 0 unconditionally from the intrinsic call;
988 // we can never unwind.
989 let ret_align = bx.tcx().data_layout.i32_align.abi;
990 bx.store(bx.const_i32(0), dest, ret_align);
991 } else if wants_msvc_seh(bx.sess()) {
992 codegen_msvc_try(bx, try_func, data, catch_func, dest);
994 codegen_gnu_try(bx, try_func, data, catch_func, dest);
998 // MSVC's definition of the `rust_try` function.
1000 // This implementation uses the new exception handling instructions in LLVM
1001 // which have support in LLVM for SEH on MSVC targets. Although these
1002 // instructions are meant to work for all targets, as of the time of this
1003 // writing, however, LLVM does not recommend the usage of these new instructions
1004 // as the old ones are still more optimized.
1005 fn codegen_msvc_try(
1006 bx: &mut Builder<'a, 'll, 'tcx>,
1007 try_func: &'ll Value,
1009 catch_func: &'ll Value,
1012 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1013 bx.set_personality_fn(bx.eh_personality());
1016 let mut normal = bx.build_sibling_block("normal");
1017 let mut catchswitch = bx.build_sibling_block("catchswitch");
1018 let mut catchpad = bx.build_sibling_block("catchpad");
1019 let mut caught = bx.build_sibling_block("caught");
1021 let try_func = llvm::get_param(bx.llfn(), 0);
1022 let data = llvm::get_param(bx.llfn(), 1);
1023 let catch_func = llvm::get_param(bx.llfn(), 2);
1025 // We're generating an IR snippet that looks like:
1027 // declare i32 @rust_try(%try_func, %data, %catch_func) {
1028 // %slot = alloca u8*
1029 // invoke %try_func(%data) to label %normal unwind label %catchswitch
1035 // %cs = catchswitch within none [%catchpad] unwind to caller
1038 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
1039 // %ptr = load %slot
1040 // call %catch_func(%data, %ptr)
1041 // catchret from %tok to label %caught
1047 // This structure follows the basic usage of throw/try/catch in LLVM.
1048 // For example, compile this C++ snippet to see what LLVM generates:
1050 // #include <stdint.h>
1052 // struct rust_panic {
1053 // rust_panic(const rust_panic&);
1060 // void (*try_func)(void*),
1062 // void (*catch_func)(void*, void*) noexcept
1067 // } catch(rust_panic& a) {
1068 // catch_func(data, &a);
1073 // More information can be found in libstd's seh.rs implementation.
1074 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
1075 let slot = bx.alloca(bx.type_i8p(), ptr_align);
1076 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
1078 normal.ret(bx.const_i32(0));
1080 let cs = catchswitch.catch_switch(None, None, 1);
1081 catchswitch.add_handler(cs, catchpad.llbb());
1083 // We can't use the TypeDescriptor defined in libpanic_unwind because it
1084 // might be in another DLL and the SEH encoding only supports specifying
1085 // a TypeDescriptor from the current module.
1087 // However this isn't an issue since the MSVC runtime uses string
1088 // comparison on the type name to match TypeDescriptors rather than
1089 // pointer equality.
1091 // So instead we generate a new TypeDescriptor in each module that uses
1092 // `try` and let the linker merge duplicate definitions in the same
1095 // When modifying, make sure that the type_name string exactly matches
1096 // the one used in src/libpanic_unwind/seh.rs.
1097 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
1098 let type_name = bx.const_bytes(b"rust_panic\0");
1100 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
1101 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
1103 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1104 llvm::SetUniqueComdat(bx.llmod, tydesc);
1105 llvm::LLVMSetInitializer(tydesc, type_info);
1108 // The flag value of 8 indicates that we are catching the exception by
1109 // reference instead of by value. We can't use catch by value because
1110 // that requires copying the exception object, which we don't support
1111 // since our exception object effectively contains a Box.
1113 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1114 let flags = bx.const_i32(8);
1115 let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
1116 let ptr = catchpad.load(slot, ptr_align);
1117 catchpad.call(catch_func, &[data, ptr], Some(&funclet));
1119 catchpad.catch_ret(&funclet, caught.llbb());
1121 caught.ret(bx.const_i32(1));
1124 // Note that no invoke is used here because by definition this function
1125 // can't panic (that's what it's catching).
1126 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1127 let i32_align = bx.tcx().data_layout.i32_align.abi;
1128 bx.store(ret, dest, i32_align);
1131 // Definition of the standard `try` function for Rust using the GNU-like model
1132 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1135 // This codegen is a little surprising because we always call a shim
1136 // function instead of inlining the call to `invoke` manually here. This is done
1137 // because in LLVM we're only allowed to have one personality per function
1138 // definition. The call to the `try` intrinsic is being inlined into the
1139 // function calling it, and that function may already have other personality
1140 // functions in play. By calling a shim we're guaranteed that our shim will have
1141 // the right personality function.
1143 bx: &mut Builder<'a, 'll, 'tcx>,
1144 try_func: &'ll Value,
1146 catch_func: &'ll Value,
1149 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1150 // Codegens the shims described above:
1153 // invoke %try_func(%data) normal %normal unwind %catch
1159 // (%ptr, _) = landingpad
1160 // call %catch_func(%data, %ptr)
1165 let mut then = bx.build_sibling_block("then");
1166 let mut catch = bx.build_sibling_block("catch");
1168 let try_func = llvm::get_param(bx.llfn(), 0);
1169 let data = llvm::get_param(bx.llfn(), 1);
1170 let catch_func = llvm::get_param(bx.llfn(), 2);
1171 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1172 then.ret(bx.const_i32(0));
1174 // Type indicator for the exception being thrown.
1176 // The first value in this tuple is a pointer to the exception object
1177 // being thrown. The second value is a "selector" indicating which of
1178 // the landing pad clauses the exception's type had been matched to.
1179 // rust_try ignores the selector.
1180 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1181 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1182 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1184 let tydesc = bx.get_static(tydesc);
1185 bx.bitcast(tydesc, bx.type_i8p())
1187 None => bx.const_null(bx.type_i8p()),
1189 catch.add_clause(vals, tydesc);
1190 let ptr = catch.extract_value(vals, 0);
1191 catch.call(catch_func, &[data, ptr], None);
1192 catch.ret(bx.const_i32(1));
1195 // Note that no invoke is used here because by definition this function
1196 // can't panic (that's what it's catching).
1197 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1198 let i32_align = bx.tcx().data_layout.i32_align.abi;
1199 bx.store(ret, dest, i32_align);
1202 // Helper function to give a Block to a closure to codegen a shim function.
1203 // This is currently primarily used for the `try` intrinsic functions above.
1204 fn gen_fn<'ll, 'tcx>(
1205 cx: &CodegenCx<'ll, 'tcx>,
1207 inputs: Vec<Ty<'tcx>>,
1209 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1211 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1215 hir::Unsafety::Unsafe,
1218 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1219 let llfn = cx.declare_fn(name, &fn_abi);
1220 cx.set_frame_pointer_elimination(llfn);
1221 cx.apply_target_cpu_attr(llfn);
1222 // FIXME(eddyb) find a nicer way to do this.
1223 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1224 let bx = Builder::new_block(cx, llfn, "entry-block");
1229 // Helper function used to get a handle to the `__rust_try` function used to
1230 // catch exceptions.
1232 // This function is only generated once and is then cached.
1233 fn get_rust_try_fn<'ll, 'tcx>(
1234 cx: &CodegenCx<'ll, 'tcx>,
1235 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1237 if let Some(llfn) = cx.rust_try_fn.get() {
1241 // Define the type up front for the signature of the rust_try function.
1243 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1244 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1248 hir::Unsafety::Unsafe,
1251 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1252 [i8p, i8p].iter().cloned(),
1255 hir::Unsafety::Unsafe,
1258 let output = tcx.types.i32;
1259 let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1260 cx.rust_try_fn.set(Some(rust_try));
1264 fn generic_simd_intrinsic(
1265 bx: &mut Builder<'a, 'll, 'tcx>,
1267 callee_ty: Ty<'tcx>,
1268 args: &[OperandRef<'tcx, &'ll Value>],
1270 llret_ty: &'ll Type,
1272 ) -> Result<&'ll Value, ()> {
1273 // macros for error handling:
1274 macro_rules! emit_error {
1278 ($msg: tt, $($fmt: tt)*) => {
1279 span_invalid_monomorphization_error(
1281 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1286 macro_rules! return_error {
1289 emit_error!($($fmt)*);
1295 macro_rules! require {
1296 ($cond: expr, $($fmt: tt)*) => {
1298 return_error!($($fmt)*);
1303 macro_rules! require_simd {
1304 ($ty: expr, $position: expr) => {
1305 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1311 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1312 let arg_tys = sig.inputs();
1313 let name_str = &*name.as_str();
1315 if name == sym::simd_select_bitmask {
1316 let in_ty = arg_tys[0];
1317 let m_len = match in_ty.kind {
1318 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1319 // of intentional as there's not currently a use case for that.
1320 ty::Int(i) => i.bit_width().unwrap(),
1321 ty::Uint(i) => i.bit_width().unwrap(),
1322 _ => return_error!("`{}` is not an integral type", in_ty),
1324 require_simd!(arg_tys[1], "argument");
1325 let v_len = arg_tys[1].simd_size(tcx);
1328 "mismatched lengths: mask length `{}` != other vector length `{}`",
1332 let i1 = bx.type_i1();
1333 let i1xn = bx.type_vector(i1, m_len);
1334 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1335 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1338 // every intrinsic below takes a SIMD vector as its first argument
1339 require_simd!(arg_tys[0], "input");
1340 let in_ty = arg_tys[0];
1341 let in_elem = arg_tys[0].simd_type(tcx);
1342 let in_len = arg_tys[0].simd_size(tcx);
1344 let comparison = match name {
1345 sym::simd_eq => Some(hir::BinOpKind::Eq),
1346 sym::simd_ne => Some(hir::BinOpKind::Ne),
1347 sym::simd_lt => Some(hir::BinOpKind::Lt),
1348 sym::simd_le => Some(hir::BinOpKind::Le),
1349 sym::simd_gt => Some(hir::BinOpKind::Gt),
1350 sym::simd_ge => Some(hir::BinOpKind::Ge),
1354 if let Some(cmp_op) = comparison {
1355 require_simd!(ret_ty, "return");
1357 let out_len = ret_ty.simd_size(tcx);
1360 "expected return type with length {} (same as input type `{}`), \
1361 found `{}` with length {}",
1368 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1369 "expected return type with integer elements, found `{}` with non-integer `{}`",
1371 ret_ty.simd_type(tcx)
1374 return Ok(compare_simd_types(
1376 args[0].immediate(),
1377 args[1].immediate(),
1384 if name_str.starts_with("simd_shuffle") {
1385 let n: u64 = name_str["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1386 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1389 require_simd!(ret_ty, "return");
1391 let out_len = ret_ty.simd_size(tcx);
1394 "expected return type of length {}, found `{}` with length {}",
1400 in_elem == ret_ty.simd_type(tcx),
1401 "expected return element type `{}` (element of input `{}`), \
1402 found `{}` with element type `{}`",
1406 ret_ty.simd_type(tcx)
1409 let total_len = u128::from(in_len) * 2;
1411 let vector = args[2].immediate();
1413 let indices: Option<Vec<_>> = (0..n)
1416 let val = bx.const_get_elt(vector, i as u64);
1417 match bx.const_to_opt_u128(val, true) {
1419 emit_error!("shuffle index #{} is not a constant", arg_idx);
1422 Some(idx) if idx >= total_len => {
1424 "shuffle index #{} is out of bounds (limit {})",
1430 Some(idx) => Some(bx.const_i32(idx as i32)),
1434 let indices = match indices {
1436 None => return Ok(bx.const_null(llret_ty)),
1439 return Ok(bx.shuffle_vector(
1440 args[0].immediate(),
1441 args[1].immediate(),
1442 bx.const_vector(&indices),
1446 if name == sym::simd_insert {
1448 in_elem == arg_tys[2],
1449 "expected inserted type `{}` (element of input `{}`), found `{}`",
1454 return Ok(bx.insert_element(
1455 args[0].immediate(),
1456 args[2].immediate(),
1457 args[1].immediate(),
1460 if name == sym::simd_extract {
1463 "expected return type `{}` (element of input `{}`), found `{}`",
1468 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1471 if name == sym::simd_select {
1472 let m_elem_ty = in_elem;
1474 require_simd!(arg_tys[1], "argument");
1475 let v_len = arg_tys[1].simd_size(tcx);
1478 "mismatched lengths: mask length `{}` != other vector length `{}`",
1482 match m_elem_ty.kind {
1484 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1486 // truncate the mask to a vector of i1s
1487 let i1 = bx.type_i1();
1488 let i1xn = bx.type_vector(i1, m_len as u64);
1489 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1490 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1493 if name == sym::simd_bitmask {
1494 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1495 // vector mask and returns an unsigned integer containing the most
1496 // significant bit (MSB) of each lane.
1498 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1500 let expected_int_bits = in_len.max(8);
1502 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1503 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1506 // Integer vector <i{in_bitwidth} x in_len>:
1507 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1509 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1512 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1515 "vector argument `{}`'s element type `{}`, expected integer element type",
1521 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1524 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1527 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1528 // Truncate vector to an <i1 x N>
1529 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1530 // Bitcast <i1 x N> to iN:
1531 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1532 // Zero-extend iN to the bitmask type:
1533 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1536 fn simd_simple_float_intrinsic(
1538 in_elem: &::rustc_middle::ty::TyS<'_>,
1539 in_ty: &::rustc_middle::ty::TyS<'_>,
1541 bx: &mut Builder<'a, 'll, 'tcx>,
1543 args: &[OperandRef<'tcx, &'ll Value>],
1544 ) -> Result<&'ll Value, ()> {
1545 macro_rules! emit_error {
1549 ($msg: tt, $($fmt: tt)*) => {
1550 span_invalid_monomorphization_error(
1552 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1556 macro_rules! return_error {
1559 emit_error!($($fmt)*);
1564 let ety = match in_elem.kind {
1565 ty::Float(f) if f.bit_width() == 32 => {
1566 if in_len < 2 || in_len > 16 {
1568 "unsupported floating-point vector `{}` with length `{}` \
1569 out-of-range [2, 16]",
1576 ty::Float(f) if f.bit_width() == 64 => {
1577 if in_len < 2 || in_len > 8 {
1579 "unsupported floating-point vector `{}` with length `{}` \
1580 out-of-range [2, 8]",
1589 "unsupported element type `{}` of floating-point vector `{}`",
1595 return_error!("`{}` is not a floating-point type", in_ty);
1599 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1600 let intrinsic = bx.get_intrinsic(&llvm_name);
1602 bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1603 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1608 sym::simd_fsqrt => {
1609 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1612 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1615 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1618 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1620 sym::simd_floor => {
1621 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1624 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1627 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1629 sym::simd_fexp2 => {
1630 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1632 sym::simd_flog10 => {
1633 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1635 sym::simd_flog2 => {
1636 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1639 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1641 sym::simd_fpowi => {
1642 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1645 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1648 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1650 _ => { /* fallthrough */ }
1654 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1655 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1656 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1657 let p0s: String = "p0".repeat(no_pointers);
1658 match elem_ty.kind {
1659 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1660 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1661 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1662 _ => unreachable!(),
1667 cx: &CodegenCx<'ll, '_>,
1670 mut no_pointers: usize,
1672 // FIXME: use cx.layout_of(ty).llvm_type() ?
1673 let mut elem_ty = match elem_ty.kind {
1674 ty::Int(v) => cx.type_int_from_ty(v),
1675 ty::Uint(v) => cx.type_uint_from_ty(v),
1676 ty::Float(v) => cx.type_float_from_ty(v),
1677 _ => unreachable!(),
1679 while no_pointers > 0 {
1680 elem_ty = cx.type_ptr_to(elem_ty);
1683 cx.type_vector(elem_ty, vec_len)
1686 if name == sym::simd_gather {
1687 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1688 // mask: <N x i{M}>) -> <N x T>
1689 // * N: number of elements in the input vectors
1690 // * T: type of the element to load
1691 // * M: any integer width is supported, will be truncated to i1
1693 // All types must be simd vector types
1694 require_simd!(in_ty, "first");
1695 require_simd!(arg_tys[1], "second");
1696 require_simd!(arg_tys[2], "third");
1697 require_simd!(ret_ty, "return");
1699 // Of the same length:
1701 in_len == arg_tys[1].simd_size(tcx),
1702 "expected {} argument with length {} (same as input type `{}`), \
1703 found `{}` with length {}",
1708 arg_tys[1].simd_size(tcx)
1711 in_len == arg_tys[2].simd_size(tcx),
1712 "expected {} argument with length {} (same as input type `{}`), \
1713 found `{}` with length {}",
1718 arg_tys[2].simd_size(tcx)
1721 // The return type must match the first argument type
1722 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1724 // This counts how many pointers
1725 fn ptr_count(t: Ty<'_>) -> usize {
1727 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1733 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1735 ty::RawPtr(p) => non_ptr(p.ty),
1740 // The second argument must be a simd vector with an element type that's a pointer
1741 // to the element type of the first argument
1742 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1743 ty::RawPtr(p) if p.ty == in_elem => {
1744 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1749 "expected element type `{}` of second argument `{}` \
1750 to be a pointer to the element type `{}` of the first \
1751 argument `{}`, found `{}` != `*_ {}`",
1752 arg_tys[1].simd_type(tcx),
1756 arg_tys[1].simd_type(tcx),
1762 assert!(pointer_count > 0);
1763 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1764 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1766 // The element type of the third argument must be a signed integer type of any width:
1767 match arg_tys[2].simd_type(tcx).kind {
1772 "expected element type `{}` of third argument `{}` \
1773 to be a signed integer type",
1774 arg_tys[2].simd_type(tcx),
1780 // Alignment of T, must be a constant integer value:
1781 let alignment_ty = bx.type_i32();
1782 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1784 // Truncate the mask vector to a vector of i1s:
1785 let (mask, mask_ty) = {
1786 let i1 = bx.type_i1();
1787 let i1xn = bx.type_vector(i1, in_len);
1788 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1791 // Type of the vector of pointers:
1792 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1793 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1795 // Type of the vector of elements:
1796 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1797 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1799 let llvm_intrinsic =
1800 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1801 let f = bx.declare_cfn(
1804 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1808 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1809 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1813 if name == sym::simd_scatter {
1814 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1815 // mask: <N x i{M}>) -> ()
1816 // * N: number of elements in the input vectors
1817 // * T: type of the element to load
1818 // * M: any integer width is supported, will be truncated to i1
1820 // All types must be simd vector types
1821 require_simd!(in_ty, "first");
1822 require_simd!(arg_tys[1], "second");
1823 require_simd!(arg_tys[2], "third");
1825 // Of the same length:
1827 in_len == arg_tys[1].simd_size(tcx),
1828 "expected {} argument with length {} (same as input type `{}`), \
1829 found `{}` with length {}",
1834 arg_tys[1].simd_size(tcx)
1837 in_len == arg_tys[2].simd_size(tcx),
1838 "expected {} argument with length {} (same as input type `{}`), \
1839 found `{}` with length {}",
1844 arg_tys[2].simd_size(tcx)
1847 // This counts how many pointers
1848 fn ptr_count(t: Ty<'_>) -> usize {
1850 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1856 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1858 ty::RawPtr(p) => non_ptr(p.ty),
1863 // The second argument must be a simd vector with an element type that's a pointer
1864 // to the element type of the first argument
1865 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1866 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1867 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1872 "expected element type `{}` of second argument `{}` \
1873 to be a pointer to the element type `{}` of the first \
1874 argument `{}`, found `{}` != `*mut {}`",
1875 arg_tys[1].simd_type(tcx),
1879 arg_tys[1].simd_type(tcx),
1885 assert!(pointer_count > 0);
1886 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1887 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1889 // The element type of the third argument must be a signed integer type of any width:
1890 match arg_tys[2].simd_type(tcx).kind {
1895 "expected element type `{}` of third argument `{}` \
1896 to be a signed integer type",
1897 arg_tys[2].simd_type(tcx),
1903 // Alignment of T, must be a constant integer value:
1904 let alignment_ty = bx.type_i32();
1905 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1907 // Truncate the mask vector to a vector of i1s:
1908 let (mask, mask_ty) = {
1909 let i1 = bx.type_i1();
1910 let i1xn = bx.type_vector(i1, in_len);
1911 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1914 let ret_t = bx.type_void();
1916 // Type of the vector of pointers:
1917 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1918 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1920 // Type of the vector of elements:
1921 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1922 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1924 let llvm_intrinsic =
1925 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1926 let f = bx.declare_cfn(
1928 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1930 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1931 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1935 macro_rules! arith_red {
1936 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1937 $identity:expr) => {
1938 if name == sym::$name {
1941 "expected return type `{}` (element of input `{}`), found `{}`",
1946 return match in_elem.kind {
1947 ty::Int(_) | ty::Uint(_) => {
1948 let r = bx.$integer_reduce(args[0].immediate());
1950 // if overflow occurs, the result is the
1951 // mathematical result modulo 2^n:
1952 Ok(bx.$op(args[1].immediate(), r))
1954 Ok(bx.$integer_reduce(args[0].immediate()))
1958 let acc = if $ordered {
1959 // ordered arithmetic reductions take an accumulator
1962 // unordered arithmetic reductions use the identity accumulator
1963 match f.bit_width() {
1964 32 => bx.const_real(bx.type_f32(), $identity),
1965 64 => bx.const_real(bx.type_f64(), $identity),
1968 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1977 Ok(bx.$float_reduce(acc, args[0].immediate()))
1980 "unsupported {} from `{}` with element `{}` to `{}`",
1991 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1992 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1994 simd_reduce_add_unordered: vector_reduce_add,
1995 vector_reduce_fadd_fast,
2001 simd_reduce_mul_unordered: vector_reduce_mul,
2002 vector_reduce_fmul_fast,
2008 macro_rules! minmax_red {
2009 ($name:ident: $int_red:ident, $float_red:ident) => {
2010 if name == sym::$name {
2013 "expected return type `{}` (element of input `{}`), found `{}`",
2018 return match in_elem.kind {
2019 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
2020 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
2021 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
2023 "unsupported {} from `{}` with element `{}` to `{}`",
2034 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
2035 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
2037 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
2038 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
2040 macro_rules! bitwise_red {
2041 ($name:ident : $red:ident, $boolean:expr) => {
2042 if name == sym::$name {
2043 let input = if !$boolean {
2046 "expected return type `{}` (element of input `{}`), found `{}`",
2053 match in_elem.kind {
2054 ty::Int(_) | ty::Uint(_) => {}
2056 "unsupported {} from `{}` with element `{}` to `{}`",
2064 // boolean reductions operate on vectors of i1s:
2065 let i1 = bx.type_i1();
2066 let i1xn = bx.type_vector(i1, in_len as u64);
2067 bx.trunc(args[0].immediate(), i1xn)
2069 return match in_elem.kind {
2070 ty::Int(_) | ty::Uint(_) => {
2071 let r = bx.$red(input);
2072 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2075 "unsupported {} from `{}` with element `{}` to `{}`",
2086 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2087 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2088 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2089 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2090 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2092 if name == sym::simd_cast {
2093 require_simd!(ret_ty, "return");
2094 let out_len = ret_ty.simd_size(tcx);
2097 "expected return type with length {} (same as input type `{}`), \
2098 found `{}` with length {}",
2104 // casting cares about nominal type, not just structural type
2105 let out_elem = ret_ty.simd_type(tcx);
2107 if in_elem == out_elem {
2108 return Ok(args[0].immediate());
2113 Int(/* is signed? */ bool),
2117 let (in_style, in_width) = match in_elem.kind {
2118 // vectors of pointer-sized integers should've been
2119 // disallowed before here, so this unwrap is safe.
2120 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2121 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2122 ty::Float(f) => (Style::Float, f.bit_width()),
2123 _ => (Style::Unsupported, 0),
2125 let (out_style, out_width) = match out_elem.kind {
2126 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2127 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2128 ty::Float(f) => (Style::Float, f.bit_width()),
2129 _ => (Style::Unsupported, 0),
2132 match (in_style, out_style) {
2133 (Style::Int(in_is_signed), Style::Int(_)) => {
2134 return Ok(match in_width.cmp(&out_width) {
2135 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2136 Ordering::Equal => args[0].immediate(),
2139 bx.sext(args[0].immediate(), llret_ty)
2141 bx.zext(args[0].immediate(), llret_ty)
2146 (Style::Int(in_is_signed), Style::Float) => {
2147 return Ok(if in_is_signed {
2148 bx.sitofp(args[0].immediate(), llret_ty)
2150 bx.uitofp(args[0].immediate(), llret_ty)
2153 (Style::Float, Style::Int(out_is_signed)) => {
2154 return Ok(if out_is_signed {
2155 bx.fptosi(args[0].immediate(), llret_ty)
2157 bx.fptoui(args[0].immediate(), llret_ty)
2160 (Style::Float, Style::Float) => {
2161 return Ok(match in_width.cmp(&out_width) {
2162 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2163 Ordering::Equal => args[0].immediate(),
2164 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2167 _ => { /* Unsupported. Fallthrough. */ }
2171 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2178 macro_rules! arith {
2179 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2180 $(if name == sym::$name {
2181 match in_elem.kind {
2182 $($(ty::$p(_))|* => {
2183 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2188 "unsupported operation on `{}` with element `{}`",
2195 simd_add: Uint, Int => add, Float => fadd;
2196 simd_sub: Uint, Int => sub, Float => fsub;
2197 simd_mul: Uint, Int => mul, Float => fmul;
2198 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2199 simd_rem: Uint => urem, Int => srem, Float => frem;
2200 simd_shl: Uint, Int => shl;
2201 simd_shr: Uint => lshr, Int => ashr;
2202 simd_and: Uint, Int => and;
2203 simd_or: Uint, Int => or;
2204 simd_xor: Uint, Int => xor;
2205 simd_fmax: Float => maxnum;
2206 simd_fmin: Float => minnum;
2210 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2211 let lhs = args[0].immediate();
2212 let rhs = args[1].immediate();
2213 let is_add = name == sym::simd_saturating_add;
2214 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2215 let (signed, elem_width, elem_ty) = match in_elem.kind {
2216 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2217 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2220 "expected element type `{}` of vector type `{}` \
2221 to be a signed or unsigned integer type",
2222 arg_tys[0].simd_type(tcx),
2227 let llvm_intrinsic = &format!(
2228 "llvm.{}{}.sat.v{}i{}",
2229 if signed { 's' } else { 'u' },
2230 if is_add { "add" } else { "sub" },
2234 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2236 let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2237 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2238 let v = bx.call(f, &[lhs, rhs], None);
2242 span_bug!(span, "unknown SIMD intrinsic");
2245 // Returns the width of an int Ty, and if it's signed or not
2246 // Returns None if the type is not an integer
2247 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2249 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2251 ty::Int(t) => Some((
2253 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2254 ast::IntTy::I8 => 8,
2255 ast::IntTy::I16 => 16,
2256 ast::IntTy::I32 => 32,
2257 ast::IntTy::I64 => 64,
2258 ast::IntTy::I128 => 128,
2262 ty::Uint(t) => Some((
2264 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2265 ast::UintTy::U8 => 8,
2266 ast::UintTy::U16 => 16,
2267 ast::UintTy::U32 => 32,
2268 ast::UintTy::U64 => 64,
2269 ast::UintTy::U128 => 128,
2277 // Returns the width of a float Ty
2278 // Returns None if the type is not a float
2279 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2281 ty::Float(t) => Some(t.bit_width()),
2286 fn op_to_u32<'tcx>(op: &Operand<'tcx>) -> u32 {
2287 Operand::scalar_from_const(op).to_u32().expect("Scalar is u32")
2290 fn op_to_u64<'tcx>(op: &Operand<'tcx>) -> u64 {
2291 Operand::scalar_from_const(op).to_u64().expect("Scalar is u64")