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;
10 use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh};
11 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
12 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
13 use rustc_codegen_ssa::errors::InvalidMonomorphization;
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, Align, HasDataLayout, Primitive};
23 use rustc_target::spec::{HasTargetSpec, PanicStrategy};
25 use std::cmp::Ordering;
28 fn get_simple_intrinsic<'ll>(
29 cx: &CodegenCx<'ll, '_>,
31 ) -> Option<(&'ll Type, &'ll Value)> {
32 let llvm_name = match name {
33 sym::sqrtf32 => "llvm.sqrt.f32",
34 sym::sqrtf64 => "llvm.sqrt.f64",
35 sym::powif32 => "llvm.powi.f32",
36 sym::powif64 => "llvm.powi.f64",
37 sym::sinf32 => "llvm.sin.f32",
38 sym::sinf64 => "llvm.sin.f64",
39 sym::cosf32 => "llvm.cos.f32",
40 sym::cosf64 => "llvm.cos.f64",
41 sym::powf32 => "llvm.pow.f32",
42 sym::powf64 => "llvm.pow.f64",
43 sym::expf32 => "llvm.exp.f32",
44 sym::expf64 => "llvm.exp.f64",
45 sym::exp2f32 => "llvm.exp2.f32",
46 sym::exp2f64 => "llvm.exp2.f64",
47 sym::logf32 => "llvm.log.f32",
48 sym::logf64 => "llvm.log.f64",
49 sym::log10f32 => "llvm.log10.f32",
50 sym::log10f64 => "llvm.log10.f64",
51 sym::log2f32 => "llvm.log2.f32",
52 sym::log2f64 => "llvm.log2.f64",
53 sym::fmaf32 => "llvm.fma.f32",
54 sym::fmaf64 => "llvm.fma.f64",
55 sym::fabsf32 => "llvm.fabs.f32",
56 sym::fabsf64 => "llvm.fabs.f64",
57 sym::minnumf32 => "llvm.minnum.f32",
58 sym::minnumf64 => "llvm.minnum.f64",
59 sym::maxnumf32 => "llvm.maxnum.f32",
60 sym::maxnumf64 => "llvm.maxnum.f64",
61 sym::copysignf32 => "llvm.copysign.f32",
62 sym::copysignf64 => "llvm.copysign.f64",
63 sym::floorf32 => "llvm.floor.f32",
64 sym::floorf64 => "llvm.floor.f64",
65 sym::ceilf32 => "llvm.ceil.f32",
66 sym::ceilf64 => "llvm.ceil.f64",
67 sym::truncf32 => "llvm.trunc.f32",
68 sym::truncf64 => "llvm.trunc.f64",
69 sym::rintf32 => "llvm.rint.f32",
70 sym::rintf64 => "llvm.rint.f64",
71 sym::nearbyintf32 => "llvm.nearbyint.f32",
72 sym::nearbyintf64 => "llvm.nearbyint.f64",
73 sym::roundf32 => "llvm.round.f32",
74 sym::roundf64 => "llvm.round.f64",
75 sym::ptr_mask => "llvm.ptrmask",
78 Some(cx.get_intrinsic(llvm_name))
81 impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
82 fn codegen_intrinsic_call(
84 instance: ty::Instance<'tcx>,
85 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
86 args: &[OperandRef<'tcx, &'ll Value>],
91 let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
93 let ty::FnDef(def_id, substs) = *callee_ty.kind() else {
94 bug!("expected fn item type, found {}", callee_ty);
97 let sig = callee_ty.fn_sig(tcx);
98 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
99 let arg_tys = sig.inputs();
100 let ret_ty = sig.output();
101 let name = tcx.item_name(def_id);
103 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
104 let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
106 let simple = get_simple_intrinsic(self, name);
107 let llval = match name {
108 _ if simple.is_some() => {
109 let (simple_ty, simple_fn) = simple.unwrap();
114 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
119 self.call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(true)])
121 sym::unlikely => self
122 .call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(false)]),
133 sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[]),
135 self.call_intrinsic("llvm.va_copy", &[args[0].immediate(), args[1].immediate()])
138 match fn_abi.ret.layout.abi {
139 abi::Abi::Scalar(scalar) => {
140 match scalar.primitive() {
141 Primitive::Int(..) => {
142 if self.cx().size_of(ret_ty).bytes() < 4 {
143 // `va_arg` should not be called on an integer type
144 // less than 4 bytes in length. If it is, promote
145 // the integer to an `i32` and truncate the result
146 // back to the smaller type.
147 let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
148 self.trunc(promoted_result, llret_ty)
150 emit_va_arg(self, args[0], ret_ty)
153 Primitive::F64 | Primitive::Pointer => {
154 emit_va_arg(self, args[0], ret_ty)
156 // `va_arg` should never be used with the return type f32.
157 Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
160 _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
164 sym::volatile_load | sym::unaligned_volatile_load => {
165 let tp_ty = substs.type_at(0);
166 let ptr = args[0].immediate();
167 let load = if let PassMode::Cast(ty, _) = &fn_abi.ret.mode {
168 let llty = ty.llvm_type(self);
169 let ptr = self.pointercast(ptr, self.type_ptr_to(llty));
170 self.volatile_load(llty, ptr)
172 self.volatile_load(self.layout_of(tp_ty).llvm_type(self), ptr)
174 let align = if name == sym::unaligned_volatile_load {
177 self.align_of(tp_ty).bytes() as u32
180 llvm::LLVMSetAlignment(load, align);
182 self.to_immediate(load, self.layout_of(tp_ty))
184 sym::volatile_store => {
185 let dst = args[0].deref(self.cx());
186 args[1].val.volatile_store(self, dst);
189 sym::unaligned_volatile_store => {
190 let dst = args[0].deref(self.cx());
191 args[1].val.unaligned_volatile_store(self, dst);
194 sym::prefetch_read_data
195 | sym::prefetch_write_data
196 | sym::prefetch_read_instruction
197 | sym::prefetch_write_instruction => {
198 let (rw, cache_type) = match name {
199 sym::prefetch_read_data => (0, 1),
200 sym::prefetch_write_data => (1, 1),
201 sym::prefetch_read_instruction => (0, 0),
202 sym::prefetch_write_instruction => (1, 0),
211 self.const_i32(cache_type),
224 | sym::saturating_add
225 | sym::saturating_sub => {
227 match int_type_width_signed(ty, self) {
228 Some((width, signed)) => match name {
229 sym::ctlz | sym::cttz => {
230 let y = self.const_bool(false);
232 &format!("llvm.{}.i{}", name, width),
233 &[args[0].immediate(), y],
236 sym::ctlz_nonzero => {
237 let y = self.const_bool(true);
238 let llvm_name = &format!("llvm.ctlz.i{}", width);
239 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
241 sym::cttz_nonzero => {
242 let y = self.const_bool(true);
243 let llvm_name = &format!("llvm.cttz.i{}", width);
244 self.call_intrinsic(llvm_name, &[args[0].immediate(), y])
246 sym::ctpop => self.call_intrinsic(
247 &format!("llvm.ctpop.i{}", width),
248 &[args[0].immediate()],
252 args[0].immediate() // byte swap a u8/i8 is just a no-op
255 &format!("llvm.bswap.i{}", width),
256 &[args[0].immediate()],
260 sym::bitreverse => self.call_intrinsic(
261 &format!("llvm.bitreverse.i{}", width),
262 &[args[0].immediate()],
264 sym::rotate_left | sym::rotate_right => {
265 let is_left = name == sym::rotate_left;
266 let val = args[0].immediate();
267 let raw_shift = args[1].immediate();
268 // rotate = funnel shift with first two args the same
270 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
271 self.call_intrinsic(llvm_name, &[val, val, raw_shift])
273 sym::saturating_add | sym::saturating_sub => {
274 let is_add = name == sym::saturating_add;
275 let lhs = args[0].immediate();
276 let rhs = args[1].immediate();
277 let llvm_name = &format!(
279 if signed { 's' } else { 'u' },
280 if is_add { "add" } else { "sub" },
283 self.call_intrinsic(llvm_name, &[lhs, rhs])
288 tcx.sess.emit_err(InvalidMonomorphization::BasicIntegerType {
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 match self.cx.sess().target.arch.as_ref() {
332 "avr" | "msp430" => self.icmp(IntPredicate::IntEQ, cmp, self.const_i16(0)),
333 _ => self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0)),
339 args[0].val.store(self, result);
340 let result_val_span = [result.llval];
341 // We need to "use" the argument in some way LLVM can't introspect, and on
342 // targets that support it we can typically leverage inline assembly to do
343 // this. LLVM's interpretation of inline assembly is that it's, well, a black
344 // box. This isn't the greatest implementation since it probably deoptimizes
345 // more than we want, but it's so far good enough.
347 // For zero-sized types, the location pointed to by the result may be
348 // uninitialized. Do not "use" the result in this case; instead just clobber
350 let (constraint, inputs): (&str, &[_]) = if result.layout.is_zst() {
353 ("r,~{memory}", &result_val_span)
355 crate::asm::inline_asm_call(
363 llvm::AsmDialect::Att,
368 .unwrap_or_else(|| bug!("failed to generate inline asm call for `black_box`"));
370 // We have copied the value to `result` already.
374 _ if name.as_str().starts_with("simd_") => {
375 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
381 _ => bug!("unknown intrinsic '{}'", name),
384 if !fn_abi.ret.is_ignore() {
385 if let PassMode::Cast(ty, _) = &fn_abi.ret.mode {
386 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
387 let ptr = self.pointercast(result.llval, ptr_llty);
388 self.store(llval, ptr, result.align);
390 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
392 .store(self, result);
397 fn abort(&mut self) {
398 self.call_intrinsic("llvm.trap", &[]);
401 fn assume(&mut self, val: Self::Value) {
402 self.call_intrinsic("llvm.assume", &[val]);
405 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
406 self.call_intrinsic("llvm.expect.i1", &[cond, self.const_bool(expected)])
409 fn type_test(&mut self, pointer: Self::Value, typeid: Self::Value) -> Self::Value {
410 // Test the called operand using llvm.type.test intrinsic. The LowerTypeTests link-time
411 // optimization pass replaces calls to this intrinsic with code to test type membership.
412 let i8p_ty = self.type_i8p();
413 let bitcast = self.bitcast(pointer, i8p_ty);
414 self.call_intrinsic("llvm.type.test", &[bitcast, typeid])
417 fn type_checked_load(
419 llvtable: &'ll Value,
420 vtable_byte_offset: u64,
423 let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
424 let type_checked_load =
425 self.call_intrinsic("llvm.type.checked.load", &[llvtable, vtable_byte_offset, typeid]);
426 self.extract_value(type_checked_load, 0)
429 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
430 self.call_intrinsic("llvm.va_start", &[va_list])
433 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
434 self.call_intrinsic("llvm.va_end", &[va_list])
438 fn try_intrinsic<'ll>(
439 bx: &mut Builder<'_, 'll, '_>,
440 try_func: &'ll Value,
442 catch_func: &'ll Value,
445 if bx.sess().panic_strategy() == PanicStrategy::Abort {
446 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
447 bx.call(try_func_ty, None, try_func, &[data], None);
448 // Return 0 unconditionally from the intrinsic call;
449 // we can never unwind.
450 let ret_align = bx.tcx().data_layout.i32_align.abi;
451 bx.store(bx.const_i32(0), dest, ret_align);
452 } else if wants_msvc_seh(bx.sess()) {
453 codegen_msvc_try(bx, try_func, data, catch_func, dest);
454 } else if bx.sess().target.os == "emscripten" {
455 codegen_emcc_try(bx, try_func, data, catch_func, dest);
457 codegen_gnu_try(bx, try_func, data, catch_func, dest);
461 // MSVC's definition of the `rust_try` function.
463 // This implementation uses the new exception handling instructions in LLVM
464 // which have support in LLVM for SEH on MSVC targets. Although these
465 // instructions are meant to work for all targets, as of the time of this
466 // writing, however, LLVM does not recommend the usage of these new instructions
467 // as the old ones are still more optimized.
468 fn codegen_msvc_try<'ll>(
469 bx: &mut Builder<'_, 'll, '_>,
470 try_func: &'ll Value,
472 catch_func: &'ll Value,
475 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
476 bx.set_personality_fn(bx.eh_personality());
478 let normal = bx.append_sibling_block("normal");
479 let catchswitch = bx.append_sibling_block("catchswitch");
480 let catchpad_rust = bx.append_sibling_block("catchpad_rust");
481 let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
482 let caught = bx.append_sibling_block("caught");
484 let try_func = llvm::get_param(bx.llfn(), 0);
485 let data = llvm::get_param(bx.llfn(), 1);
486 let catch_func = llvm::get_param(bx.llfn(), 2);
488 // We're generating an IR snippet that looks like:
490 // declare i32 @rust_try(%try_func, %data, %catch_func) {
491 // %slot = alloca i8*
492 // invoke %try_func(%data) to label %normal unwind label %catchswitch
498 // %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
501 // %tok = catchpad within %cs [%type_descriptor, 8, %slot]
503 // call %catch_func(%data, %ptr)
504 // catchret from %tok to label %caught
507 // %tok = catchpad within %cs [null, 64, null]
508 // call %catch_func(%data, null)
509 // catchret from %tok to label %caught
515 // This structure follows the basic usage of throw/try/catch in LLVM.
516 // For example, compile this C++ snippet to see what LLVM generates:
518 // struct rust_panic {
519 // rust_panic(const rust_panic&);
526 // void (*try_func)(void*),
528 // void (*catch_func)(void*, void*) noexcept
533 // } catch(rust_panic& a) {
534 // catch_func(data, &a);
537 // catch_func(data, NULL);
542 // More information can be found in libstd's seh.rs implementation.
543 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
544 let slot = bx.alloca(bx.type_i8p(), ptr_align);
545 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
546 bx.invoke(try_func_ty, None, try_func, &[data], normal, catchswitch, None);
548 bx.switch_to_block(normal);
549 bx.ret(bx.const_i32(0));
551 bx.switch_to_block(catchswitch);
552 let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
554 // We can't use the TypeDescriptor defined in libpanic_unwind because it
555 // might be in another DLL and the SEH encoding only supports specifying
556 // a TypeDescriptor from the current module.
558 // However this isn't an issue since the MSVC runtime uses string
559 // comparison on the type name to match TypeDescriptors rather than
562 // So instead we generate a new TypeDescriptor in each module that uses
563 // `try` and let the linker merge duplicate definitions in the same
566 // When modifying, make sure that the type_name string exactly matches
567 // the one used in library/panic_unwind/src/seh.rs.
568 let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
569 let type_name = bx.const_bytes(b"rust_panic\0");
571 bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
572 let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
574 llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
575 llvm::SetUniqueComdat(bx.llmod, tydesc);
576 llvm::LLVMSetInitializer(tydesc, type_info);
579 // The flag value of 8 indicates that we are catching the exception by
580 // reference instead of by value. We can't use catch by value because
581 // that requires copying the exception object, which we don't support
582 // since our exception object effectively contains a Box.
584 // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
585 bx.switch_to_block(catchpad_rust);
586 let flags = bx.const_i32(8);
587 let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
588 let ptr = bx.load(bx.type_i8p(), slot, ptr_align);
589 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
590 bx.call(catch_ty, None, catch_func, &[data, ptr], Some(&funclet));
591 bx.catch_ret(&funclet, caught);
593 // The flag value of 64 indicates a "catch-all".
594 bx.switch_to_block(catchpad_foreign);
595 let flags = bx.const_i32(64);
596 let null = bx.const_null(bx.type_i8p());
597 let funclet = bx.catch_pad(cs, &[null, flags, null]);
598 bx.call(catch_ty, None, catch_func, &[data, null], Some(&funclet));
599 bx.catch_ret(&funclet, caught);
601 bx.switch_to_block(caught);
602 bx.ret(bx.const_i32(1));
605 // Note that no invoke is used here because by definition this function
606 // can't panic (that's what it's catching).
607 let ret = bx.call(llty, None, llfn, &[try_func, data, catch_func], None);
608 let i32_align = bx.tcx().data_layout.i32_align.abi;
609 bx.store(ret, dest, i32_align);
612 // Definition of the standard `try` function for Rust using the GNU-like model
613 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
616 // This codegen is a little surprising because we always call a shim
617 // function instead of inlining the call to `invoke` manually here. This is done
618 // because in LLVM we're only allowed to have one personality per function
619 // definition. The call to the `try` intrinsic is being inlined into the
620 // function calling it, and that function may already have other personality
621 // functions in play. By calling a shim we're guaranteed that our shim will have
622 // the right personality function.
623 fn codegen_gnu_try<'ll>(
624 bx: &mut Builder<'_, 'll, '_>,
625 try_func: &'ll Value,
627 catch_func: &'ll Value,
630 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
631 // Codegens the shims described above:
634 // invoke %try_func(%data) normal %normal unwind %catch
640 // (%ptr, _) = landingpad
641 // call %catch_func(%data, %ptr)
643 let then = bx.append_sibling_block("then");
644 let catch = bx.append_sibling_block("catch");
646 let try_func = llvm::get_param(bx.llfn(), 0);
647 let data = llvm::get_param(bx.llfn(), 1);
648 let catch_func = llvm::get_param(bx.llfn(), 2);
649 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
650 bx.invoke(try_func_ty, None, try_func, &[data], then, catch, None);
652 bx.switch_to_block(then);
653 bx.ret(bx.const_i32(0));
655 // Type indicator for the exception being thrown.
657 // The first value in this tuple is a pointer to the exception object
658 // being thrown. The second value is a "selector" indicating which of
659 // the landing pad clauses the exception's type had been matched to.
660 // rust_try ignores the selector.
661 bx.switch_to_block(catch);
662 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
663 let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
664 let tydesc = bx.const_null(bx.type_i8p());
665 bx.add_clause(vals, tydesc);
666 let ptr = bx.extract_value(vals, 0);
667 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
668 bx.call(catch_ty, None, catch_func, &[data, ptr], None);
669 bx.ret(bx.const_i32(1));
672 // Note that no invoke is used here because by definition this function
673 // can't panic (that's what it's catching).
674 let ret = bx.call(llty, None, llfn, &[try_func, data, catch_func], None);
675 let i32_align = bx.tcx().data_layout.i32_align.abi;
676 bx.store(ret, dest, i32_align);
679 // Variant of codegen_gnu_try used for emscripten where Rust panics are
680 // implemented using C++ exceptions. Here we use exceptions of a specific type
681 // (`struct rust_panic`) to represent Rust panics.
682 fn codegen_emcc_try<'ll>(
683 bx: &mut Builder<'_, 'll, '_>,
684 try_func: &'ll Value,
686 catch_func: &'ll Value,
689 let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
690 // Codegens the shims described above:
693 // invoke %try_func(%data) normal %normal unwind %catch
699 // (%ptr, %selector) = landingpad
700 // %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
701 // %is_rust_panic = %selector == %rust_typeid
702 // %catch_data = alloca { i8*, i8 }
703 // %catch_data[0] = %ptr
704 // %catch_data[1] = %is_rust_panic
705 // call %catch_func(%data, %catch_data)
707 let then = bx.append_sibling_block("then");
708 let catch = bx.append_sibling_block("catch");
710 let try_func = llvm::get_param(bx.llfn(), 0);
711 let data = llvm::get_param(bx.llfn(), 1);
712 let catch_func = llvm::get_param(bx.llfn(), 2);
713 let try_func_ty = bx.type_func(&[bx.type_i8p()], bx.type_void());
714 bx.invoke(try_func_ty, None, try_func, &[data], then, catch, None);
716 bx.switch_to_block(then);
717 bx.ret(bx.const_i32(0));
719 // Type indicator for the exception being thrown.
721 // The first value in this tuple is a pointer to the exception object
722 // being thrown. The second value is a "selector" indicating which of
723 // the landing pad clauses the exception's type had been matched to.
724 bx.switch_to_block(catch);
725 let tydesc = bx.eh_catch_typeinfo();
726 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
727 let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
728 bx.add_clause(vals, tydesc);
729 bx.add_clause(vals, bx.const_null(bx.type_i8p()));
730 let ptr = bx.extract_value(vals, 0);
731 let selector = bx.extract_value(vals, 1);
733 // Check if the typeid we got is the one for a Rust panic.
734 let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[tydesc]);
735 let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
736 let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
738 // We need to pass two values to catch_func (ptr and is_rust_panic), so
739 // create an alloca and pass a pointer to that.
740 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
741 let i8_align = bx.tcx().data_layout.i8_align.abi;
742 let catch_data_type = bx.type_struct(&[bx.type_i8p(), bx.type_bool()], false);
743 let catch_data = bx.alloca(catch_data_type, ptr_align);
745 bx.inbounds_gep(catch_data_type, catch_data, &[bx.const_usize(0), bx.const_usize(0)]);
746 bx.store(ptr, catch_data_0, ptr_align);
748 bx.inbounds_gep(catch_data_type, catch_data, &[bx.const_usize(0), bx.const_usize(1)]);
749 bx.store(is_rust_panic, catch_data_1, i8_align);
750 let catch_data = bx.bitcast(catch_data, bx.type_i8p());
752 let catch_ty = bx.type_func(&[bx.type_i8p(), bx.type_i8p()], bx.type_void());
753 bx.call(catch_ty, None, catch_func, &[data, catch_data], None);
754 bx.ret(bx.const_i32(1));
757 // Note that no invoke is used here because by definition this function
758 // can't panic (that's what it's catching).
759 let ret = bx.call(llty, None, llfn, &[try_func, data, catch_func], None);
760 let i32_align = bx.tcx().data_layout.i32_align.abi;
761 bx.store(ret, dest, i32_align);
764 // Helper function to give a Block to a closure to codegen a shim function.
765 // This is currently primarily used for the `try` intrinsic functions above.
766 fn gen_fn<'ll, 'tcx>(
767 cx: &CodegenCx<'ll, 'tcx>,
769 rust_fn_sig: ty::PolyFnSig<'tcx>,
770 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
771 ) -> (&'ll Type, &'ll Value) {
772 let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
773 let llty = fn_abi.llvm_type(cx);
774 let llfn = cx.declare_fn(name, fn_abi);
775 cx.set_frame_pointer_type(llfn);
776 cx.apply_target_cpu_attr(llfn);
777 // FIXME(eddyb) find a nicer way to do this.
778 unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
779 let llbb = Builder::append_block(cx, llfn, "entry-block");
780 let bx = Builder::build(cx, llbb);
785 // Helper function used to get a handle to the `__rust_try` function used to
788 // This function is only generated once and is then cached.
789 fn get_rust_try_fn<'ll, 'tcx>(
790 cx: &CodegenCx<'ll, 'tcx>,
791 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
792 ) -> (&'ll Type, &'ll Value) {
793 if let Some(llfn) = cx.rust_try_fn.get() {
797 // Define the type up front for the signature of the rust_try function.
799 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
800 // `unsafe fn(*mut i8) -> ()`
801 let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
805 hir::Unsafety::Unsafe,
808 // `unsafe fn(*mut i8, *mut i8) -> ()`
809 let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
810 [i8p, i8p].iter().cloned(),
813 hir::Unsafety::Unsafe,
816 // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
817 let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
818 [try_fn_ty, i8p, catch_fn_ty].into_iter(),
821 hir::Unsafety::Unsafe,
824 let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
825 cx.rust_try_fn.set(Some(rust_try));
829 fn generic_simd_intrinsic<'ll, 'tcx>(
830 bx: &mut Builder<'_, 'll, 'tcx>,
833 args: &[OperandRef<'tcx, &'ll Value>],
837 ) -> Result<&'ll Value, ()> {
838 // macros for error handling:
839 #[allow(unused_macro_rules)]
840 macro_rules! emit_error {
844 ($msg: tt, $($fmt: tt)*) => {
845 span_invalid_monomorphization_error(
847 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
852 macro_rules! return_error {
855 emit_error!($($fmt)*);
861 macro_rules! require {
862 ($cond: expr, $($fmt: tt)*) => {
864 return_error!($($fmt)*);
869 macro_rules! require_simd {
870 ($ty: expr, $position: expr) => {
871 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
877 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), callee_ty.fn_sig(tcx));
878 let arg_tys = sig.inputs();
880 if name == sym::simd_select_bitmask {
881 require_simd!(arg_tys[1], "argument");
882 let (len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
884 let expected_int_bits = (len.max(8) - 1).next_power_of_two();
885 let expected_bytes = len / 8 + ((len % 8 > 0) as u64);
887 let mask_ty = arg_tys[0];
888 let mask = match mask_ty.kind() {
889 ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
890 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
892 if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
893 && len.try_eval_usize(bx.tcx, ty::ParamEnv::reveal_all())
894 == Some(expected_bytes) =>
896 let place = PlaceRef::alloca(bx, args[0].layout);
897 args[0].val.store(bx, place);
898 let int_ty = bx.type_ix(expected_bytes * 8);
899 let ptr = bx.pointercast(place.llval, bx.cx.type_ptr_to(int_ty));
900 bx.load(int_ty, ptr, Align::ONE)
903 "invalid bitmask `{}`, expected `u{}` or `[u8; {}]`",
910 let i1 = bx.type_i1();
911 let im = bx.type_ix(len);
912 let i1xn = bx.type_vector(i1, len);
913 let m_im = bx.trunc(mask, im);
914 let m_i1s = bx.bitcast(m_im, i1xn);
915 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
918 // every intrinsic below takes a SIMD vector as its first argument
919 require_simd!(arg_tys[0], "input");
920 let in_ty = arg_tys[0];
922 let comparison = match name {
923 sym::simd_eq => Some(hir::BinOpKind::Eq),
924 sym::simd_ne => Some(hir::BinOpKind::Ne),
925 sym::simd_lt => Some(hir::BinOpKind::Lt),
926 sym::simd_le => Some(hir::BinOpKind::Le),
927 sym::simd_gt => Some(hir::BinOpKind::Gt),
928 sym::simd_ge => Some(hir::BinOpKind::Ge),
932 let (in_len, in_elem) = arg_tys[0].simd_size_and_type(bx.tcx());
933 if let Some(cmp_op) = comparison {
934 require_simd!(ret_ty, "return");
936 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
939 "expected return type with length {} (same as input type `{}`), \
940 found `{}` with length {}",
947 bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
948 "expected return type with integer elements, found `{}` with non-integer `{}`",
953 return Ok(compare_simd_types(
963 if let Some(stripped) = name.as_str().strip_prefix("simd_shuffle") {
964 // If this intrinsic is the older "simd_shuffleN" form, simply parse the integer.
965 // If there is no suffix, use the index array length.
966 let n: u64 = if stripped.is_empty() {
967 // Make sure this is actually an array, since typeck only checks the length-suffixed
968 // version of this intrinsic.
969 match args[2].layout.ty.kind() {
970 ty::Array(ty, len) if matches!(ty.kind(), ty::Uint(ty::UintTy::U32)) => {
971 len.try_eval_usize(bx.cx.tcx, ty::ParamEnv::reveal_all()).unwrap_or_else(|| {
972 span_bug!(span, "could not evaluate shuffle index array length")
976 "simd_shuffle index must be an array of `u32`, got `{}`",
981 stripped.parse().unwrap_or_else(|_| {
982 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
986 require_simd!(ret_ty, "return");
987 let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx());
990 "expected return type of length {}, found `{}` with length {}",
997 "expected return element type `{}` (element of input `{}`), \
998 found `{}` with element type `{}`",
1005 let total_len = u128::from(in_len) * 2;
1007 let vector = args[2].immediate();
1009 let indices: Option<Vec<_>> = (0..n)
1012 let val = bx.const_get_elt(vector, i as u64);
1013 match bx.const_to_opt_u128(val, true) {
1015 emit_error!("shuffle index #{} is not a constant", arg_idx);
1018 Some(idx) if idx >= total_len => {
1020 "shuffle index #{} is out of bounds (limit {})",
1026 Some(idx) => Some(bx.const_i32(idx as i32)),
1030 let Some(indices) = indices else {
1031 return Ok(bx.const_null(llret_ty));
1034 return Ok(bx.shuffle_vector(
1035 args[0].immediate(),
1036 args[1].immediate(),
1037 bx.const_vector(&indices),
1041 if name == sym::simd_insert {
1043 in_elem == arg_tys[2],
1044 "expected inserted type `{}` (element of input `{}`), found `{}`",
1049 return Ok(bx.insert_element(
1050 args[0].immediate(),
1051 args[2].immediate(),
1052 args[1].immediate(),
1055 if name == sym::simd_extract {
1058 "expected return type `{}` (element of input `{}`), found `{}`",
1063 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1066 if name == sym::simd_select {
1067 let m_elem_ty = in_elem;
1069 require_simd!(arg_tys[1], "argument");
1070 let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1073 "mismatched lengths: mask length `{}` != other vector length `{}`",
1077 match m_elem_ty.kind() {
1079 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1081 // truncate the mask to a vector of i1s
1082 let i1 = bx.type_i1();
1083 let i1xn = bx.type_vector(i1, m_len as u64);
1084 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1085 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1088 if name == sym::simd_bitmask {
1089 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1090 // vector mask and returns the most significant bit (MSB) of each lane in the form
1092 // * an unsigned integer
1093 // * an array of `u8`
1094 // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
1096 // The bit order of the result depends on the byte endianness, LSB-first for little
1097 // endian and MSB-first for big endian.
1098 let expected_int_bits = in_len.max(8);
1099 let expected_bytes = expected_int_bits / 8 + ((expected_int_bits % 8 > 0) as u64);
1101 // Integer vector <i{in_bitwidth} x in_len>:
1102 let (i_xn, in_elem_bitwidth) = match in_elem.kind() {
1104 args[0].immediate(),
1105 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1108 args[0].immediate(),
1109 i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size.bits()),
1112 "vector argument `{}`'s element type `{}`, expected integer element type",
1118 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1121 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1124 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1125 // Truncate vector to an <i1 x N>
1126 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1127 // Bitcast <i1 x N> to iN:
1128 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1130 match ret_ty.kind() {
1131 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
1132 // Zero-extend iN to the bitmask type:
1133 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1135 ty::Array(elem, len)
1136 if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1137 && len.try_eval_usize(bx.tcx, ty::ParamEnv::reveal_all())
1138 == Some(expected_bytes) =>
1140 // Zero-extend iN to the array length:
1141 let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
1143 // Convert the integer to a byte array
1144 let ptr = bx.alloca(bx.type_ix(expected_bytes * 8), Align::ONE);
1145 bx.store(ze, ptr, Align::ONE);
1146 let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
1147 let ptr = bx.pointercast(ptr, bx.cx.type_ptr_to(array_ty));
1148 return Ok(bx.load(array_ty, ptr, Align::ONE));
1151 "cannot return `{}`, expected `u{}` or `[u8; {}]`",
1159 fn simd_simple_float_intrinsic<'ll, 'tcx>(
1164 bx: &mut Builder<'_, 'll, 'tcx>,
1166 args: &[OperandRef<'tcx, &'ll Value>],
1167 ) -> Result<&'ll Value, ()> {
1168 let (elem_ty_str, elem_ty) = if let ty::Float(f) = in_elem.kind() {
1169 let elem_ty = bx.cx.type_float_from_ty(*f);
1170 match f.bit_width() {
1171 32 => ("f32", elem_ty),
1172 64 => ("f64", elem_ty),
1174 bx.sess().emit_err(InvalidMonomorphization::FloatingPointVector {
1184 bx.sess().emit_err(InvalidMonomorphization::FloatingPointType { span, name, in_ty });
1188 let vec_ty = bx.type_vector(elem_ty, in_len);
1190 let (intr_name, fn_ty) = match name {
1191 sym::simd_ceil => ("ceil", bx.type_func(&[vec_ty], vec_ty)),
1192 sym::simd_fabs => ("fabs", bx.type_func(&[vec_ty], vec_ty)),
1193 sym::simd_fcos => ("cos", bx.type_func(&[vec_ty], vec_ty)),
1194 sym::simd_fexp2 => ("exp2", bx.type_func(&[vec_ty], vec_ty)),
1195 sym::simd_fexp => ("exp", bx.type_func(&[vec_ty], vec_ty)),
1196 sym::simd_flog10 => ("log10", bx.type_func(&[vec_ty], vec_ty)),
1197 sym::simd_flog2 => ("log2", bx.type_func(&[vec_ty], vec_ty)),
1198 sym::simd_flog => ("log", bx.type_func(&[vec_ty], vec_ty)),
1199 sym::simd_floor => ("floor", bx.type_func(&[vec_ty], vec_ty)),
1200 sym::simd_fma => ("fma", bx.type_func(&[vec_ty, vec_ty, vec_ty], vec_ty)),
1201 sym::simd_fpowi => ("powi", bx.type_func(&[vec_ty, bx.type_i32()], vec_ty)),
1202 sym::simd_fpow => ("pow", bx.type_func(&[vec_ty, vec_ty], vec_ty)),
1203 sym::simd_fsin => ("sin", bx.type_func(&[vec_ty], vec_ty)),
1204 sym::simd_fsqrt => ("sqrt", bx.type_func(&[vec_ty], vec_ty)),
1205 sym::simd_round => ("round", bx.type_func(&[vec_ty], vec_ty)),
1206 sym::simd_trunc => ("trunc", bx.type_func(&[vec_ty], vec_ty)),
1208 bx.sess().emit_err(InvalidMonomorphization::UnrecognizedIntrinsic { span, name });
1212 let llvm_name = &format!("llvm.{0}.v{1}{2}", intr_name, in_len, elem_ty_str);
1213 let f = bx.declare_cfn(llvm_name, llvm::UnnamedAddr::No, fn_ty);
1218 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1243 return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1247 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1248 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1253 bx: &Builder<'_, '_, '_>,
1255 let p0s: String = "p0".repeat(no_pointers);
1256 match *elem_ty.kind() {
1257 ty::Int(v) => format!(
1261 // Normalize to prevent crash if v: IntTy::Isize
1262 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1264 ty::Uint(v) => format!(
1268 // Normalize to prevent crash if v: UIntTy::Usize
1269 v.normalize(bx.target_spec().pointer_width).bit_width().unwrap()
1271 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1272 _ => unreachable!(),
1276 fn llvm_vector_ty<'ll>(
1277 cx: &CodegenCx<'ll, '_>,
1280 mut no_pointers: usize,
1282 // FIXME: use cx.layout_of(ty).llvm_type() ?
1283 let mut elem_ty = match *elem_ty.kind() {
1284 ty::Int(v) => cx.type_int_from_ty(v),
1285 ty::Uint(v) => cx.type_uint_from_ty(v),
1286 ty::Float(v) => cx.type_float_from_ty(v),
1287 _ => unreachable!(),
1289 while no_pointers > 0 {
1290 elem_ty = cx.type_ptr_to(elem_ty);
1293 cx.type_vector(elem_ty, vec_len)
1296 if name == sym::simd_gather {
1297 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1298 // mask: <N x i{M}>) -> <N x T>
1299 // * N: number of elements in the input vectors
1300 // * T: type of the element to load
1301 // * M: any integer width is supported, will be truncated to i1
1303 // All types must be simd vector types
1304 require_simd!(in_ty, "first");
1305 require_simd!(arg_tys[1], "second");
1306 require_simd!(arg_tys[2], "third");
1307 require_simd!(ret_ty, "return");
1309 // Of the same length:
1310 let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1311 let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1314 "expected {} argument with length {} (same as input type `{}`), \
1315 found `{}` with length {}",
1324 "expected {} argument with length {} (same as input type `{}`), \
1325 found `{}` with length {}",
1333 // The return type must match the first argument type
1334 require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1336 // This counts how many pointers
1337 fn ptr_count(t: Ty<'_>) -> usize {
1339 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1345 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1347 ty::RawPtr(p) => non_ptr(p.ty),
1352 // The second argument must be a simd vector with an element type that's a pointer
1353 // to the element type of the first argument
1354 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1355 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1356 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1357 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(element_ty1), non_ptr(element_ty1)),
1361 "expected element type `{}` of second argument `{}` \
1362 to be a pointer to the element type `{}` of the first \
1363 argument `{}`, found `{}` != `*_ {}`",
1374 assert!(pointer_count > 0);
1375 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1376 assert_eq!(underlying_ty, non_ptr(element_ty0));
1378 // The element type of the third argument must be a signed integer type of any width:
1379 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1380 match element_ty2.kind() {
1385 "expected element type `{}` of third argument `{}` \
1386 to be a signed integer type",
1393 // Alignment of T, must be a constant integer value:
1394 let alignment_ty = bx.type_i32();
1395 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1397 // Truncate the mask vector to a vector of i1s:
1398 let (mask, mask_ty) = {
1399 let i1 = bx.type_i1();
1400 let i1xn = bx.type_vector(i1, in_len);
1401 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1404 // Type of the vector of pointers:
1405 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1406 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1408 // Type of the vector of elements:
1409 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1410 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1412 let llvm_intrinsic =
1413 format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1414 let fn_ty = bx.type_func(
1415 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1418 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1423 &[args[1].immediate(), alignment, mask, args[0].immediate()],
1429 if name == sym::simd_scatter {
1430 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1431 // mask: <N x i{M}>) -> ()
1432 // * N: number of elements in the input vectors
1433 // * T: type of the element to load
1434 // * M: any integer width is supported, will be truncated to i1
1436 // All types must be simd vector types
1437 require_simd!(in_ty, "first");
1438 require_simd!(arg_tys[1], "second");
1439 require_simd!(arg_tys[2], "third");
1441 // Of the same length:
1442 let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx());
1443 let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx());
1445 in_len == element_len1,
1446 "expected {} argument with length {} (same as input type `{}`), \
1447 found `{}` with length {}",
1455 in_len == element_len2,
1456 "expected {} argument with length {} (same as input type `{}`), \
1457 found `{}` with length {}",
1465 // This counts how many pointers
1466 fn ptr_count(t: Ty<'_>) -> usize {
1468 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1474 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1476 ty::RawPtr(p) => non_ptr(p.ty),
1481 // The second argument must be a simd vector with an element type that's a pointer
1482 // to the element type of the first argument
1483 let (_, element_ty0) = arg_tys[0].simd_size_and_type(bx.tcx());
1484 let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx());
1485 let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx());
1486 let (pointer_count, underlying_ty) = match element_ty1.kind() {
1487 ty::RawPtr(p) if p.ty == in_elem && p.mutbl.is_mut() => {
1488 (ptr_count(element_ty1), non_ptr(element_ty1))
1493 "expected element type `{}` of second argument `{}` \
1494 to be a pointer to the element type `{}` of the first \
1495 argument `{}`, found `{}` != `*mut {}`",
1506 assert!(pointer_count > 0);
1507 assert_eq!(pointer_count - 1, ptr_count(element_ty0));
1508 assert_eq!(underlying_ty, non_ptr(element_ty0));
1510 // The element type of the third argument must be a signed integer type of any width:
1511 match element_ty2.kind() {
1516 "expected element type `{}` of third argument `{}` \
1517 be a signed integer type",
1524 // Alignment of T, must be a constant integer value:
1525 let alignment_ty = bx.type_i32();
1526 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1528 // Truncate the mask vector to a vector of i1s:
1529 let (mask, mask_ty) = {
1530 let i1 = bx.type_i1();
1531 let i1xn = bx.type_vector(i1, in_len);
1532 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1535 let ret_t = bx.type_void();
1537 // Type of the vector of pointers:
1538 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1539 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count, bx);
1541 // Type of the vector of elements:
1542 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1543 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1, bx);
1545 let llvm_intrinsic =
1546 format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1548 bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t);
1549 let f = bx.declare_cfn(&llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
1554 &[args[0].immediate(), args[1].immediate(), alignment, mask],
1560 macro_rules! arith_red {
1561 ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1562 $identity:expr) => {
1563 if name == sym::$name {
1566 "expected return type `{}` (element of input `{}`), found `{}`",
1571 return match in_elem.kind() {
1572 ty::Int(_) | ty::Uint(_) => {
1573 let r = bx.$integer_reduce(args[0].immediate());
1575 // if overflow occurs, the result is the
1576 // mathematical result modulo 2^n:
1577 Ok(bx.$op(args[1].immediate(), r))
1579 Ok(bx.$integer_reduce(args[0].immediate()))
1583 let acc = if $ordered {
1584 // ordered arithmetic reductions take an accumulator
1587 // unordered arithmetic reductions use the identity accumulator
1588 match f.bit_width() {
1589 32 => bx.const_real(bx.type_f32(), $identity),
1590 64 => bx.const_real(bx.type_f64(), $identity),
1593 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1602 Ok(bx.$float_reduce(acc, args[0].immediate()))
1605 "unsupported {} from `{}` with element `{}` to `{}`",
1616 arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1617 arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1619 simd_reduce_add_unordered: vector_reduce_add,
1620 vector_reduce_fadd_fast,
1626 simd_reduce_mul_unordered: vector_reduce_mul,
1627 vector_reduce_fmul_fast,
1633 macro_rules! minmax_red {
1634 ($name:ident: $int_red:ident, $float_red:ident) => {
1635 if name == sym::$name {
1638 "expected return type `{}` (element of input `{}`), found `{}`",
1643 return match in_elem.kind() {
1644 ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
1645 ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
1646 ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
1648 "unsupported {} from `{}` with element `{}` to `{}`",
1659 minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
1660 minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
1662 minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
1663 minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
1665 macro_rules! bitwise_red {
1666 ($name:ident : $red:ident, $boolean:expr) => {
1667 if name == sym::$name {
1668 let input = if !$boolean {
1671 "expected return type `{}` (element of input `{}`), found `{}`",
1678 match in_elem.kind() {
1679 ty::Int(_) | ty::Uint(_) => {}
1681 "unsupported {} from `{}` with element `{}` to `{}`",
1689 // boolean reductions operate on vectors of i1s:
1690 let i1 = bx.type_i1();
1691 let i1xn = bx.type_vector(i1, in_len as u64);
1692 bx.trunc(args[0].immediate(), i1xn)
1694 return match in_elem.kind() {
1695 ty::Int(_) | ty::Uint(_) => {
1696 let r = bx.$red(input);
1697 Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
1700 "unsupported {} from `{}` with element `{}` to `{}`",
1711 bitwise_red!(simd_reduce_and: vector_reduce_and, false);
1712 bitwise_red!(simd_reduce_or: vector_reduce_or, false);
1713 bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
1714 bitwise_red!(simd_reduce_all: vector_reduce_and, true);
1715 bitwise_red!(simd_reduce_any: vector_reduce_or, true);
1717 if name == sym::simd_cast_ptr {
1718 require_simd!(ret_ty, "return");
1719 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1722 "expected return type with length {} (same as input type `{}`), \
1723 found `{}` with length {}",
1730 match in_elem.kind() {
1732 let (metadata, check_sized) = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
1733 bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty)
1735 assert!(!check_sized); // we are in codegen, so we shouldn't see these types
1736 require!(metadata.is_unit(), "cannot cast fat pointer `{}`", in_elem)
1738 _ => return_error!("expected pointer, got `{}`", in_elem),
1740 match out_elem.kind() {
1742 let (metadata, check_sized) = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
1743 bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty)
1745 assert!(!check_sized); // we are in codegen, so we shouldn't see these types
1746 require!(metadata.is_unit(), "cannot cast to fat pointer `{}`", out_elem)
1748 _ => return_error!("expected pointer, got `{}`", out_elem),
1751 if in_elem == out_elem {
1752 return Ok(args[0].immediate());
1754 return Ok(bx.pointercast(args[0].immediate(), llret_ty));
1758 if name == sym::simd_expose_addr {
1759 require_simd!(ret_ty, "return");
1760 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1763 "expected return type with length {} (same as input type `{}`), \
1764 found `{}` with length {}",
1771 match in_elem.kind() {
1773 _ => return_error!("expected pointer, got `{}`", in_elem),
1775 match out_elem.kind() {
1776 ty::Uint(ty::UintTy::Usize) => {}
1777 _ => return_error!("expected `usize`, got `{}`", out_elem),
1780 return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
1783 if name == sym::simd_from_exposed_addr {
1784 require_simd!(ret_ty, "return");
1785 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1788 "expected return type with length {} (same as input type `{}`), \
1789 found `{}` with length {}",
1796 match in_elem.kind() {
1797 ty::Uint(ty::UintTy::Usize) => {}
1798 _ => return_error!("expected `usize`, got `{}`", in_elem),
1800 match out_elem.kind() {
1802 _ => return_error!("expected pointer, got `{}`", out_elem),
1805 return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
1808 if name == sym::simd_cast || name == sym::simd_as {
1809 require_simd!(ret_ty, "return");
1810 let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx());
1813 "expected return type with length {} (same as input type `{}`), \
1814 found `{}` with length {}",
1820 // casting cares about nominal type, not just structural type
1821 if in_elem == out_elem {
1822 return Ok(args[0].immediate());
1827 Int(/* is signed? */ bool),
1831 let (in_style, in_width) = match in_elem.kind() {
1832 // vectors of pointer-sized integers should've been
1833 // disallowed before here, so this unwrap is safe.
1836 i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1840 u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1842 ty::Float(f) => (Style::Float, f.bit_width()),
1843 _ => (Style::Unsupported, 0),
1845 let (out_style, out_width) = match out_elem.kind() {
1848 i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1852 u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
1854 ty::Float(f) => (Style::Float, f.bit_width()),
1855 _ => (Style::Unsupported, 0),
1858 match (in_style, out_style) {
1859 (Style::Int(in_is_signed), Style::Int(_)) => {
1860 return Ok(match in_width.cmp(&out_width) {
1861 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1862 Ordering::Equal => args[0].immediate(),
1865 bx.sext(args[0].immediate(), llret_ty)
1867 bx.zext(args[0].immediate(), llret_ty)
1872 (Style::Int(in_is_signed), Style::Float) => {
1873 return Ok(if in_is_signed {
1874 bx.sitofp(args[0].immediate(), llret_ty)
1876 bx.uitofp(args[0].immediate(), llret_ty)
1879 (Style::Float, Style::Int(out_is_signed)) => {
1880 return Ok(match (out_is_signed, name == sym::simd_as) {
1881 (false, false) => bx.fptoui(args[0].immediate(), llret_ty),
1882 (true, false) => bx.fptosi(args[0].immediate(), llret_ty),
1883 (_, true) => bx.cast_float_to_int(out_is_signed, args[0].immediate(), llret_ty),
1886 (Style::Float, Style::Float) => {
1887 return Ok(match in_width.cmp(&out_width) {
1888 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1889 Ordering::Equal => args[0].immediate(),
1890 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
1893 _ => { /* Unsupported. Fallthrough. */ }
1897 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1904 macro_rules! arith_binary {
1905 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1906 $(if name == sym::$name {
1907 match in_elem.kind() {
1908 $($(ty::$p(_))|* => {
1909 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1914 "unsupported operation on `{}` with element `{}`",
1921 simd_add: Uint, Int => add, Float => fadd;
1922 simd_sub: Uint, Int => sub, Float => fsub;
1923 simd_mul: Uint, Int => mul, Float => fmul;
1924 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1925 simd_rem: Uint => urem, Int => srem, Float => frem;
1926 simd_shl: Uint, Int => shl;
1927 simd_shr: Uint => lshr, Int => ashr;
1928 simd_and: Uint, Int => and;
1929 simd_or: Uint, Int => or;
1930 simd_xor: Uint, Int => xor;
1931 simd_fmax: Float => maxnum;
1932 simd_fmin: Float => minnum;
1935 macro_rules! arith_unary {
1936 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1937 $(if name == sym::$name {
1938 match in_elem.kind() {
1939 $($(ty::$p(_))|* => {
1940 return Ok(bx.$call(args[0].immediate()))
1945 "unsupported operation on `{}` with element `{}`",
1952 simd_neg: Int => neg, Float => fneg;
1955 if name == sym::simd_arith_offset {
1956 // This also checks that the first operand is a ptr type.
1957 let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
1958 span_bug!(span, "must be called with a vector of pointer types as first argument")
1960 let layout = bx.layout_of(pointee.ty);
1961 let ptrs = args[0].immediate();
1962 // The second argument must be a ptr-sized integer.
1963 // (We don't care about the signedness, this is wrapping anyway.)
1964 let (_offsets_len, offsets_elem) = arg_tys[1].simd_size_and_type(bx.tcx());
1965 if !matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
1968 "must be called with a vector of pointer-sized integers as second argument"
1971 let offsets = args[1].immediate();
1973 return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
1976 if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
1977 let lhs = args[0].immediate();
1978 let rhs = args[1].immediate();
1979 let is_add = name == sym::simd_saturating_add;
1980 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1981 let (signed, elem_width, elem_ty) = match *in_elem.kind() {
1982 ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
1983 ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
1986 "expected element type `{}` of vector type `{}` \
1987 to be a signed or unsigned integer type",
1988 arg_tys[0].simd_size_and_type(bx.tcx()).1,
1993 let llvm_intrinsic = &format!(
1994 "llvm.{}{}.sat.v{}i{}",
1995 if signed { 's' } else { 'u' },
1996 if is_add { "add" } else { "sub" },
2000 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2002 let fn_ty = bx.type_func(&[vec_ty, vec_ty], vec_ty);
2003 let f = bx.declare_cfn(llvm_intrinsic, llvm::UnnamedAddr::No, fn_ty);
2004 let v = bx.call(fn_ty, None, f, &[lhs, rhs], None);
2008 span_bug!(span, "unknown SIMD intrinsic");
2011 // Returns the width of an int Ty, and if it's signed or not
2012 // Returns None if the type is not an integer
2013 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2015 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2018 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), true))
2021 Some((t.bit_width().unwrap_or(u64::from(cx.tcx.sess.target.pointer_width)), false))