1 use crate::abi::{Abi, FnAbi, FnAbiLlvmExt, 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;
11 use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh};
12 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
13 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
14 use rustc_codegen_ssa::mir::operand::OperandRef;
15 use rustc_codegen_ssa::mir::place::PlaceRef;
16 use rustc_codegen_ssa::traits::*;
18 use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, LayoutOf};
19 use rustc_middle::ty::{self, Ty};
20 use rustc_middle::{bug, span_bug};
21 use rustc_span::{sym, symbol::kw, Span, Symbol};
22 use rustc_target::abi::{self, HasDataLayout, Primitive};
23 use rustc_target::spec::{HasTargetSpec, PanicStrategy};
25 use std::cmp::Ordering;
28 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<(&'ll Type, &'ll Value)> {
29 let llvm_name = match name {
30 sym::sqrtf32 => "llvm.sqrt.f32",
31 sym::sqrtf64 => "llvm.sqrt.f64",
32 sym::powif32 => "llvm.powi.f32",
33 sym::powif64 => "llvm.powi.f64",
34 sym::sinf32 => "llvm.sin.f32",
35 sym::sinf64 => "llvm.sin.f64",
36 sym::cosf32 => "llvm.cos.f32",
37 sym::cosf64 => "llvm.cos.f64",
38 sym::powf32 => "llvm.pow.f32",
39 sym::powf64 => "llvm.pow.f64",
40 sym::expf32 => "llvm.exp.f32",
41 sym::expf64 => "llvm.exp.f64",
42 sym::exp2f32 => "llvm.exp2.f32",
43 sym::exp2f64 => "llvm.exp2.f64",
44 sym::logf32 => "llvm.log.f32",
45 sym::logf64 => "llvm.log.f64",
46 sym::log10f32 => "llvm.log10.f32",
47 sym::log10f64 => "llvm.log10.f64",
48 sym::log2f32 => "llvm.log2.f32",
49 sym::log2f64 => "llvm.log2.f64",
50 sym::fmaf32 => "llvm.fma.f32",
51 sym::fmaf64 => "llvm.fma.f64",
52 sym::fabsf32 => "llvm.fabs.f32",
53 sym::fabsf64 => "llvm.fabs.f64",
54 sym::minnumf32 => "llvm.minnum.f32",
55 sym::minnumf64 => "llvm.minnum.f64",
56 sym::maxnumf32 => "llvm.maxnum.f32",
57 sym::maxnumf64 => "llvm.maxnum.f64",
58 sym::copysignf32 => "llvm.copysign.f32",
59 sym::copysignf64 => "llvm.copysign.f64",
60 sym::floorf32 => "llvm.floor.f32",
61 sym::floorf64 => "llvm.floor.f64",
62 sym::ceilf32 => "llvm.ceil.f32",
63 sym::ceilf64 => "llvm.ceil.f64",
64 sym::truncf32 => "llvm.trunc.f32",
65 sym::truncf64 => "llvm.trunc.f64",
66 sym::rintf32 => "llvm.rint.f32",
67 sym::rintf64 => "llvm.rint.f64",
68 sym::nearbyintf32 => "llvm.nearbyint.f32",
69 sym::nearbyintf64 => "llvm.nearbyint.f64",
70 sym::roundf32 => "llvm.round.f32",
71 sym::roundf64 => "llvm.round.f64",
74 Some(cx.get_intrinsic(llvm_name))
77 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
78 fn codegen_intrinsic_call(
80 instance: ty::Instance<'tcx>,
81 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
82 args: &[OperandRef<'tcx, &'ll Value>],
87 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
89 let (def_id, substs) = match *callee_ty.kind() {
90 ty::FnDef(def_id, substs) => (def_id, substs),
91 _ => bug!("expected fn item type, found {}", callee_ty),
94 let sig = callee_ty.fn_sig(tcx);
95 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
96 let arg_tys = sig.inputs();
97 let ret_ty = sig.output();
98 let name = tcx.item_name(def_id);
100 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
101 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
103 let simple = get_simple_intrinsic(self, name);
104 let llval = match name {
105 _ if simple.is_some() => {
106 let (simple_ty, simple_fn) = simple.unwrap();
110 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
115 self.call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(true)])
117 sym::unlikely => self
118 .call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(false)]),
129 sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[]),
131 self.call_intrinsic("llvm.va_copy", &[args[0].immediate(), args[1].immediate()])
134 match fn_abi.ret.layout.abi {
135 abi::Abi::Scalar(scalar) => {
137 Primitive::Int(..) => {
138 if self.cx().size_of(ret_ty).bytes() < 4 {
139 // `va_arg` should not be called on an integer type
140 // less than 4 bytes in length. If it is, promote
141 // the integer to an `i32` and truncate the result
142 // back to the smaller type.
143 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
144 self.trunc(promoted_result, llret_ty)
146 emit_va_arg(self, args[0], ret_ty)
149 Primitive::F64 | Primitive::Pointer => {
150 emit_va_arg(self, args[0], ret_ty)
152 // `va_arg` should never be used with the return type f32.
153 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
156 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
160 sym::volatile_load | sym::unaligned_volatile_load => {
161 let tp_ty = substs.type_at(0);
162 let ptr = args[0].immediate();
163 let load = if let PassMode::Cast(ty) = fn_abi.ret.mode {
164 let llty = ty.llvm_type(self);
165 let ptr = self.pointercast(ptr, self.type_ptr_to(llty));
166 self.volatile_load(llty, ptr)
168 self.volatile_load(self.layout_of(tp_ty).llvm_type(self), ptr)
170 let align = if name == sym::unaligned_volatile_load {
173 self.align_of(tp_ty).bytes() as u32
176 llvm::LLVMSetAlignment(load, align);
178 self.to_immediate(load, self.layout_of(tp_ty))
180 sym::volatile_store => {
181 let dst = args[0].deref(self.cx());
182 args[1].val.volatile_store(self, dst);
185 sym::unaligned_volatile_store => {
186 let dst = args[0].deref(self.cx());
187 args[1].val.unaligned_volatile_store(self, dst);
190 sym::prefetch_read_data
191 | sym::prefetch_write_data
192 | sym::prefetch_read_instruction
193 | sym::prefetch_write_instruction => {
194 let (rw, cache_type) = match name {
195 sym::prefetch_read_data => (0, 1),
196 sym::prefetch_write_data => (1, 1),
197 sym::prefetch_read_instruction => (0, 0),
198 sym::prefetch_write_instruction => (1, 0),
207 self.const_i32(cache_type),
220 | sym::saturating_add
221 | sym::saturating_sub => {
223 match int_type_width_signed(ty, self) {
224 Some((width, signed)) => match name {
225 sym::ctlz | sym::cttz => {
226 let y = self.const_bool(false);
228 &format!("llvm.{}.i{}", name, width),
229 &[args[0].immediate(), y],
232 sym::ctlz_nonzero => {
233 let y = self.const_bool(true);
234 let llvm_name = &format!("llvm.ctlz.i{}", width);
235 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
237 sym::cttz_nonzero => {
238 let y = self.const_bool(true);
239 let llvm_name = &format!("llvm.cttz.i{}", width);
240 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
242 sym::ctpop => self.call_intrinsic(
243 &format!("llvm.ctpop.i{}", width),
244 &[args[0].immediate()],
248 args[0].immediate() // byte swap a u8/i8 is just a no-op
251 &format!("llvm.bswap.i{}", width),
252 &[args[0].immediate()],
256 sym::bitreverse => self.call_intrinsic(
257 &format!("llvm.bitreverse.i{}", width),
258 &[args[0].immediate()],
260 sym::rotate_left | sym::rotate_right => {
261 let is_left = name == sym::rotate_left;
262 let val = args[0].immediate();
263 let raw_shift = args[1].immediate();
264 // rotate = funnel shift with first two args the same
266 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
267 self.call_intrinsic(llvm_name, &[val, val, raw_shift])
269 sym::saturating_add | sym::saturating_sub => {
270 let is_add = name == sym::saturating_add;
271 let lhs = args[0].immediate();
272 let rhs = args[1].immediate();
273 let llvm_name = &format!(
275 if signed { 's' } else { 'u' },
276 if is_add { "add" } else { "sub" },
279 self.call_intrinsic(llvm_name, &[lhs, rhs])
284 span_invalid_monomorphization_error(
288 "invalid monomorphization of `{}` intrinsic: \
289 expected basic integer type, found `{}`",
300 let tp_ty = substs.type_at(0);
301 let layout = self.layout_of(tp_ty).layout;
302 let use_integer_compare = match layout.abi {
303 Scalar(_) | ScalarPair(_, _) => true,
304 Uninhabited | Vector { .. } => false,
305 Aggregate { .. } => {
306 // For rusty ABIs, small aggregates are actually passed
307 // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
308 // so we re-use that same threshold here.
309 layout.size <= self.data_layout().pointer_size * 2
313 let a = args[0].immediate();
314 let b = args[1].immediate();
315 if layout.size.bytes() == 0 {
316 self.const_bool(true)
317 } else if use_integer_compare {
318 let integer_ty = self.type_ix(layout.size.bits());
319 let ptr_ty = self.type_ptr_to(integer_ty);
320 let a_ptr = self.bitcast(a, ptr_ty);
321 let a_val = self.load(integer_ty, a_ptr, layout.align.abi);
322 let b_ptr = self.bitcast(b, ptr_ty);
323 let b_val = self.load(integer_ty, b_ptr, layout.align.abi);
324 self.icmp(IntPredicate::IntEQ, a_val, b_val)
326 let i8p_ty = self.type_i8p();
327 let a_ptr = self.bitcast(a, i8p_ty);
328 let b_ptr = self.bitcast(b, i8p_ty);
329 let n = self.const_usize(layout.size.bytes());
330 let cmp = self.call_intrinsic("memcmp", &[a_ptr, b_ptr, n]);
331 self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0))
336 args[0].val.store(self, result);
338 // We need to "use" the argument in some way LLVM can't introspect, and on
339 // targets that support it we can typically leverage inline assembly to do
340 // this. LLVM's interpretation of inline assembly is that it's, well, a black
341 // box. This isn't the greatest implementation since it probably deoptimizes
342 // more than we want, but it's so far good enough.
343 crate::asm::inline_asm_call(
351 ast::LlvmAsmDialect::Att,
354 .unwrap_or_else(|| bug!("failed to generate inline asm call for `black_box`"));
356 // We have copied the value to `result` already.
360 _ if name.as_str().starts_with("simd_") => {
361 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
367 _ => bug!("unknown intrinsic '{}'", name),
370 if !fn_abi.ret.is_ignore() {
371 if let PassMode::Cast(ty) = fn_abi.ret.mode {
372 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
373 let ptr = self.pointercast(result.llval, ptr_llty);
374 self.store(llval, ptr, result.align);
376 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
378 .store(self, result);
383 fn abort(&mut self) {
384 self.call_intrinsic("llvm.trap", &[]);
387 fn assume(&mut self, val: Self::Value) {
388 self.call_intrinsic("llvm.assume", &[val]);
391 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
392 self.call_intrinsic("llvm.expect.i1", &[cond, self.const_bool(expected)])
395 fn sideeffect(&mut self) {
396 // This kind of check would make a ton of sense in the caller, but currently the only
397 // caller of this function is in `rustc_codegen_ssa`, which is agnostic to whether LLVM
398 // codegen backend being used, and so is unable to check the LLVM version.
399 if unsafe { llvm::LLVMRustVersionMajor() } < 12 {
400 self.call_intrinsic("llvm.sideeffect", &[]);
404 fn type_test(&mut self, pointer: Self::Value, typeid: Self::Value) -> Self::Value {
405 // Test the called operand using llvm.type.test intrinsic. The LowerTypeTests link-time
406 // optimization pass replaces calls to this intrinsic with code to test type membership.
407 let i8p_ty = self.type_i8p();
408 let bitcast = self.bitcast(pointer, i8p_ty);
409 self.call_intrinsic("llvm.type.test", &[bitcast, typeid])
412 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
413 self.call_intrinsic("llvm.va_start", &[va_list])
416 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
417 self.call_intrinsic("llvm.va_end", &[va_list])
422 bx: &mut Builder<'a, 'll, 'tcx>,
423 try_func: &'ll Value,
425 catch_func: &'ll Value,
428 if bx.sess().panic_strategy() == PanicStrategy::Abort {
429 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
430 bx.call(try_func_ty, try_func, &[data], None);
431 // Return 0 unconditionally from the intrinsic call;
432 // we can never unwind.
433 let ret_align = bx.tcx().data_layout.i32_align.abi;
434 bx.store(bx.const_i32(0), dest, ret_align);
435 } else if wants_msvc_seh(bx.sess()) {
436 codegen_msvc_try(bx, try_func, data, catch_func, dest);
437 } else if bx.sess().target.is_like_emscripten {
438 codegen_emcc_try(bx, try_func, data, catch_func, dest);
440 codegen_gnu_try(bx, try_func, data, catch_func, dest);
444 // MSVC's definition of the `rust_try` function.
446 // This implementation uses the new exception handling instructions in LLVM
447 // which have support in LLVM for SEH on MSVC targets. Although these
448 // instructions are meant to work for all targets, as of the time of this
449 // writing, however, LLVM does not recommend the usage of these new instructions
450 // as the old ones are still more optimized.
452 bx: &mut Builder<'a, 'll, 'tcx>,
453 try_func: &'ll Value,
455 catch_func: &'ll Value,
458 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
459 bx.set_personality_fn(bx.eh_personality());
461 let mut normal = bx.build_sibling_block("normal");
462 let mut catchswitch = bx.build_sibling_block("catchswitch");
463 let mut catchpad_rust = bx.build_sibling_block("catchpad_rust");
464 let mut catchpad_foreign = bx.build_sibling_block("catchpad_foreign");
465 let mut caught = bx.build_sibling_block("caught");
467 let try_func = llvm::get_param(bx.llfn(), 0);
468 let data = llvm::get_param(bx.llfn(), 1);
469 let catch_func = llvm::get_param(bx.llfn(), 2);
471 // We're generating an IR snippet that looks like:
473 // declare i32 @rust_try(%try_func, %data, %catch_func) {
474 // %slot = alloca i8*
475 // invoke %try_func(%data) to label %normal unwind label %catchswitch
481 // %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
484 // %tok = catchpad within %cs [%type_descriptor, 8, %slot]
486 // call %catch_func(%data, %ptr)
487 // catchret from %tok to label %caught
490 // %tok = catchpad within %cs [null, 64, null]
491 // call %catch_func(%data, null)
492 // catchret from %tok to label %caught
498 // This structure follows the basic usage of throw/try/catch in LLVM.
499 // For example, compile this C++ snippet to see what LLVM generates:
501 // struct rust_panic {
502 // rust_panic(const rust_panic&);
509 // void (*try_func)(void*),
511 // void (*catch_func)(void*, void*) noexcept
516 // } catch(rust_panic& a) {
517 // catch_func(data, &a);
520 // catch_func(data, NULL);
525 // More information can be found in libstd's seh.rs implementation.
526 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
527 let slot = bx.alloca(bx.type_i8p(), ptr_align);
528 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
529 bx.invoke(try_func_ty, try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
531 normal.ret(bx.const_i32(0));
533 let cs = catchswitch.catch_switch(None, None, 2);
534 catchswitch.add_handler(cs, catchpad_rust.llbb());
535 catchswitch.add_handler(cs, catchpad_foreign.llbb());
537 // We can't use the TypeDescriptor defined in libpanic_unwind because it
538 // might be in another DLL and the SEH encoding only supports specifying
539 // a TypeDescriptor from the current module.
541 // However this isn't an issue since the MSVC runtime uses string
542 // comparison on the type name to match TypeDescriptors rather than
545 // So instead we generate a new TypeDescriptor in each module that uses
546 // `try` and let the linker merge duplicate definitions in the same
549 // When modifying, make sure that the type_name string exactly matches
550 // the one used in src/libpanic_unwind/seh.rs.
551 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
552 let type_name = bx.const_bytes(b"rust_panic\0");
554 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
555 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
557 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
558 llvm::SetUniqueComdat(bx.llmod, tydesc);
559 llvm::LLVMSetInitializer(tydesc, type_info);
562 // The flag value of 8 indicates that we are catching the exception by
563 // reference instead of by value. We can't use catch by value because
564 // that requires copying the exception object, which we don't support
565 // since our exception object effectively contains a Box.
567 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
568 let flags = bx.const_i32(8);
569 let funclet = catchpad_rust.catch_pad(cs, &[tydesc, flags, slot]);
570 let ptr = catchpad_rust.load(bx.type_i8p(), slot, ptr_align);
571 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
572 catchpad_rust.call(catch_ty, catch_func, &[data, ptr], Some(&funclet));
573 catchpad_rust.catch_ret(&funclet, caught.llbb());
575 // The flag value of 64 indicates a "catch-all".
576 let flags = bx.const_i32(64);
577 let null = bx.const_null(bx.type_i8p());
578 let funclet = catchpad_foreign.catch_pad(cs, &[null, flags, null]);
579 catchpad_foreign.call(catch_ty, catch_func, &[data, null], Some(&funclet));
580 catchpad_foreign.catch_ret(&funclet, caught.llbb());
582 caught.ret(bx.const_i32(1));
585 // Note that no invoke is used here because by definition this function
586 // can't panic (that's what it's catching).
587 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
588 let i32_align = bx.tcx().data_layout.i32_align.abi;
589 bx.store(ret, dest, i32_align);
592 // Definition of the standard `try` function for Rust using the GNU-like model
593 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
596 // This codegen is a little surprising because we always call a shim
597 // function instead of inlining the call to `invoke` manually here. This is done
598 // because in LLVM we're only allowed to have one personality per function
599 // definition. The call to the `try` intrinsic is being inlined into the
600 // function calling it, and that function may already have other personality
601 // functions in play. By calling a shim we're guaranteed that our shim will have
602 // the right personality function.
604 bx: &mut Builder<'a, 'll, 'tcx>,
605 try_func: &'ll Value,
607 catch_func: &'ll Value,
610 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
611 // Codegens the shims described above:
614 // invoke %try_func(%data) normal %normal unwind %catch
620 // (%ptr, _) = landingpad
621 // call %catch_func(%data, %ptr)
623 let mut then = bx.build_sibling_block("then");
624 let mut catch = bx.build_sibling_block("catch");
626 let try_func = llvm::get_param(bx.llfn(), 0);
627 let data = llvm::get_param(bx.llfn(), 1);
628 let catch_func = llvm::get_param(bx.llfn(), 2);
629 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
630 bx.invoke(try_func_ty, try_func, &[data], then.llbb(), catch.llbb(), None);
631 then.ret(bx.const_i32(0));
633 // Type indicator for the exception being thrown.
635 // The first value in this tuple is a pointer to the exception object
636 // being thrown. The second value is a "selector" indicating which of
637 // the landing pad clauses the exception's type had been matched to.
638 // rust_try ignores the selector.
639 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
640 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
641 let tydesc = bx.const_null(bx.type_i8p());
642 catch.add_clause(vals, tydesc);
643 let ptr = catch.extract_value(vals, 0);
644 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
645 catch.call(catch_ty, catch_func, &[data, ptr], None);
646 catch.ret(bx.const_i32(1));
649 // Note that no invoke is used here because by definition this function
650 // can't panic (that's what it's catching).
651 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
652 let i32_align = bx.tcx().data_layout.i32_align.abi;
653 bx.store(ret, dest, i32_align);
656 // Variant of codegen_gnu_try used for emscripten where Rust panics are
657 // implemented using C++ exceptions. Here we use exceptions of a specific type
658 // (`struct rust_panic`) to represent Rust panics.
660 bx: &mut Builder<'a, 'll, 'tcx>,
661 try_func: &'ll Value,
663 catch_func: &'ll Value,
666 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
667 // Codegens the shims described above:
670 // invoke %try_func(%data) normal %normal unwind %catch
676 // (%ptr, %selector) = landingpad
677 // %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
678 // %is_rust_panic = %selector == %rust_typeid
679 // %catch_data = alloca { i8*, i8 }
680 // %catch_data[0] = %ptr
681 // %catch_data[1] = %is_rust_panic
682 // call %catch_func(%data, %catch_data)
684 let mut then = bx.build_sibling_block("then");
685 let mut catch = bx.build_sibling_block("catch");
687 let try_func = llvm::get_param(bx.llfn(), 0);
688 let data = llvm::get_param(bx.llfn(), 1);
689 let catch_func = llvm::get_param(bx.llfn(), 2);
690 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
691 bx.invoke(try_func_ty, try_func, &[data], then.llbb(), catch.llbb(), None);
692 then.ret(bx.const_i32(0));
694 // Type indicator for the exception being thrown.
696 // The first value in this tuple is a pointer to the exception object
697 // being thrown. The second value is a "selector" indicating which of
698 // the landing pad clauses the exception's type had been matched to.
699 let tydesc = bx.eh_catch_typeinfo();
700 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
701 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 2);
702 catch.add_clause(vals, tydesc);
703 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
704 let ptr = catch.extract_value(vals, 0);
705 let selector = catch.extract_value(vals, 1);
707 // Check if the typeid we got is the one for a Rust panic.
708 let rust_typeid = catch.call_intrinsic("llvm.eh.typeid.for", &[tydesc]);
709 let is_rust_panic = catch.icmp(IntPredicate::IntEQ, selector, rust_typeid);
710 let is_rust_panic = catch.zext(is_rust_panic, bx.type_bool());
712 // We need to pass two values to catch_func (ptr and is_rust_panic), so
713 // create an alloca and pass a pointer to that.
714 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
715 let i8_align = bx.tcx().data_layout.i8_align.abi;
716 let catch_data_type = bx.type_struct(&[bx.type_i8p(), bx.type_bool()], false);
717 let catch_data = catch.alloca(catch_data_type, ptr_align);
718 let catch_data_0 = catch.inbounds_gep(
721 &[bx.const_usize(0), bx.const_usize(0)],
723 catch.store(ptr, catch_data_0, ptr_align);
724 let catch_data_1 = catch.inbounds_gep(
727 &[bx.const_usize(0), bx.const_usize(1)],
729 catch.store(is_rust_panic, catch_data_1, i8_align);
730 let catch_data = catch.bitcast(catch_data, bx.type_i8p());
732 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
733 catch.call(catch_ty, catch_func, &[data, catch_data], None);
734 catch.ret(bx.const_i32(1));
737 // Note that no invoke is used here because by definition this function
738 // can't panic (that's what it's catching).
739 let ret = bx.call(llty, llfn, &[try_func, data, catch_func], None);
740 let i32_align = bx.tcx().data_layout.i32_align.abi;
741 bx.store(ret, dest, i32_align);
744 // Helper function to give a Block to a closure to codegen a shim function.
745 // This is currently primarily used for the `try` intrinsic functions above.
746 fn gen_fn<'ll, 'tcx>(
747 cx: &CodegenCx<'ll, 'tcx>,
749 rust_fn_sig: ty::PolyFnSig<'tcx>,
750 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
751 ) -> (&'ll Type, &'ll Value) {
752 let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
753 let llty = fn_abi.llvm_type(cx);
754 let llfn = cx.declare_fn(name, fn_abi);
755 cx.set_frame_pointer_type(llfn);
756 cx.apply_target_cpu_attr(llfn);
757 // FIXME(eddyb) find a nicer way to do this.
758 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
759 let llbb = Builder::append_block(cx, llfn, "entry-block");
760 let bx = Builder::build(cx, llbb);
765 // Helper function used to get a handle to the `__rust_try` function used to
768 // This function is only generated once and is then cached.
769 fn get_rust_try_fn<'ll, 'tcx>(
770 cx: &CodegenCx<'ll, 'tcx>,
771 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
772 ) -> (&'ll Type, &'ll Value) {
773 if let Some(llfn) = cx.rust_try_fn.get() {
777 // Define the type up front for the signature of the rust_try function.
779 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
780 // `unsafe fn(*mut i8) -> ()`
781 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
785 hir::Unsafety::Unsafe,
788 // `unsafe fn(*mut i8, *mut i8) -> ()`
789 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
790 [i8p, i8p].iter().cloned(),
793 hir::Unsafety::Unsafe,
796 // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
797 let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
798 vec![try_fn_ty, i8p, catch_fn_ty].into_iter(),
801 hir::Unsafety::Unsafe,
804 let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
805 cx.rust_try_fn.set(Some(rust_try));
809 fn generic_simd_intrinsic(
810 bx: &mut Builder<'a, 'll, 'tcx>,
813 args: &[OperandRef<'tcx, &'ll Value>],
817 ) -> Result<&'ll Value, ()> {
818 // macros for error handling:
819 macro_rules! emit_error {
823 ($msg: tt, $($fmt: tt)*) => {
824 span_invalid_monomorphization_error(
826 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
831 macro_rules! return_error {
834 emit_error!($($fmt)*);
840 macro_rules! require {
841 ($cond: expr, $($fmt: tt)*) => {
843 return_error!($($fmt)*);
848 macro_rules! require_simd {
849 ($ty: expr, $position: expr) => {
850 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
856 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), callee_ty.fn_sig(tcx));
857 let arg_tys = sig.inputs();
859 if name == sym::simd_select_bitmask {
860 let in_ty = arg_tys[0];
861 let m_len = match in_ty.kind() {
862 // Note that this `.unwrap()` crashes for isize/usize, that's sort
863 // of intentional as there's not currently a use case for that.
864 ty::Int(i) => i.bit_width().unwrap(),
865 ty::Uint(i) => i.bit_width().unwrap(),
866 _ => return_error!("`{}` is not an integral type", in_ty),
868 require_simd!(arg_tys[1], "argument");
869 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
871 // Allow masks for vectors with fewer than 8 elements to be
872 // represented with a u8 or i8.
873 m_len == v_len || (m_len == 8 && v_len < 8),
874 "mismatched lengths: mask length `{}` != other vector length `{}`",
878 let i1 = bx.type_i1();
879 let im = bx.type_ix(v_len);
880 let i1xn = bx.type_vector(i1, v_len);
881 let m_im = bx.trunc(args[0].immediate(), im);
882 let m_i1s = bx.bitcast(m_im, i1xn);
883 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
886 // every intrinsic below takes a SIMD vector as its first argument
887 require_simd!(arg_tys[0], "input");
888 let in_ty = arg_tys[0];
890 let comparison = match name {
891 sym::simd_eq => Some(hir::BinOpKind::Eq),
892 sym::simd_ne => Some(hir::BinOpKind::Ne),
893 sym::simd_lt => Some(hir::BinOpKind::Lt),
894 sym::simd_le => Some(hir::BinOpKind::Le),
895 sym::simd_gt => Some(hir::BinOpKind::Gt),
896 sym::simd_ge => Some(hir::BinOpKind::Ge),
900 let (in_len, in_elem) = arg_tys[0].simd_size_and_type(bx.tcx());
901 if let Some(cmp_op) = comparison {
902 require_simd!(ret_ty, "return");
904 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
907 "expected return type with length {} (same as input type `{}`), \
908 found `{}` with length {}",
915 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
916 "expected return type with integer elements, found `{}` with non-integer `{}`",
921 return Ok(compare_simd_types(
931 if let Some(stripped) = name.as_str().strip_prefix("simd_shuffle") {
932 // If this intrinsic is the older "simd_shuffleN" form, simply parse the integer.
933 // If there is no suffix, use the index array length.
934 let n: u64 = if stripped.is_empty() {
935 // Make sure this is actually an array, since typeck only checks the length-suffixed
936 // version of this intrinsic.
937 match args[2].layout.ty.kind() {
938 ty::Array(ty, len) if matches!(ty.kind(), ty::Uint(ty::UintTy::U32)) => {
939 len.try_eval_usize(bx.cx.tcx, ty::ParamEnv::reveal_all()).unwrap_or_else(|| {
940 span_bug!(span, "could not evaluate shuffle index array length")
944 "simd_shuffle index must be an array of `u32`, got `{}`",
949 stripped.parse().unwrap_or_else(|_| {
950 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
954 require_simd!(ret_ty, "return");
955 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
958 "expected return type of length {}, found `{}` with length {}",
965 "expected return element type `{}` (element of input `{}`), \
966 found `{}` with element type `{}`",
973 let total_len = u128::from(in_len) * 2;
975 let vector = args[2].immediate();
977 let indices: Option<Vec<_>> = (0..n)
980 let val = bx.const_get_elt(vector, i as u64);
981 match bx.const_to_opt_u128(val, true) {
983 emit_error!("shuffle index #{} is not a constant", arg_idx);
986 Some(idx) if idx >= total_len => {
988 "shuffle index #{} is out of bounds (limit {})",
994 Some(idx) => Some(bx.const_i32(idx as i32)),
998 let indices = match indices {
1000 None => return Ok(bx.const_null(llret_ty)),
1003 return Ok(bx.shuffle_vector(
1004 args[0].immediate(),
1005 args[1].immediate(),
1006 bx.const_vector(&indices),
1010 if name == sym::simd_insert {
1012 in_elem == arg_tys[2],
1013 "expected inserted type `{}` (element of input `{}`), found `{}`",
1018 return Ok(bx.insert_element(
1019 args[0].immediate(),
1020 args[2].immediate(),
1021 args[1].immediate(),
1024 if name == sym::simd_extract {
1027 "expected return type `{}` (element of input `{}`), found `{}`",
1032 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1035 if name == sym::simd_select {
1036 let m_elem_ty = in_elem;
1038 require_simd!(arg_tys[1], "argument");
1039 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1042 "mismatched lengths: mask length `{}` != other vector length `{}`",
1046 match m_elem_ty.kind() {
1048 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1050 // truncate the mask to a vector of i1s
1051 let i1 = bx.type_i1();
1052 let i1xn = bx.type_vector(i1, m_len as u64);
1053 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1054 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1057 if name == sym::simd_bitmask {
1058 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1059 // vector mask and returns an unsigned integer containing the most
1060 // significant bit (MSB) of each lane.
1062 // If the vector has less than 8 lanes, a u8 is returned with zeroed
1064 let expected_int_bits = in_len.max(8);
1065 match ret_ty.kind() {
1066 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1067 _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1070 // Integer vector <i{in_bitwidth} x in_len>:
1071 let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
1073 args[0].immediate(),
1074 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1077 args[0].immediate(),
1078 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1081 "vector argument `{}`'s element type `{}`, expected integer element type",
1087 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1090 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1093 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1094 // Truncate vector to an <i1 x N>
1095 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1096 // Bitcast <i1 x N> to iN:
1097 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1098 // Zero-extend iN to the bitmask type:
1099 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1102 fn simd_simple_float_intrinsic(
1104 in_elem: &::rustc_middle::ty::TyS<'_>,
1105 in_ty: &::rustc_middle::ty::TyS<'_>,
1107 bx: &mut Builder<'a, 'll, 'tcx>,
1109 args: &[OperandRef<'tcx, &'ll Value>],
1110 ) -> Result<&'ll Value, ()> {
1111 macro_rules! emit_error {
1115 ($msg: tt, $($fmt: tt)*) => {
1116 span_invalid_monomorphization_error(
1118 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1122 macro_rules! return_error {
1125 emit_error!($($fmt)*);
1131 let (elem_ty_str, elem_ty) = if let ty::Float(f) = in_elem.kind() {
1132 let elem_ty = bx.cx.type_float_from_ty(*f);
1133 match f.bit_width() {
1134 32 => ("f32", elem_ty),
1135 64 => ("f64", elem_ty),
1138 "unsupported element type `{}` of floating-point vector `{}`",
1145 return_error!("`{}` is not a floating-point type", in_ty);
1148 let vec_ty = bx.type_vector(elem_ty, in_len);
1150 let (intr_name, fn_ty) = match name {
1151 sym::simd_ceil => ("ceil", bx.type_func(&[vec_ty], vec_ty)),
1152 sym::simd_fabs => ("fabs", bx.type_func(&[vec_ty], vec_ty)),
1153 sym::simd_fcos => ("cos", bx.type_func(&[vec_ty], vec_ty)),
1154 sym::simd_fexp2 => ("exp2", bx.type_func(&[vec_ty], vec_ty)),
1155 sym::simd_fexp => ("exp", bx.type_func(&[vec_ty], vec_ty)),
1156 sym::simd_flog10 => ("log10", bx.type_func(&[vec_ty], vec_ty)),
1157 sym::simd_flog2 => ("log2", bx.type_func(&[vec_ty], vec_ty)),
1158 sym::simd_flog => ("log", bx.type_func(&[vec_ty], vec_ty)),
1159 sym::simd_floor => ("floor", bx.type_func(&[vec_ty], vec_ty)),
1160 sym::simd_fma => ("fma", bx.type_func(&[vec_ty, vec_ty, vec_ty], vec_ty)),
1161 sym::simd_fpowi => ("powi", bx.type_func(&[vec_ty, bx.type_i32()], vec_ty)),
1162 sym::simd_fpow => ("pow", bx.type_func(&[vec_ty, vec_ty], vec_ty)),
1163 sym::simd_fsin => ("sin", bx.type_func(&[vec_ty], vec_ty)),
1164 sym::simd_fsqrt => ("sqrt", bx.type_func(&[vec_ty], vec_ty)),
1165 sym::simd_round => ("round", bx.type_func(&[vec_ty], vec_ty)),
1166 sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
1167 _ => return_error!("unrecognized intrinsic `{}`", name),
1169 let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str);
1170 let f = bx.declare_cfn(llvm_name, llvm::UnnamedAddr::No, fn_ty);
1172 bx.call(fn_ty, f, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1195 return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1199 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1200 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1205 bx: &Builder<'a, 'll, 'tcx>,
1207 let p0s: String = "p0".repeat(no_pointers);
1208 match *elem_ty.kind() {
1209 ty::Int(v) => format!(
1213 // Normalize to prevent crash if v: IntTy::Isize
1214 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1216 ty::Uint(v) => format!(
1220 // Normalize to prevent crash if v: UIntTy::Usize
1221 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1223 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1224 _ => unreachable!(),
1229 cx: &CodegenCx<'ll, '_>,
1232 mut no_pointers: usize,
1234 // FIXME: use cx.layout_of(ty).llvm_type() ?
1235 let mut elem_ty = match *elem_ty.kind() {
1236 ty::Int(v) => cx.type_int_from_ty(v),
1237 ty::Uint(v) => cx.type_uint_from_ty(v),
1238 ty::Float(v) => cx.type_float_from_ty(v),
1239 _ => unreachable!(),
1241 while no_pointers > 0 {
1242 elem_ty = cx.type_ptr_to(elem_ty);
1245 cx.type_vector(elem_ty, vec_len)
1248 if name == sym::simd_gather {
1249 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1250 // mask: <N x i{M}>) -> <N x T>
1251 // * N: number of elements in the input vectors
1252 // * T: type of the element to load
1253 // * M: any integer width is supported, will be truncated to i1
1255 // All types must be simd vector types
1256 require_simd!(in_ty, "first");
1257 require_simd!(arg_tys[1], "second");
1258 require_simd!(arg_tys[2], "third");
1259 require_simd!(ret_ty, "return");
1261 // Of the same length:
1262 let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1263 let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1266 "expected {} argument with length {} (same as input type `{}`), \
1267 found `{}` with length {}",
1276 "expected {} argument with length {} (same as input type `{}`), \
1277 found `{}` with length {}",
1285 // The return type must match the first argument type
1286 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1288 // This counts how many pointers
1289 fn ptr_count(t: Ty<'_>) -> usize {
1291 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1297 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1299 ty::RawPtr(p) => non_ptr(p.ty),
1304 // The second argument must be a simd vector with an element type that's a pointer
1305 // to the element type of the first argument
1306 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1307 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1308 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1309 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(element_ty1), non_ptr(element_ty1)),
1313 "expected element type `{}` of second argument `{}` \
1314 to be a pointer to the element type `{}` of the first \
1315 argument `{}`, found `{}` != `*_ {}`",
1326 assert!(pointer_count > 0);
1327 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1328 assert_eq!(underlying_ty, non_ptr(element_ty0));
1330 // The element type of the third argument must be a signed integer type of any width:
1331 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1332 match element_ty2.kind() {
1337 "expected element type `{}` of third argument `{}` \
1338 to be a signed integer type",
1345 // Alignment of T, must be a constant integer value:
1346 let alignment_ty = bx.type_i32();
1347 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1349 // Truncate the mask vector to a vector of i1s:
1350 let (mask, mask_ty) = {
1351 let i1 = bx.type_i1();
1352 let i1xn = bx.type_vector(i1, in_len);
1353 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1356 // Type of the vector of pointers:
1357 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1358 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1360 // Type of the vector of elements:
1361 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1362 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1364 let llvm_intrinsic =
1365 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1366 let fn_ty = bx.type_func(
1367 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1370 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1372 bx.call(fn_ty, f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1376 if name == sym::simd_scatter {
1377 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1378 // mask: <N x i{M}>) -> ()
1379 // * N: number of elements in the input vectors
1380 // * T: type of the element to load
1381 // * M: any integer width is supported, will be truncated to i1
1383 // All types must be simd vector types
1384 require_simd!(in_ty, "first");
1385 require_simd!(arg_tys[1], "second");
1386 require_simd!(arg_tys[2], "third");
1388 // Of the same length:
1389 let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1390 let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1392 in_len == element_len1,
1393 "expected {} argument with length {} (same as input type `{}`), \
1394 found `{}` with length {}",
1402 in_len == element_len2,
1403 "expected {} argument with length {} (same as input type `{}`), \
1404 found `{}` with length {}",
1412 // This counts how many pointers
1413 fn ptr_count(t: Ty<'_>) -> usize {
1415 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1421 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1423 ty::RawPtr(p) => non_ptr(p.ty),
1428 // The second argument must be a simd vector with an element type that's a pointer
1429 // to the element type of the first argument
1430 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1431 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1432 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1433 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1434 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1435 (ptr_count(element_ty1), non_ptr(element_ty1))
1440 "expected element type `{}` of second argument `{}` \
1441 to be a pointer to the element type `{}` of the first \
1442 argument `{}`, found `{}` != `*mut {}`",
1453 assert!(pointer_count > 0);
1454 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1455 assert_eq!(underlying_ty, non_ptr(element_ty0));
1457 // The element type of the third argument must be a signed integer type of any width:
1458 match element_ty2.kind() {
1463 "expected element type `{}` of third argument `{}` \
1464 be a signed integer type",
1471 // Alignment of T, must be a constant integer value:
1472 let alignment_ty = bx.type_i32();
1473 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1475 // Truncate the mask vector to a vector of i1s:
1476 let (mask, mask_ty) = {
1477 let i1 = bx.type_i1();
1478 let i1xn = bx.type_vector(i1, in_len);
1479 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1482 let ret_t = bx.type_void();
1484 // Type of the vector of pointers:
1485 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1486 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1488 // Type of the vector of elements:
1489 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1490 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1492 let llvm_intrinsic =
1493 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1495 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t);
1496 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1498 bx.call(fn_ty, f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1502 macro_rules! arith_red {
1503 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1504 $identity:expr) => {
1505 if name == sym::$name {
1508 "expected return type `{}` (element of input `{}`), found `{}`",
1513 return match in_elem.kind() {
1514 ty::Int(_) | ty::Uint(_) => {
1515 let r = bx.$integer_reduce(args[0].immediate());
1517 // if overflow occurs, the result is the
1518 // mathematical result modulo 2^n:
1519 Ok(bx.$op(args[1].immediate(), r))
1521 Ok(bx.$integer_reduce(args[0].immediate()))
1525 let acc = if $ordered {
1526 // ordered arithmetic reductions take an accumulator
1529 // unordered arithmetic reductions use the identity accumulator
1530 match f.bit_width() {
1531 32 => bx.const_real(bx.type_f32(), $identity),
1532 64 => bx.const_real(bx.type_f64(), $identity),
1535 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1544 Ok(bx.$float_reduce(acc, args[0].immediate()))
1547 "unsupported {} from `{}` with element `{}` to `{}`",
1558 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1559 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1561 simd_reduce_add_unordered: vector_reduce_add,
1562 vector_reduce_fadd_fast,
1568 simd_reduce_mul_unordered: vector_reduce_mul,
1569 vector_reduce_fmul_fast,
1575 macro_rules! minmax_red {
1576 ($name:ident: $int_red:ident, $float_red:ident) => {
1577 if name == sym::$name {
1580 "expected return type `{}` (element of input `{}`), found `{}`",
1585 return match in_elem.kind() {
1586 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1587 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1588 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1590 "unsupported {} from `{}` with element `{}` to `{}`",
1601 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1602 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1604 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1605 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1607 macro_rules! bitwise_red {
1608 ($name:ident : $red:ident, $boolean:expr) => {
1609 if name == sym::$name {
1610 let input = if !$boolean {
1613 "expected return type `{}` (element of input `{}`), found `{}`",
1620 match in_elem.kind() {
1621 ty::Int(_) | ty::Uint(_) => {}
1623 "unsupported {} from `{}` with element `{}` to `{}`",
1631 // boolean reductions operate on vectors of i1s:
1632 let i1 = bx.type_i1();
1633 let i1xn = bx.type_vector(i1, in_len as u64);
1634 bx.trunc(args[0].immediate(), i1xn)
1636 return match in_elem.kind() {
1637 ty::Int(_) | ty::Uint(_) => {
1638 let r = bx.$red(input);
1639 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1642 "unsupported {} from `{}` with element `{}` to `{}`",
1653 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
1654 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
1655 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
1656 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
1657 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
1659 if name == sym::simd_cast {
1660 require_simd!(ret_ty, "return");
1661 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1664 "expected return type with length {} (same as input type `{}`), \
1665 found `{}` with length {}",
1671 // casting cares about nominal type, not just structural type
1672 if in_elem == out_elem {
1673 return Ok(args[0].immediate());
1678 Int(/* is signed? */ bool),
1682 let (in_style, in_width) = match in_elem.kind() {
1683 // vectors of pointer-sized integers should've been
1684 // disallowed before here, so this unwrap is safe.
1685 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1686 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1687 ty::Float(f) => (Style::Float, f.bit_width()),
1688 _ => (Style::Unsupported, 0),
1690 let (out_style, out_width) = match out_elem.kind() {
1691 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1692 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1693 ty::Float(f) => (Style::Float, f.bit_width()),
1694 _ => (Style::Unsupported, 0),
1697 match (in_style, out_style) {
1698 (Style::Int(in_is_signed), Style::Int(_)) => {
1699 return Ok(match in_width.cmp(&out_width) {
1700 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1701 Ordering::Equal => args[0].immediate(),
1704 bx.sext(args[0].immediate(), llret_ty)
1706 bx.zext(args[0].immediate(), llret_ty)
1711 (Style::Int(in_is_signed), Style::Float) => {
1712 return Ok(if in_is_signed {
1713 bx.sitofp(args[0].immediate(), llret_ty)
1715 bx.uitofp(args[0].immediate(), llret_ty)
1718 (Style::Float, Style::Int(out_is_signed)) => {
1719 return Ok(if out_is_signed {
1720 bx.fptosi(args[0].immediate(), llret_ty)
1722 bx.fptoui(args[0].immediate(), llret_ty)
1725 (Style::Float, Style::Float) => {
1726 return Ok(match in_width.cmp(&out_width) {
1727 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1728 Ordering::Equal => args[0].immediate(),
1729 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1732 _ => { /* Unsupported. Fallthrough. */ }
1736 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1743 macro_rules! arith_binary {
1744 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1745 $(if name == sym::$name {
1746 match in_elem.kind() {
1747 $($(ty::$p(_))|* => {
1748 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1753 "unsupported operation on `{}` with element `{}`",
1760 simd_add: Uint, Int => add, Float => fadd;
1761 simd_sub: Uint, Int => sub, Float => fsub;
1762 simd_mul: Uint, Int => mul, Float => fmul;
1763 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1764 simd_rem: Uint => urem, Int => srem, Float => frem;
1765 simd_shl: Uint, Int => shl;
1766 simd_shr: Uint => lshr, Int => ashr;
1767 simd_and: Uint, Int => and;
1768 simd_or: Uint, Int => or;
1769 simd_xor: Uint, Int => xor;
1770 simd_fmax: Float => maxnum;
1771 simd_fmin: Float => minnum;
1774 macro_rules! arith_unary {
1775 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1776 $(if name == sym::$name {
1777 match in_elem.kind() {
1778 $($(ty::$p(_))|* => {
1779 return Ok(bx.$call(args[0].immediate()))
1784 "unsupported operation on `{}` with element `{}`",
1791 simd_neg: Int => neg, Float => fneg;
1794 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
1795 let lhs = args[0].immediate();
1796 let rhs = args[1].immediate();
1797 let is_add = name == sym::simd_saturating_add;
1798 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1799 let (signed, elem_width, elem_ty) = match *in_elem.kind() {
1800 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
1801 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
1804 "expected element type `{}` of vector type `{}` \
1805 to be a signed or unsigned integer type",
1806 arg_tys[0].simd_size_and_type(bx.tcx()).1,
1811 let llvm_intrinsic = &format!(
1812 "llvm.{}{}.sat.v{}i{}",
1813 if signed { 's' } else { 'u' },
1814 if is_add { "add" } else { "sub" },
1818 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1820 let fn_ty = bx.type_func(&[vec_ty, vec_ty], vec_ty);
1821 let f = bx.declare_cfn(llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1822 let v = bx.call(fn_ty, f, &[lhs, rhs], None);
1826 span_bug!(span, "unknown SIMD intrinsic");
1829 // Returns the width of an int Ty, and if it's signed or not
1830 // Returns None if the type is not an integer
1831 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1833 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1836 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), true))
1839 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), false))