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::CounterOp;
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};
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: &str) -> Option<&'ll Value> {
36 let llvm_name = match name {
37 "sqrtf32" => "llvm.sqrt.f32",
38 "sqrtf64" => "llvm.sqrt.f64",
39 "powif32" => "llvm.powi.f32",
40 "powif64" => "llvm.powi.f64",
41 "sinf32" => "llvm.sin.f32",
42 "sinf64" => "llvm.sin.f64",
43 "cosf32" => "llvm.cos.f32",
44 "cosf64" => "llvm.cos.f64",
45 "powf32" => "llvm.pow.f32",
46 "powf64" => "llvm.pow.f64",
47 "expf32" => "llvm.exp.f32",
48 "expf64" => "llvm.exp.f64",
49 "exp2f32" => "llvm.exp2.f32",
50 "exp2f64" => "llvm.exp2.f64",
51 "logf32" => "llvm.log.f32",
52 "logf64" => "llvm.log.f64",
53 "log10f32" => "llvm.log10.f32",
54 "log10f64" => "llvm.log10.f64",
55 "log2f32" => "llvm.log2.f32",
56 "log2f64" => "llvm.log2.f64",
57 "fmaf32" => "llvm.fma.f32",
58 "fmaf64" => "llvm.fma.f64",
59 "fabsf32" => "llvm.fabs.f32",
60 "fabsf64" => "llvm.fabs.f64",
61 "minnumf32" => "llvm.minnum.f32",
62 "minnumf64" => "llvm.minnum.f64",
63 "maxnumf32" => "llvm.maxnum.f32",
64 "maxnumf64" => "llvm.maxnum.f64",
65 "copysignf32" => "llvm.copysign.f32",
66 "copysignf64" => "llvm.copysign.f64",
67 "floorf32" => "llvm.floor.f32",
68 "floorf64" => "llvm.floor.f64",
69 "ceilf32" => "llvm.ceil.f32",
70 "ceilf64" => "llvm.ceil.f64",
71 "truncf32" => "llvm.trunc.f32",
72 "truncf64" => "llvm.trunc.f64",
73 "rintf32" => "llvm.rint.f32",
74 "rintf64" => "llvm.rint.f64",
75 "nearbyintf32" => "llvm.nearbyint.f32",
76 "nearbyintf64" => "llvm.nearbyint.f64",
77 "roundf32" => "llvm.round.f32",
78 "roundf64" => "llvm.round.f64",
79 "assume" => "llvm.assume",
80 "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>,
94 "count_code_region" => {
95 use coverage::count_code_region_args::*;
96 self.add_counter_region(
98 op_to_u32(&args[COUNTER_INDEX]),
99 op_to_u32(&args[START_BYTE_POS]),
100 op_to_u32(&args[END_BYTE_POS]),
102 true // Also inject the counter increment in the backend
104 "coverage_counter_add" | "coverage_counter_subtract" => {
105 use coverage::coverage_counter_expression_args::*;
106 self.add_counter_expression_region(
108 op_to_u32(&args[COUNTER_EXPRESSION_INDEX]),
109 op_to_u32(&args[LEFT_INDEX]),
110 if intrinsic == "coverage_counter_add" {
115 op_to_u32(&args[RIGHT_INDEX]),
116 op_to_u32(&args[START_BYTE_POS]),
117 op_to_u32(&args[END_BYTE_POS]),
119 false // Does not inject backend code
121 "coverage_unreachable" => {
122 use coverage::coverage_unreachable_args::*;
123 self.add_unreachable_region(
125 op_to_u32(&args[START_BYTE_POS]),
126 op_to_u32(&args[END_BYTE_POS]),
128 false // Does not inject backend code
130 _ => true, // Unhandled intrinsics should be passed to `codegen_intrinsic_call()`
134 fn codegen_intrinsic_call(
136 instance: ty::Instance<'tcx>,
137 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
138 args: &[OperandRef<'tcx, &'ll Value>],
139 llresult: &'ll Value,
141 caller_instance: ty::Instance<'tcx>,
144 let callee_ty = instance.monomorphic_ty(tcx);
146 let (def_id, substs) = match callee_ty.kind {
147 ty::FnDef(def_id, substs) => (def_id, substs),
148 _ => bug!("expected fn item type, found {}", callee_ty),
151 let sig = callee_ty.fn_sig(tcx);
152 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
153 let arg_tys = sig.inputs();
154 let ret_ty = sig.output();
155 let name = &*tcx.item_name(def_id).as_str();
157 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
158 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
160 let simple = get_simple_intrinsic(self, name);
161 let llval = match name {
162 _ if simple.is_some() => self.call(
164 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
171 let expect = self.get_intrinsic(&("llvm.expect.i1"));
172 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
175 let expect = self.get_intrinsic(&("llvm.expect.i1"));
176 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
189 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
190 self.call(llfn, &[], None)
192 "count_code_region" => {
193 // FIXME(richkadel): The current implementation assumes the MIR for the given
194 // caller_instance represents a single function. Validate and/or correct if inlining
195 // and/or monomorphization invalidates these assumptions.
196 let coverageinfo = tcx.coverageinfo(caller_instance.def_id());
197 let mangled_fn = tcx.symbol_name(caller_instance);
198 let (mangled_fn_name, _len_val) = self.const_str(mangled_fn.name);
199 let hash = self.const_u64(coverageinfo.hash);
200 let num_counters = self.const_u32(coverageinfo.num_counters);
201 use coverage::count_code_region_args::*;
202 let index = args[COUNTER_INDEX].immediate();
204 "count_code_region to LLVM intrinsic instrprof.increment(fn_name={}, hash={:?}, num_counters={:?}, index={:?})",
205 mangled_fn.name, hash, num_counters, index,
207 self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
209 "va_start" => self.va_start(args[0].immediate()),
210 "va_end" => self.va_end(args[0].immediate()),
212 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
213 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
216 match fn_abi.ret.layout.abi {
217 abi::Abi::Scalar(ref scalar) => {
219 Primitive::Int(..) => {
220 if self.cx().size_of(ret_ty).bytes() < 4 {
221 // `va_arg` should not be called on a integer type
222 // less than 4 bytes in length. If it is, promote
223 // the integer to a `i32` and truncate the result
224 // back to the smaller type.
225 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
226 self.trunc(promoted_result, llret_ty)
228 emit_va_arg(self, args[0], ret_ty)
231 Primitive::F64 | Primitive::Pointer => {
232 emit_va_arg(self, args[0], ret_ty)
234 // `va_arg` should never be used with the return type f32.
235 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
238 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
242 let tp_ty = substs.type_at(0);
243 if let OperandValue::Pair(_, meta) = args[0].val {
244 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
247 self.const_usize(self.size_of(tp_ty).bytes())
250 "min_align_of_val" => {
251 let tp_ty = substs.type_at(0);
252 if let OperandValue::Pair(_, meta) = args[0].val {
253 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
256 self.const_usize(self.align_of(tp_ty).bytes())
259 "size_of" | "pref_align_of" | "min_align_of" | "needs_drop" | "type_id"
260 | "type_name" | "variant_count" => {
263 .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
265 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
272 let ptr = args[0].immediate();
273 let offset = args[1].immediate();
274 self.inbounds_gep(ptr, &[offset])
277 let ptr = args[0].immediate();
278 let offset = args[1].immediate();
279 self.gep(ptr, &[offset])
282 "copy_nonoverlapping" => {
318 "volatile_copy_nonoverlapping_memory" => {
330 "volatile_copy_memory" => {
342 "volatile_set_memory" => {
353 "volatile_load" | "unaligned_volatile_load" => {
354 let tp_ty = substs.type_at(0);
355 let mut ptr = args[0].immediate();
356 if let PassMode::Cast(ty) = fn_abi.ret.mode {
357 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
359 let load = self.volatile_load(ptr);
360 let align = if name == "unaligned_volatile_load" {
363 self.align_of(tp_ty).bytes() as u32
366 llvm::LLVMSetAlignment(load, align);
368 to_immediate(self, load, self.layout_of(tp_ty))
370 "volatile_store" => {
371 let dst = args[0].deref(self.cx());
372 args[1].val.volatile_store(self, dst);
375 "unaligned_volatile_store" => {
376 let dst = args[0].deref(self.cx());
377 args[1].val.unaligned_volatile_store(self, dst);
381 | "prefetch_write_data"
382 | "prefetch_read_instruction"
383 | "prefetch_write_instruction" => {
384 let expect = self.get_intrinsic(&("llvm.prefetch"));
385 let (rw, cache_type) = match name {
386 "prefetch_read_data" => (0, 1),
387 "prefetch_write_data" => (1, 1),
388 "prefetch_read_instruction" => (0, 0),
389 "prefetch_write_instruction" => (1, 0),
398 self.const_i32(cache_type),
403 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap"
404 | "bitreverse" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow"
405 | "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "unchecked_div"
406 | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "unchecked_add"
407 | "unchecked_sub" | "unchecked_mul" | "exact_div" | "rotate_left" | "rotate_right"
408 | "saturating_add" | "saturating_sub" => {
410 match int_type_width_signed(ty, self) {
411 Some((width, signed)) => match name {
413 let y = self.const_bool(false);
414 let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
415 self.call(llfn, &[args[0].immediate(), y], None)
417 "ctlz_nonzero" | "cttz_nonzero" => {
418 let y = self.const_bool(true);
419 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
420 let llfn = self.get_intrinsic(llvm_name);
421 self.call(llfn, &[args[0].immediate(), y], None)
423 "ctpop" => self.call(
424 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
425 &[args[0].immediate()],
430 args[0].immediate() // byte swap a u8/i8 is just a no-op
433 self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
434 &[args[0].immediate()],
439 "bitreverse" => self.call(
440 self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
441 &[args[0].immediate()],
444 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
445 let intrinsic = format!(
446 "llvm.{}{}.with.overflow.i{}",
447 if signed { 's' } else { 'u' },
451 let llfn = self.get_intrinsic(&intrinsic);
453 // Convert `i1` to a `bool`, and write it to the out parameter
455 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
456 let val = self.extract_value(pair, 0);
457 let overflow = self.extract_value(pair, 1);
458 let overflow = self.zext(overflow, self.type_bool());
460 let dest = result.project_field(self, 0);
461 self.store(val, dest.llval, dest.align);
462 let dest = result.project_field(self, 1);
463 self.store(overflow, dest.llval, dest.align);
467 "wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
468 "wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
469 "wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
472 self.exactsdiv(args[0].immediate(), args[1].immediate())
474 self.exactudiv(args[0].immediate(), args[1].immediate())
479 self.sdiv(args[0].immediate(), args[1].immediate())
481 self.udiv(args[0].immediate(), args[1].immediate())
486 self.srem(args[0].immediate(), args[1].immediate())
488 self.urem(args[0].immediate(), args[1].immediate())
491 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
494 self.ashr(args[0].immediate(), args[1].immediate())
496 self.lshr(args[0].immediate(), args[1].immediate())
501 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
503 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
508 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
510 self.unchecked_usub(args[0].immediate(), args[1].immediate())
515 self.unchecked_smul(args[0].immediate(), args[1].immediate())
517 self.unchecked_umul(args[0].immediate(), args[1].immediate())
520 "rotate_left" | "rotate_right" => {
521 let is_left = name == "rotate_left";
522 let val = args[0].immediate();
523 let raw_shift = args[1].immediate();
524 // rotate = funnel shift with first two args the same
526 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
527 let llfn = self.get_intrinsic(llvm_name);
528 self.call(llfn, &[val, val, raw_shift], None)
530 "saturating_add" | "saturating_sub" => {
531 let is_add = name == "saturating_add";
532 let lhs = args[0].immediate();
533 let rhs = args[1].immediate();
534 let llvm_name = &format!(
536 if signed { 's' } else { 'u' },
537 if is_add { "add" } else { "sub" },
540 let llfn = self.get_intrinsic(llvm_name);
541 self.call(llfn, &[lhs, rhs], None)
546 span_invalid_monomorphization_error(
550 "invalid monomorphization of `{}` intrinsic: \
551 expected basic integer type, found `{}`",
559 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
560 match float_type_width(arg_tys[0]) {
561 Some(_width) => match name {
562 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
563 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
564 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
565 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
566 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
570 span_invalid_monomorphization_error(
574 "invalid monomorphization of `{}` intrinsic: \
575 expected basic float type, found `{}`",
584 "float_to_int_unchecked" => {
585 if float_type_width(arg_tys[0]).is_none() {
586 span_invalid_monomorphization_error(
590 "invalid monomorphization of `float_to_int_unchecked` \
591 intrinsic: expected basic float type, \
598 match int_type_width_signed(ret_ty, self.cx) {
599 Some((width, signed)) => {
601 self.fptosi(args[0].immediate(), self.cx.type_ix(width))
603 self.fptoui(args[0].immediate(), self.cx.type_ix(width))
607 span_invalid_monomorphization_error(
611 "invalid monomorphization of `float_to_int_unchecked` \
612 intrinsic: expected basic integer type, \
622 "discriminant_value" => {
623 if ret_ty.is_integral() {
624 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
626 span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
630 name if name.starts_with("simd_") => {
631 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
636 // This requires that atomic intrinsics follow a specific naming pattern:
637 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
638 name if name.starts_with("atomic_") => {
639 use rustc_codegen_ssa::common::AtomicOrdering::*;
640 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
642 let split: Vec<&str> = name.split('_').collect();
644 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
645 let (order, failorder) = match split.len() {
646 2 => (SequentiallyConsistent, SequentiallyConsistent),
647 3 => match split[2] {
648 "unordered" => (Unordered, Unordered),
649 "relaxed" => (Monotonic, Monotonic),
650 "acq" => (Acquire, Acquire),
651 "rel" => (Release, Monotonic),
652 "acqrel" => (AcquireRelease, Acquire),
653 "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
654 "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
655 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
657 4 => match (split[2], split[3]) {
658 ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
659 ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
660 _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
662 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
665 let invalid_monomorphization = |ty| {
666 span_invalid_monomorphization_error(
670 "invalid monomorphization of `{}` intrinsic: \
671 expected basic integer type, found `{}`",
678 "cxchg" | "cxchgweak" => {
679 let ty = substs.type_at(0);
680 if int_type_width_signed(ty, self).is_some() {
681 let weak = split[1] == "cxchgweak";
682 let pair = self.atomic_cmpxchg(
690 let val = self.extract_value(pair, 0);
691 let success = self.extract_value(pair, 1);
692 let success = self.zext(success, self.type_bool());
694 let dest = result.project_field(self, 0);
695 self.store(val, dest.llval, dest.align);
696 let dest = result.project_field(self, 1);
697 self.store(success, dest.llval, dest.align);
700 return invalid_monomorphization(ty);
705 let ty = substs.type_at(0);
706 if int_type_width_signed(ty, self).is_some() {
707 let size = self.size_of(ty);
708 self.atomic_load(args[0].immediate(), order, size)
710 return invalid_monomorphization(ty);
715 let ty = substs.type_at(0);
716 if int_type_width_signed(ty, self).is_some() {
717 let size = self.size_of(ty);
726 return invalid_monomorphization(ty);
731 self.atomic_fence(order, SynchronizationScope::CrossThread);
735 "singlethreadfence" => {
736 self.atomic_fence(order, SynchronizationScope::SingleThread);
740 // These are all AtomicRMW ops
742 let atom_op = match op {
743 "xchg" => AtomicRmwBinOp::AtomicXchg,
744 "xadd" => AtomicRmwBinOp::AtomicAdd,
745 "xsub" => AtomicRmwBinOp::AtomicSub,
746 "and" => AtomicRmwBinOp::AtomicAnd,
747 "nand" => AtomicRmwBinOp::AtomicNand,
748 "or" => AtomicRmwBinOp::AtomicOr,
749 "xor" => AtomicRmwBinOp::AtomicXor,
750 "max" => AtomicRmwBinOp::AtomicMax,
751 "min" => AtomicRmwBinOp::AtomicMin,
752 "umax" => AtomicRmwBinOp::AtomicUMax,
753 "umin" => AtomicRmwBinOp::AtomicUMin,
754 _ => self.sess().fatal("unknown atomic operation"),
757 let ty = substs.type_at(0);
758 if int_type_width_signed(ty, self).is_some() {
766 return invalid_monomorphization(ty);
772 "nontemporal_store" => {
773 let dst = args[0].deref(self.cx());
774 args[1].val.nontemporal_store(self, dst);
778 "ptr_guaranteed_eq" | "ptr_guaranteed_ne" => {
779 let a = args[0].immediate();
780 let b = args[1].immediate();
781 if name == "ptr_guaranteed_eq" {
782 self.icmp(IntPredicate::IntEQ, a, b)
784 self.icmp(IntPredicate::IntNE, a, b)
788 "ptr_offset_from" => {
789 let ty = substs.type_at(0);
790 let pointee_size = self.size_of(ty);
792 // This is the same sequence that Clang emits for pointer subtraction.
793 // It can be neither `nsw` nor `nuw` because the input is treated as
794 // unsigned but then the output is treated as signed, so neither works.
795 let a = args[0].immediate();
796 let b = args[1].immediate();
797 let a = self.ptrtoint(a, self.type_isize());
798 let b = self.ptrtoint(b, self.type_isize());
799 let d = self.sub(a, b);
800 let pointee_size = self.const_usize(pointee_size.bytes());
801 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
802 self.exactsdiv(d, pointee_size)
805 _ => bug!("unknown intrinsic '{}'", name),
808 if !fn_abi.ret.is_ignore() {
809 if let PassMode::Cast(ty) = fn_abi.ret.mode {
810 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
811 let ptr = self.pointercast(result.llval, ptr_llty);
812 self.store(llval, ptr, result.align);
814 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
816 .store(self, result);
821 fn abort(&mut self) {
822 let fnname = self.get_intrinsic(&("llvm.trap"));
823 self.call(fnname, &[], None);
826 fn assume(&mut self, val: Self::Value) {
827 let assume_intrinsic = self.get_intrinsic("llvm.assume");
828 self.call(assume_intrinsic, &[val], None);
831 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
832 let expect = self.get_intrinsic(&"llvm.expect.i1");
833 self.call(expect, &[cond, self.const_bool(expected)], None)
836 fn sideeffect(&mut self) {
837 if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
838 let fnname = self.get_intrinsic(&("llvm.sideeffect"));
839 self.call(fnname, &[], None);
843 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
844 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
845 self.call(intrinsic, &[va_list], None)
848 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
849 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
850 self.call(intrinsic, &[va_list], None)
855 bx: &mut Builder<'a, 'll, 'tcx>,
863 let (size, align) = bx.size_and_align_of(ty);
864 let size = bx.mul(bx.const_usize(size.bytes()), count);
865 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
867 bx.memmove(dst, align, src, align, size, flags);
869 bx.memcpy(dst, align, src, align, size, flags);
874 bx: &mut Builder<'a, 'll, 'tcx>,
881 let (size, align) = bx.size_and_align_of(ty);
882 let size = bx.mul(bx.const_usize(size.bytes()), count);
883 let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
884 bx.memset(dst, val, size, align, flags);
888 bx: &mut Builder<'a, 'll, 'tcx>,
889 try_func: &'ll Value,
891 catch_func: &'ll Value,
894 if bx.sess().panic_strategy() == PanicStrategy::Abort {
895 bx.call(try_func, &[data], None);
896 // Return 0 unconditionally from the intrinsic call;
897 // we can never unwind.
898 let ret_align = bx.tcx().data_layout.i32_align.abi;
899 bx.store(bx.const_i32(0), dest, ret_align);
900 } else if wants_msvc_seh(bx.sess()) {
901 codegen_msvc_try(bx, try_func, data, catch_func, dest);
903 codegen_gnu_try(bx, try_func, data, catch_func, dest);
907 // MSVC's definition of the `rust_try` function.
909 // This implementation uses the new exception handling instructions in LLVM
910 // which have support in LLVM for SEH on MSVC targets. Although these
911 // instructions are meant to work for all targets, as of the time of this
912 // writing, however, LLVM does not recommend the usage of these new instructions
913 // as the old ones are still more optimized.
915 bx: &mut Builder<'a, 'll, 'tcx>,
916 try_func: &'ll Value,
918 catch_func: &'ll Value,
921 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
922 bx.set_personality_fn(bx.eh_personality());
925 let mut normal = bx.build_sibling_block("normal");
926 let mut catchswitch = bx.build_sibling_block("catchswitch");
927 let mut catchpad = bx.build_sibling_block("catchpad");
928 let mut caught = bx.build_sibling_block("caught");
930 let try_func = llvm::get_param(bx.llfn(), 0);
931 let data = llvm::get_param(bx.llfn(), 1);
932 let catch_func = llvm::get_param(bx.llfn(), 2);
934 // We're generating an IR snippet that looks like:
936 // declare i32 @rust_try(%try_func, %data, %catch_func) {
937 // %slot = alloca u8*
938 // invoke %try_func(%data) to label %normal unwind label %catchswitch
944 // %cs = catchswitch within none [%catchpad] unwind to caller
947 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
949 // call %catch_func(%data, %ptr)
950 // catchret from %tok to label %caught
956 // This structure follows the basic usage of throw/try/catch in LLVM.
957 // For example, compile this C++ snippet to see what LLVM generates:
959 // #include <stdint.h>
961 // struct rust_panic {
962 // rust_panic(const rust_panic&);
969 // void (*try_func)(void*),
971 // void (*catch_func)(void*, void*) noexcept
976 // } catch(rust_panic& a) {
977 // catch_func(data, &a);
982 // More information can be found in libstd's seh.rs implementation.
983 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
984 let slot = bx.alloca(bx.type_i8p(), ptr_align);
985 bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
987 normal.ret(bx.const_i32(0));
989 let cs = catchswitch.catch_switch(None, None, 1);
990 catchswitch.add_handler(cs, catchpad.llbb());
992 // We can't use the TypeDescriptor defined in libpanic_unwind because it
993 // might be in another DLL and the SEH encoding only supports specifying
994 // a TypeDescriptor from the current module.
996 // However this isn't an issue since the MSVC runtime uses string
997 // comparison on the type name to match TypeDescriptors rather than
1000 // So instead we generate a new TypeDescriptor in each module that uses
1001 // `try` and let the linker merge duplicate definitions in the same
1004 // When modifying, make sure that the type_name string exactly matches
1005 // the one used in src/libpanic_unwind/seh.rs.
1006 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
1007 let type_name = bx.const_bytes(b"rust_panic\0");
1009 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
1010 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
1012 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1013 llvm::SetUniqueComdat(bx.llmod, tydesc);
1014 llvm::LLVMSetInitializer(tydesc, type_info);
1017 // The flag value of 8 indicates that we are catching the exception by
1018 // reference instead of by value. We can't use catch by value because
1019 // that requires copying the exception object, which we don't support
1020 // since our exception object effectively contains a Box.
1022 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1023 let flags = bx.const_i32(8);
1024 let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
1025 let ptr = catchpad.load(slot, ptr_align);
1026 catchpad.call(catch_func, &[data, ptr], Some(&funclet));
1028 catchpad.catch_ret(&funclet, caught.llbb());
1030 caught.ret(bx.const_i32(1));
1033 // Note that no invoke is used here because by definition this function
1034 // can't panic (that's what it's catching).
1035 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1036 let i32_align = bx.tcx().data_layout.i32_align.abi;
1037 bx.store(ret, dest, i32_align);
1040 // Definition of the standard `try` function for Rust using the GNU-like model
1041 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1044 // This codegen is a little surprising because we always call a shim
1045 // function instead of inlining the call to `invoke` manually here. This is done
1046 // because in LLVM we're only allowed to have one personality per function
1047 // definition. The call to the `try` intrinsic is being inlined into the
1048 // function calling it, and that function may already have other personality
1049 // functions in play. By calling a shim we're guaranteed that our shim will have
1050 // the right personality function.
1052 bx: &mut Builder<'a, 'll, 'tcx>,
1053 try_func: &'ll Value,
1055 catch_func: &'ll Value,
1058 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1059 // Codegens the shims described above:
1062 // invoke %try_func(%data) normal %normal unwind %catch
1068 // (%ptr, _) = landingpad
1069 // call %catch_func(%data, %ptr)
1074 let mut then = bx.build_sibling_block("then");
1075 let mut catch = bx.build_sibling_block("catch");
1077 let try_func = llvm::get_param(bx.llfn(), 0);
1078 let data = llvm::get_param(bx.llfn(), 1);
1079 let catch_func = llvm::get_param(bx.llfn(), 2);
1080 bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1081 then.ret(bx.const_i32(0));
1083 // Type indicator for the exception being thrown.
1085 // The first value in this tuple is a pointer to the exception object
1086 // being thrown. The second value is a "selector" indicating which of
1087 // the landing pad clauses the exception's type had been matched to.
1088 // rust_try ignores the selector.
1089 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1090 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1091 let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1093 let tydesc = bx.get_static(tydesc);
1094 bx.bitcast(tydesc, bx.type_i8p())
1096 None => bx.const_null(bx.type_i8p()),
1098 catch.add_clause(vals, tydesc);
1099 let ptr = catch.extract_value(vals, 0);
1100 catch.call(catch_func, &[data, ptr], None);
1101 catch.ret(bx.const_i32(1));
1104 // Note that no invoke is used here because by definition this function
1105 // can't panic (that's what it's catching).
1106 let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1107 let i32_align = bx.tcx().data_layout.i32_align.abi;
1108 bx.store(ret, dest, i32_align);
1111 // Helper function to give a Block to a closure to codegen a shim function.
1112 // This is currently primarily used for the `try` intrinsic functions above.
1113 fn gen_fn<'ll, 'tcx>(
1114 cx: &CodegenCx<'ll, 'tcx>,
1116 inputs: Vec<Ty<'tcx>>,
1118 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1120 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1124 hir::Unsafety::Unsafe,
1127 let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1128 let llfn = cx.declare_fn(name, &fn_abi);
1129 cx.set_frame_pointer_elimination(llfn);
1130 cx.apply_target_cpu_attr(llfn);
1131 // FIXME(eddyb) find a nicer way to do this.
1132 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1133 let bx = Builder::new_block(cx, llfn, "entry-block");
1138 // Helper function used to get a handle to the `__rust_try` function used to
1139 // catch exceptions.
1141 // This function is only generated once and is then cached.
1142 fn get_rust_try_fn<'ll, 'tcx>(
1143 cx: &CodegenCx<'ll, 'tcx>,
1144 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1146 if let Some(llfn) = cx.rust_try_fn.get() {
1150 // Define the type up front for the signature of the rust_try function.
1152 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1153 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1157 hir::Unsafety::Unsafe,
1160 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1161 [i8p, i8p].iter().cloned(),
1164 hir::Unsafety::Unsafe,
1167 let output = tcx.types.i32;
1168 let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1169 cx.rust_try_fn.set(Some(rust_try));
1173 fn generic_simd_intrinsic(
1174 bx: &mut Builder<'a, 'll, 'tcx>,
1176 callee_ty: Ty<'tcx>,
1177 args: &[OperandRef<'tcx, &'ll Value>],
1179 llret_ty: &'ll Type,
1181 ) -> Result<&'ll Value, ()> {
1182 // macros for error handling:
1183 macro_rules! emit_error {
1187 ($msg: tt, $($fmt: tt)*) => {
1188 span_invalid_monomorphization_error(
1190 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1195 macro_rules! return_error {
1198 emit_error!($($fmt)*);
1204 macro_rules! require {
1205 ($cond: expr, $($fmt: tt)*) => {
1207 return_error!($($fmt)*);
1212 macro_rules! require_simd {
1213 ($ty: expr, $position: expr) => {
1214 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1220 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1221 let arg_tys = sig.inputs();
1223 if name == "simd_select_bitmask" {
1224 let in_ty = arg_tys[0];
1225 let m_len = match in_ty.kind {
1226 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1227 // of intentional as there's not currently a use case for that.
1228 ty::Int(i) => i.bit_width().unwrap(),
1229 ty::Uint(i) => i.bit_width().unwrap(),
1230 _ => return_error!("`{}` is not an integral type", in_ty),
1232 require_simd!(arg_tys[1], "argument");
1233 let v_len = arg_tys[1].simd_size(tcx);
1236 "mismatched lengths: mask length `{}` != other vector length `{}`",
1240 let i1 = bx.type_i1();
1241 let i1xn = bx.type_vector(i1, m_len);
1242 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1243 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1246 // every intrinsic below takes a SIMD vector as its first argument
1247 require_simd!(arg_tys[0], "input");
1248 let in_ty = arg_tys[0];
1249 let in_elem = arg_tys[0].simd_type(tcx);
1250 let in_len = arg_tys[0].simd_size(tcx);
1252 let comparison = match name {
1253 "simd_eq" => Some(hir::BinOpKind::Eq),
1254 "simd_ne" => Some(hir::BinOpKind::Ne),
1255 "simd_lt" => Some(hir::BinOpKind::Lt),
1256 "simd_le" => Some(hir::BinOpKind::Le),
1257 "simd_gt" => Some(hir::BinOpKind::Gt),
1258 "simd_ge" => Some(hir::BinOpKind::Ge),
1262 if let Some(cmp_op) = comparison {
1263 require_simd!(ret_ty, "return");
1265 let out_len = ret_ty.simd_size(tcx);
1268 "expected return type with length {} (same as input type `{}`), \
1269 found `{}` with length {}",
1276 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1277 "expected return type with integer elements, found `{}` with non-integer `{}`",
1279 ret_ty.simd_type(tcx)
1282 return Ok(compare_simd_types(
1284 args[0].immediate(),
1285 args[1].immediate(),
1292 if name.starts_with("simd_shuffle") {
1293 let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1294 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1297 require_simd!(ret_ty, "return");
1299 let out_len = ret_ty.simd_size(tcx);
1302 "expected return type of length {}, found `{}` with length {}",
1308 in_elem == ret_ty.simd_type(tcx),
1309 "expected return element type `{}` (element of input `{}`), \
1310 found `{}` with element type `{}`",
1314 ret_ty.simd_type(tcx)
1317 let total_len = u128::from(in_len) * 2;
1319 let vector = args[2].immediate();
1321 let indices: Option<Vec<_>> = (0..n)
1324 let val = bx.const_get_elt(vector, i as u64);
1325 match bx.const_to_opt_u128(val, true) {
1327 emit_error!("shuffle index #{} is not a constant", arg_idx);
1330 Some(idx) if idx >= total_len => {
1332 "shuffle index #{} is out of bounds (limit {})",
1338 Some(idx) => Some(bx.const_i32(idx as i32)),
1342 let indices = match indices {
1344 None => return Ok(bx.const_null(llret_ty)),
1347 return Ok(bx.shuffle_vector(
1348 args[0].immediate(),
1349 args[1].immediate(),
1350 bx.const_vector(&indices),
1354 if name == "simd_insert" {
1356 in_elem == arg_tys[2],
1357 "expected inserted type `{}` (element of input `{}`), found `{}`",
1362 return Ok(bx.insert_element(
1363 args[0].immediate(),
1364 args[2].immediate(),
1365 args[1].immediate(),
1368 if name == "simd_extract" {
1371 "expected return type `{}` (element of input `{}`), found `{}`",
1376 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1379 if name == "simd_select" {
1380 let m_elem_ty = in_elem;
1382 require_simd!(arg_tys[1], "argument");
1383 let v_len = arg_tys[1].simd_size(tcx);
1386 "mismatched lengths: mask length `{}` != other vector length `{}`",
1390 match m_elem_ty.kind {
1392 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1394 // truncate the mask to a vector of i1s
1395 let i1 = bx.type_i1();
1396 let i1xn = bx.type_vector(i1, m_len as u64);
1397 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1398 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1401 if name == "simd_bitmask" {
1402 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1403 // vector mask and returns an unsigned integer containing the most
1404 // significant bit (MSB) of each lane.
1406 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1408 let expected_int_bits = in_len.max(8);
1410 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1411 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1414 // Integer vector <i{in_bitwidth} x in_len>:
1415 let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1417 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1420 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1423 "vector argument `{}`'s element type `{}`, expected integer element type",
1429 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1432 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1435 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1436 // Truncate vector to an <i1 x N>
1437 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1438 // Bitcast <i1 x N> to iN:
1439 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1440 // Zero-extend iN to the bitmask type:
1441 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1444 fn simd_simple_float_intrinsic(
1446 in_elem: &::rustc_middle::ty::TyS<'_>,
1447 in_ty: &::rustc_middle::ty::TyS<'_>,
1449 bx: &mut Builder<'a, 'll, 'tcx>,
1451 args: &[OperandRef<'tcx, &'ll Value>],
1452 ) -> Result<&'ll Value, ()> {
1453 macro_rules! emit_error {
1457 ($msg: tt, $($fmt: tt)*) => {
1458 span_invalid_monomorphization_error(
1460 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1464 macro_rules! return_error {
1467 emit_error!($($fmt)*);
1472 let ety = match in_elem.kind {
1473 ty::Float(f) if f.bit_width() == 32 => {
1474 if in_len < 2 || in_len > 16 {
1476 "unsupported floating-point vector `{}` with length `{}` \
1477 out-of-range [2, 16]",
1484 ty::Float(f) if f.bit_width() == 64 => {
1485 if in_len < 2 || in_len > 8 {
1487 "unsupported floating-point vector `{}` with length `{}` \
1488 out-of-range [2, 8]",
1497 "unsupported element type `{}` of floating-point vector `{}`",
1503 return_error!("`{}` is not a floating-point type", in_ty);
1507 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1508 let intrinsic = bx.get_intrinsic(&llvm_name);
1510 bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1511 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1517 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1520 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1523 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1526 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1529 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1532 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1535 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1538 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1541 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1544 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1547 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1550 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1553 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1556 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1558 _ => { /* fallthrough */ }
1562 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1563 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1564 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1565 let p0s: String = "p0".repeat(no_pointers);
1566 match elem_ty.kind {
1567 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1568 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1569 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1570 _ => unreachable!(),
1575 cx: &CodegenCx<'ll, '_>,
1578 mut no_pointers: usize,
1580 // FIXME: use cx.layout_of(ty).llvm_type() ?
1581 let mut elem_ty = match elem_ty.kind {
1582 ty::Int(v) => cx.type_int_from_ty(v),
1583 ty::Uint(v) => cx.type_uint_from_ty(v),
1584 ty::Float(v) => cx.type_float_from_ty(v),
1585 _ => unreachable!(),
1587 while no_pointers > 0 {
1588 elem_ty = cx.type_ptr_to(elem_ty);
1591 cx.type_vector(elem_ty, vec_len)
1594 if name == "simd_gather" {
1595 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1596 // mask: <N x i{M}>) -> <N x T>
1597 // * N: number of elements in the input vectors
1598 // * T: type of the element to load
1599 // * M: any integer width is supported, will be truncated to i1
1601 // All types must be simd vector types
1602 require_simd!(in_ty, "first");
1603 require_simd!(arg_tys[1], "second");
1604 require_simd!(arg_tys[2], "third");
1605 require_simd!(ret_ty, "return");
1607 // Of the same length:
1609 in_len == arg_tys[1].simd_size(tcx),
1610 "expected {} argument with length {} (same as input type `{}`), \
1611 found `{}` with length {}",
1616 arg_tys[1].simd_size(tcx)
1619 in_len == arg_tys[2].simd_size(tcx),
1620 "expected {} argument with length {} (same as input type `{}`), \
1621 found `{}` with length {}",
1626 arg_tys[2].simd_size(tcx)
1629 // The return type must match the first argument type
1630 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1632 // This counts how many pointers
1633 fn ptr_count(t: Ty<'_>) -> usize {
1635 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1641 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1643 ty::RawPtr(p) => non_ptr(p.ty),
1648 // The second argument must be a simd vector with an element type that's a pointer
1649 // to the element type of the first argument
1650 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1651 ty::RawPtr(p) if p.ty == in_elem => {
1652 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1657 "expected element type `{}` of second argument `{}` \
1658 to be a pointer to the element type `{}` of the first \
1659 argument `{}`, found `{}` != `*_ {}`",
1660 arg_tys[1].simd_type(tcx),
1664 arg_tys[1].simd_type(tcx),
1670 assert!(pointer_count > 0);
1671 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1672 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1674 // The element type of the third argument must be a signed integer type of any width:
1675 match arg_tys[2].simd_type(tcx).kind {
1680 "expected element type `{}` of third argument `{}` \
1681 to be a signed integer type",
1682 arg_tys[2].simd_type(tcx),
1688 // Alignment of T, must be a constant integer value:
1689 let alignment_ty = bx.type_i32();
1690 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1692 // Truncate the mask vector to a vector of i1s:
1693 let (mask, mask_ty) = {
1694 let i1 = bx.type_i1();
1695 let i1xn = bx.type_vector(i1, in_len);
1696 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1699 // Type of the vector of pointers:
1700 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1701 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1703 // Type of the vector of elements:
1704 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1705 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1707 let llvm_intrinsic =
1708 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1709 let f = bx.declare_cfn(
1712 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1716 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1717 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1721 if name == "simd_scatter" {
1722 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1723 // mask: <N x i{M}>) -> ()
1724 // * N: number of elements in the input vectors
1725 // * T: type of the element to load
1726 // * M: any integer width is supported, will be truncated to i1
1728 // All types must be simd vector types
1729 require_simd!(in_ty, "first");
1730 require_simd!(arg_tys[1], "second");
1731 require_simd!(arg_tys[2], "third");
1733 // Of the same length:
1735 in_len == arg_tys[1].simd_size(tcx),
1736 "expected {} argument with length {} (same as input type `{}`), \
1737 found `{}` with length {}",
1742 arg_tys[1].simd_size(tcx)
1745 in_len == arg_tys[2].simd_size(tcx),
1746 "expected {} argument with length {} (same as input type `{}`), \
1747 found `{}` with length {}",
1752 arg_tys[2].simd_size(tcx)
1755 // This counts how many pointers
1756 fn ptr_count(t: Ty<'_>) -> usize {
1758 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1764 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1766 ty::RawPtr(p) => non_ptr(p.ty),
1771 // The second argument must be a simd vector with an element type that's a pointer
1772 // to the element type of the first argument
1773 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1774 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1775 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1780 "expected element type `{}` of second argument `{}` \
1781 to be a pointer to the element type `{}` of the first \
1782 argument `{}`, found `{}` != `*mut {}`",
1783 arg_tys[1].simd_type(tcx),
1787 arg_tys[1].simd_type(tcx),
1793 assert!(pointer_count > 0);
1794 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1795 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1797 // The element type of the third argument must be a signed integer type of any width:
1798 match arg_tys[2].simd_type(tcx).kind {
1803 "expected element type `{}` of third argument `{}` \
1804 to be a signed integer type",
1805 arg_tys[2].simd_type(tcx),
1811 // Alignment of T, must be a constant integer value:
1812 let alignment_ty = bx.type_i32();
1813 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1815 // Truncate the mask vector to a vector of i1s:
1816 let (mask, mask_ty) = {
1817 let i1 = bx.type_i1();
1818 let i1xn = bx.type_vector(i1, in_len);
1819 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1822 let ret_t = bx.type_void();
1824 // Type of the vector of pointers:
1825 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1826 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1828 // Type of the vector of elements:
1829 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1830 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1832 let llvm_intrinsic =
1833 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1834 let f = bx.declare_cfn(
1836 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1838 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1839 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1843 macro_rules! arith_red {
1844 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1848 "expected return type `{}` (element of input `{}`), found `{}`",
1853 return match in_elem.kind {
1854 ty::Int(_) | ty::Uint(_) => {
1855 let r = bx.$integer_reduce(args[0].immediate());
1857 // if overflow occurs, the result is the
1858 // mathematical result modulo 2^n:
1859 if name.contains("mul") {
1860 Ok(bx.mul(args[1].immediate(), r))
1862 Ok(bx.add(args[1].immediate(), r))
1865 Ok(bx.$integer_reduce(args[0].immediate()))
1869 let acc = if $ordered {
1870 // ordered arithmetic reductions take an accumulator
1873 // unordered arithmetic reductions use the identity accumulator
1874 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1875 match f.bit_width() {
1876 32 => bx.const_real(bx.type_f32(), identity_acc),
1877 64 => bx.const_real(bx.type_f64(), identity_acc),
1880 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1889 Ok(bx.$float_reduce(acc, args[0].immediate()))
1892 "unsupported {} from `{}` with element `{}` to `{}`",
1903 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1904 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1905 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1906 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1908 macro_rules! minmax_red {
1909 ($name:tt: $int_red:ident, $float_red:ident) => {
1913 "expected return type `{}` (element of input `{}`), found `{}`",
1918 return match in_elem.kind {
1919 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1920 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1921 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1923 "unsupported {} from `{}` with element `{}` to `{}`",
1934 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1935 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1937 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1938 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1940 macro_rules! bitwise_red {
1941 ($name:tt : $red:ident, $boolean:expr) => {
1943 let input = if !$boolean {
1946 "expected return type `{}` (element of input `{}`), found `{}`",
1953 match in_elem.kind {
1954 ty::Int(_) | ty::Uint(_) => {}
1956 "unsupported {} from `{}` with element `{}` to `{}`",
1964 // boolean reductions operate on vectors of i1s:
1965 let i1 = bx.type_i1();
1966 let i1xn = bx.type_vector(i1, in_len as u64);
1967 bx.trunc(args[0].immediate(), i1xn)
1969 return match in_elem.kind {
1970 ty::Int(_) | ty::Uint(_) => {
1971 let r = bx.$red(input);
1972 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1975 "unsupported {} from `{}` with element `{}` to `{}`",
1986 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1987 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1988 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1989 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1990 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1992 if name == "simd_cast" {
1993 require_simd!(ret_ty, "return");
1994 let out_len = ret_ty.simd_size(tcx);
1997 "expected return type with length {} (same as input type `{}`), \
1998 found `{}` with length {}",
2004 // casting cares about nominal type, not just structural type
2005 let out_elem = ret_ty.simd_type(tcx);
2007 if in_elem == out_elem {
2008 return Ok(args[0].immediate());
2013 Int(/* is signed? */ bool),
2017 let (in_style, in_width) = match in_elem.kind {
2018 // vectors of pointer-sized integers should've been
2019 // disallowed before here, so this unwrap is safe.
2020 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2021 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2022 ty::Float(f) => (Style::Float, f.bit_width()),
2023 _ => (Style::Unsupported, 0),
2025 let (out_style, out_width) = match out_elem.kind {
2026 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2027 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2028 ty::Float(f) => (Style::Float, f.bit_width()),
2029 _ => (Style::Unsupported, 0),
2032 match (in_style, out_style) {
2033 (Style::Int(in_is_signed), Style::Int(_)) => {
2034 return Ok(match in_width.cmp(&out_width) {
2035 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2036 Ordering::Equal => args[0].immediate(),
2039 bx.sext(args[0].immediate(), llret_ty)
2041 bx.zext(args[0].immediate(), llret_ty)
2046 (Style::Int(in_is_signed), Style::Float) => {
2047 return Ok(if in_is_signed {
2048 bx.sitofp(args[0].immediate(), llret_ty)
2050 bx.uitofp(args[0].immediate(), llret_ty)
2053 (Style::Float, Style::Int(out_is_signed)) => {
2054 return Ok(if out_is_signed {
2055 bx.fptosi(args[0].immediate(), llret_ty)
2057 bx.fptoui(args[0].immediate(), llret_ty)
2060 (Style::Float, Style::Float) => {
2061 return Ok(match in_width.cmp(&out_width) {
2062 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2063 Ordering::Equal => args[0].immediate(),
2064 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2067 _ => { /* Unsupported. Fallthrough. */ }
2071 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2078 macro_rules! arith {
2079 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2080 $(if name == stringify!($name) {
2081 match in_elem.kind {
2082 $($(ty::$p(_))|* => {
2083 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2088 "unsupported operation on `{}` with element `{}`",
2095 simd_add: Uint, Int => add, Float => fadd;
2096 simd_sub: Uint, Int => sub, Float => fsub;
2097 simd_mul: Uint, Int => mul, Float => fmul;
2098 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2099 simd_rem: Uint => urem, Int => srem, Float => frem;
2100 simd_shl: Uint, Int => shl;
2101 simd_shr: Uint => lshr, Int => ashr;
2102 simd_and: Uint, Int => and;
2103 simd_or: Uint, Int => or;
2104 simd_xor: Uint, Int => xor;
2105 simd_fmax: Float => maxnum;
2106 simd_fmin: Float => minnum;
2110 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
2111 let lhs = args[0].immediate();
2112 let rhs = args[1].immediate();
2113 let is_add = name == "simd_saturating_add";
2114 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2115 let (signed, elem_width, elem_ty) = match in_elem.kind {
2116 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2117 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2120 "expected element type `{}` of vector type `{}` \
2121 to be a signed or unsigned integer type",
2122 arg_tys[0].simd_type(tcx),
2127 let llvm_intrinsic = &format!(
2128 "llvm.{}{}.sat.v{}i{}",
2129 if signed { 's' } else { 'u' },
2130 if is_add { "add" } else { "sub" },
2134 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2136 let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2137 llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2138 let v = bx.call(f, &[lhs, rhs], None);
2142 span_bug!(span, "unknown SIMD intrinsic");
2145 // Returns the width of an int Ty, and if it's signed or not
2146 // Returns None if the type is not an integer
2147 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2149 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2151 ty::Int(t) => Some((
2153 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2154 ast::IntTy::I8 => 8,
2155 ast::IntTy::I16 => 16,
2156 ast::IntTy::I32 => 32,
2157 ast::IntTy::I64 => 64,
2158 ast::IntTy::I128 => 128,
2162 ty::Uint(t) => Some((
2164 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2165 ast::UintTy::U8 => 8,
2166 ast::UintTy::U16 => 16,
2167 ast::UintTy::U32 => 32,
2168 ast::UintTy::U64 => 64,
2169 ast::UintTy::U128 => 128,
2177 // Returns the width of a float Ty
2178 // Returns None if the type is not a float
2179 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2181 ty::Float(t) => Some(t.bit_width()),
2186 fn op_to_u32<'tcx>(op: &Operand<'tcx>) -> u32 {
2187 Operand::scalar_from_const(op).to_u32().expect("Scalar is u32")