blob: 6701ca16f817d649470ec51df47e6b395a25cc15 [file]
use std::{assert_matches, cmp};
use libc::c_uint;
use rustc_abi::{
ArmCall, BackendRepr, CanonAbi, Float, HasDataLayout, InterruptKind, Primitive, Reg, RegKind,
Size, X86Call,
};
use rustc_codegen_ssa::MemFlags;
use rustc_codegen_ssa::common::RealPredicate;
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
use rustc_codegen_ssa::traits::*;
use rustc_middle::ty;
use rustc_middle::ty::Ty;
use rustc_middle::ty::layout::LayoutOf;
use rustc_session::{Session, config};
use rustc_span::bug;
use rustc_target::callconv::{
ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, CastTarget, FnAbi, IndirectMode, PassMode,
};
use rustc_target::spec::{Arch, SanitizerSet};
use smallvec::SmallVec;
use crate::attributes::{self, llfn_attrs_from_instance};
use crate::builder::Builder;
use crate::context::CodegenCx;
use crate::llvm::{self, Attribute, AttributePlace, Type, Value};
use crate::type_of::LayoutLlvmExt;
trait ArgAttributesExt {
fn apply_attrs_to_llfn<'ll>(
&self,
idx: AttributePlace,
cx: &CodegenCx<'ll, '_>,
llfn: Value<'ll>,
);
fn apply_attrs_to_callsite<'ll>(
&self,
idx: AttributePlace,
cx: &CodegenCx<'ll, '_>,
callsite: Value<'ll>,
);
}
const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
[(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 6] = [
(ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
(ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
(ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
(ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
(ArgAttribute::Writable, llvm::AttributeKind::Writable),
// Our internal NoFree attribute still allows deallocation of zero-size allocations. However,
// these don't render any bytes non-dereferenceable, so it's still fine to apply LLVM NoFree
// for them.
(ArgAttribute::NoFree, llvm::AttributeKind::NoFree),
];
const CAPTURES_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 3] = [
(ArgAttribute::CapturesNone, llvm::AttributeKind::CapturesNone),
(ArgAttribute::CapturesAddress, llvm::AttributeKind::CapturesAddress),
(ArgAttribute::CapturesReadOnly, llvm::AttributeKind::CapturesReadOnly),
];
fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[Attribute<'ll>; 8]> {
let mut regular = this.regular;
let mut attrs = SmallVec::new();
// ABI-affecting attributes must always be applied
for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
if regular.contains(attr) {
attrs.push(llattr.create_attr(cx.llcx));
}
}
if let Some(align) = this.pointee_align {
attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
}
match this.arg_ext {
ArgExtension::None => {}
ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
}
// Only apply remaining attributes when optimizing
if cx.sess().opts.optimize != config::OptLevel::No {
let deref = this.pointee_size.bytes();
// Prior to <https://github.com/llvm/llvm-project/pull/204795> dereferenceable in LLVM
// implied nofree, so only emit dereferenceable on older versions of LLVM if nofree
// is also set.
let llvm_version = crate::llvm_util::get_version();
if deref != 0 && (llvm_version >= (23, 0, 0) || regular.contains(ArgAttribute::NoFree)) {
if regular.contains(ArgAttribute::NonNull) {
attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
} else {
attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
}
regular -= ArgAttribute::NonNull;
}
for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
if regular.contains(attr) {
attrs.push(llattr.create_attr(cx.llcx));
}
}
for (attr, llattr) in CAPTURES_ATTRIBUTES {
if regular.contains(attr) {
attrs.push(llattr.create_attr(cx.llcx));
break;
}
}
} else if cx.tcx.sess.sanitizers().contains(SanitizerSet::MEMORY) {
// If we're not optimising, *but* memory sanitizer is on, emit noundef, since it affects
// memory sanitizer's behavior.
if regular.contains(ArgAttribute::NoUndef) {
attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
}
}
attrs
}
impl ArgAttributesExt for ArgAttributes {
fn apply_attrs_to_llfn<'ll>(
&self,
idx: AttributePlace,
cx: &CodegenCx<'ll, '_>,
llfn: Value<'ll>,
) {
let attrs = get_attrs(self, cx);
attributes::apply_to_llfn(llfn, idx, &attrs);
}
fn apply_attrs_to_callsite<'ll>(
&self,
idx: AttributePlace,
cx: &CodegenCx<'ll, '_>,
callsite: Value<'ll>,
) {
let attrs = get_attrs(self, cx);
attributes::apply_to_callsite(callsite, idx, &attrs);
}
}
pub(crate) trait LlvmType {
fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> Type<'ll>;
}
impl LlvmType for Reg {
fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> Type<'ll> {
match self.kind {
RegKind::Integer => cx.type_ix(self.size.bits()),
RegKind::Float => match self.size.bits() {
16 => cx.type_f16(),
32 => cx.type_f32(),
64 => cx.type_f64(),
80 => cx.type_x87_f80(),
128 => cx.type_f128(),
_ => bug!("unsupported float: {:?}", self),
},
RegKind::PpcF128 => cx.type_ppcf128(),
RegKind::Vector { hint_vector_elem } => {
// NOTE: it is valid to ignore the element type hint (and always pick i8).
// But providing a more accurate type means fewer casts in LLVM IR,
// which helps with optimization.
assert!(
!matches!(hint_vector_elem, Primitive::Float(Float::PpcF128 | Float::X87F80)),
"Unsupported vector element type"
);
let ty = cx.type_from_primitive(hint_vector_elem);
assert!(self.size.bytes().is_multiple_of(hint_vector_elem.size(cx).bytes()));
let len = self.size.bytes() / hint_vector_elem.size(cx).bytes();
cx.type_vector(ty, len)
}
}
}
}
impl LlvmType for CastTarget {
fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> Type<'ll> {
if self.pass_via_x87_floating_point_stack {
return cx.type_x87_f80();
}
let rest_ll_unit = self.rest.unit.llvm_type(cx);
let rest_count = if self.rest.total == Size::ZERO {
0
} else {
assert_ne!(
self.rest.unit.size,
Size::ZERO,
"total size {:?} cannot be divided into units of zero size",
self.rest.total
);
if !self.rest.total.bytes().is_multiple_of(self.rest.unit.size.bytes()) {
assert_eq!(self.rest.unit.kind, RegKind::Integer, "only int regs can be split");
}
self.rest.total.bytes().div_ceil(self.rest.unit.size.bytes())
};
// Simplify to an array if there is no prefix.
if self.prefix.is_empty() {
// Pass `[1 x unit]` as just `unit`.
//
// On little-endian targets this produces a compatible layout, but using a simpler type.
// But on big-endian targets (e.g. aarch64_be or powerpc64) the value may be passed in
// different halves of the register-sized slot, so unit and [1 x unit] are incompatible.
//
// Setting `is_consecutive` forces use of an array.
if rest_count == 1 && !self.rest.is_consecutive {
return rest_ll_unit;
}
// The x87_f80 type has a store size of 10 bytes, but an allocation size of 12 or 16
// bytes. Ensure we don't cast to it, because that could have unintened behavior.
assert!(rest_ll_unit != cx.type_x87_f80());
return cx.type_array(rest_ll_unit, rest_count);
}
// Generate a struct type with the prefix and the "rest" arguments.
let prefix_args = self.prefix.iter().map(|reg| reg.llvm_type(cx));
let rest_args = (0..rest_count).map(|_| rest_ll_unit);
let args: Vec<_> = prefix_args.chain(rest_args).collect();
// The x87_f80 type has a store size of 10 bytes, but an allocation size of 12 or 16 bytes.
// Ensure we don't cast to it, because that could have unintened behavior.
//
// Make an exception when using a `rest_offset`, which is used when returning
// `Complex<x87_f80>`.
assert!(self.rest_offset.is_some() || args.iter().all(|a| *a != cx.type_x87_f80()));
cx.type_struct(&args)
}
}
trait ArgAbiExt<'ll, 'tcx> {
fn store(
&self,
bx: &mut Builder<'_, 'll, 'tcx>,
val: Value<'ll>,
dst: PlaceRef<'tcx, Value<'ll>>,
);
fn store_fn_arg(
&self,
bx: &mut Builder<'_, 'll, 'tcx>,
idx: &mut usize,
dst: PlaceRef<'tcx, Value<'ll>>,
);
}
impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
/// Stores a direct/indirect value described by this ArgAbi into a
/// place for the original Rust type of this argument/return.
/// Can be used for both storing formal arguments into Rust variables
/// or results of call/invoke instructions into their destinations.
fn store(
&self,
bx: &mut Builder<'_, 'll, 'tcx>,
val: Value<'ll>,
dst: PlaceRef<'tcx, Value<'ll>>,
) {
match &self.mode {
PassMode::Ignore => {}
// Sized indirect arguments
PassMode::Indirect { attrs, address_space: _, mode: _ } => {
let align = attrs.pointee_align.unwrap_or(self.layout.align);
OperandValue::Ref(PlaceValue::new_sized(val, align)).store(bx, dst);
}
// Unsized indirect arguments cannot be stored
PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
bug!("unsized `ArgAbi` cannot be stored");
}
PassMode::Cast { cast, pad_i32_count: _ } => {
// The ABI mandates that the value is passed as a different struct representation.
// Spill and reload it from the stack to convert from the ABI representation to
// the Rust representation.
let scratch_size = cast.size(bx);
let scratch_align = cast.align(bx);
// Note that the ABI type may be either larger or smaller than the Rust type,
// due to the presence or absence of trailing padding. For example:
// - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
// when passed by value, making it smaller.
// - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
// when passed by value, making it larger.
let copy_bytes =
cmp::min(cast.unaligned_size(bx).bytes(), self.layout.size.bytes());
// Allocate some scratch space...
let llscratch = bx.alloca(scratch_size, scratch_align);
bx.lifetime_start(llscratch, scratch_size);
// ...store the value...
rustc_codegen_ssa::mir::store_cast(bx, cast, val, llscratch, scratch_align);
// ... and then memcpy it to the intended destination.
bx.memcpy(
dst.val.llval,
self.layout.align,
llscratch,
scratch_align,
bx.const_usize(copy_bytes),
MemFlags::empty(),
None,
);
bx.lifetime_end(llscratch, scratch_size);
}
PassMode::Pair(..) | PassMode::Direct { .. } => {
OperandRef::from_immediate_or_packed_pair(bx, val, self.layout).val.store(bx, dst);
}
}
}
fn store_fn_arg(
&self,
bx: &mut Builder<'_, 'll, 'tcx>,
idx: &mut usize,
dst: PlaceRef<'tcx, Value<'ll>>,
) {
let mut next = || {
let val = llvm::get_param(bx.llfn(), *idx as c_uint);
*idx += 1;
val
};
match self.mode {
PassMode::Ignore => {}
PassMode::Pair(..) => {
OperandValue::Pair(next(), next()).store(bx, dst);
}
PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
bug!("unsized `ArgAbi` cannot be stored");
}
PassMode::Direct(_)
| PassMode::Indirect { attrs: _, address_space: _, mode: _ }
| PassMode::Cast { .. } => {
let next_arg = next();
self.store(bx, next_arg, dst);
}
}
}
}
impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
fn store_fn_arg(
&mut self,
arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
idx: &mut usize,
dst: PlaceRef<'tcx, Self::Value>,
) {
arg_abi.store_fn_arg(self, idx, dst)
}
fn store_arg(
&mut self,
arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
val: Value<'ll>,
dst: PlaceRef<'tcx, Value<'ll>>,
) {
arg_abi.store(self, val, dst)
}
fn x87_lossless_float_to_fp_stack(&mut self, value: Value<'ll>, no_undef: bool) -> Value<'ll> {
// If value is (partially) uninitialized (e.g. when returning `MaybeUninit<f64>`) then e.g.
// branching on it could lead to undefined behaviour. To ensure that doesn't happen and that
// any initialized bytes within a partially uninitialized value survive the round trip,
// freeze the value.
let value = if no_undef { value } else { self.freeze(value) };
// While we only need to manually convert sNaNs, all NaNs can be converted the same way and
// checking whether `value` is NaN only takes a single floating-point x86 instruction,
// whereas checking if it is a signalling NaN additionally requires bit operations. LLVM
// also generally won't know a non-constant `value` is not a sNaN but could be a qNaN, so
// being more general here doesn't prevent the branch from being optimised out in likely
// scenarios.
let is_nan = self.fcmp(RealPredicate::RealUNO, value, value);
let is_nan_block = self.append_sibling_block("float_pre_ret.is_nan");
let is_not_nan_block = self.append_sibling_block("float_pre_ret.is_not_nan");
let after_block = self.append_sibling_block("float_pre_ret.after");
let dbg_loc = self.get_dbg_loc();
self.cond_br(is_nan, is_nan_block, is_not_nan_block);
self.switch_to_block(is_nan_block);
if let Some(dbg_loc) = dbg_loc {
self.set_dbg_loc(dbg_loc);
}
// This manually converts a NaN to `x87_f80` to avoid the quiet NaN bit of signalling NaNs
// getting set. `f32`/`f64` and `x87_f80` have the same components (sign, exponent,
// significand) in the same order except that `x87_f80` has a wider exponent and
// significand, and the `x87_f80` significand has an explicit integer bit (which is always
// 1 for NaNs).
let value_type = self.val_ty(value);
let Some(float_type) = self.float_type(value_type) else {
bug!("{value_type:?} is not a float type");
};
assert_matches!(
float_type,
Float::F32 | Float::F64,
"attempt to return {float_type:?} on the x87 floating point stack",
);
let num_bits = float_type.size().bits();
let bits_ty = self.type_ix(num_bits);
let bits = self.bitcast(value, bits_ty);
// The high 16 bits of an x87_f80 are the exponent and sign (the sign is the highest
// bit) NaNs always have all bits of the exponent set to 1, so the only bit that is
// needed from `value` is the sign bit.
// Shift out the lower bits.
let exp_and_sign = self.lshr(bits, self.const_uint(bits_ty, num_bits - 16));
// Set the exponent to all 1s.
let exp_and_sign = self.or(exp_and_sign, self.const_uint(bits_ty, 0x7FFF));
// Shift the exponent and sign into position.
let exp_and_sign = self.zext(exp_and_sign, self.type_ix(80));
let exp_and_sign = self.shl(exp_and_sign, self.const_uint_big(self.type_ix(80), 64));
// The fraction of the input NaN needs to be shifted left to just before x87_f80's
// explicit integer bit. There's no need to manually set the integer bit itself, as it
// will be already set to 1 due to the all 1s exponent in the input NaN.
let (fraction_bits, fraction) = match num_bits {
32 => (f32::MANTISSA_DIGITS - 1, self.zext(bits, self.type_i64())),
64 => (f64::MANTISSA_DIGITS - 1, bits),
_ => bug!(),
};
// Shift the fraction into position.
let fraction = self.shl(fraction, self.const_u64(63 - u64::from(fraction_bits)));
let fraction = self.zext(fraction, self.type_ix(80));
let is_nan_res = self.or(exp_and_sign, fraction);
let is_nan_res = self.bitcast(is_nan_res, self.type_x87_f80());
self.br(after_block);
self.switch_to_block(is_not_nan_block);
if let Some(dbg_loc) = dbg_loc {
self.set_dbg_loc(dbg_loc);
}
let is_not_nan_res = self.fpext(value, self.type_x87_f80());
self.br(after_block);
self.switch_to_block(after_block);
if let Some(dbg_loc) = dbg_loc {
self.set_dbg_loc(dbg_loc);
}
self.phi(
self.type_x87_f80(),
&[is_nan_res, is_not_nan_res],
&[is_nan_block, is_not_nan_block],
)
}
fn x87_lossless_fp_stack_to_float(
&mut self,
value: Value<'ll>,
float_type: Type<'ll>,
no_undef: bool,
) -> Value<'ll> {
// If value is (partially) uninitialized (e.g. when returning `MaybeUninit<f64>`) then e.g.
// branching on it could lead to undefined behaviour. To ensure that doesn't happen and that
// any initialized bytes within a partially uninitialized value survive the round trip,
// freeze the value.
let value = if no_undef { value } else { self.freeze(value) };
let Some(float) = self.float_type(float_type) else {
bug!("{float_type:?} is not a float type");
};
let fraction_bits = u64::from(match float {
Float::F32 => f32::MANTISSA_DIGITS - 1,
Float::F64 => f64::MANTISSA_DIGITS - 1,
_ => bug!("attempt to return {float:?} on the x87 floating point stack"),
});
let num_bits = float.size().bits();
let dest_bits_type = self.type_ix(num_bits);
// While we only need to manually convert sNaNs, all NaNs can be converted the same way and
// checking whether `value` is NaN only takes a single floating-point x86 instruction,
// whereas checking if it is a signalling NaN additionally requires bit operations. LLVM
// also generally won't know a non-constant `value` is not a sNaN but could be a qNaN, so
// being more general here doesn't prevent the branch from being optimised out in likely
// scenarios.
let is_nan = self.fcmp(RealPredicate::RealUNO, value, value);
let is_nan_block = self.append_sibling_block("float_post_ret.is_nan");
let is_not_nan_block = self.append_sibling_block("float_post_ret.is_not_nan");
let after_block = self.append_sibling_block("float_post_ret.after");
let dbg_loc = self.get_dbg_loc();
self.cond_br(is_nan, is_nan_block, is_not_nan_block);
self.switch_to_block(is_nan_block);
if let Some(dbg_loc) = dbg_loc {
self.set_dbg_loc(dbg_loc);
}
// This block converts a NaN to `x87_f80` manually to avoid setting the quiet NaN bit of
// signalling NaNs.
// We don't handle the "invalid operand" bitpatterns here (which are treated like NaNs) as
// they can't be generated by any post-80387 hardware, and the return value should have been
// converted from an actual `f32`/`f64`. Even on non-SSE targets current compilers don't
// seem to miscompile code so badly as to allow user-supplied `x87_f80` "invalid operands"
// to be returned as `f32`/`f64`. Similarly, sNaNs are never produced by the hardware so we
// don't handle the case where the only fraction bits set are truncated, as that can never
// happen with sNaNs converted from `f32`s/`f64`s.
let bits = self.bitcast(value, self.type_ix(80));
// Mask out the extra 1s in the exponent as `f32`/`f64` have less bits in their
// exponents than `x87_f80`.
let exp_and_sign_bits = num_bits - fraction_bits;
let exp_and_sign_mask = u16::MAX << (16 - exp_and_sign_bits);
let exp_and_sign_mask = u128::from(exp_and_sign_mask) << 64;
let exp_and_sign = self.and(bits, self.const_uint_big(self.type_ix(80), exp_and_sign_mask));
// Shift the exponent and sign into position
let exp_and_sign = self
.lshr(exp_and_sign, self.const_uint_big(self.type_ix(80), 80 - u128::from(num_bits)));
let exp_and_sign = self.trunc(exp_and_sign, dest_bits_type);
// Truncate off the exponent and sign
let fraction = self.trunc(bits, self.type_i64());
// Shift the fraction in to position. There's no need to mask out `x87_f80`'s
// explicit integer bit as the fraction is right next to the exponent which is all
// 1s anyway.
let fraction = self.lshr(fraction, self.const_u64(63 - fraction_bits));
let fraction = if num_bits != 64 { self.trunc(fraction, dest_bits_type) } else { fraction };
// Combine the parts into the resulting float
let is_nan_res = self.or(exp_and_sign, fraction);
let is_nan_res = self.bitcast(is_nan_res, float_type);
self.br(after_block);
self.switch_to_block(is_not_nan_block);
if let Some(dbg_loc) = dbg_loc {
self.set_dbg_loc(dbg_loc);
}
// Use a regular floating point conversion when the value it not a NaN.
let is_not_nan_res = self.fptrunc(value, float_type);
self.br(after_block);
self.switch_to_block(after_block);
if let Some(dbg_loc) = dbg_loc {
self.set_dbg_loc(dbg_loc);
}
self.phi(float_type, &[is_nan_res, is_not_nan_res], &[is_nan_block, is_not_nan_block])
}
}
pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> Type<'ll>;
fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> Type<'ll>;
fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
/// Apply attributes to a function declaration/definition.
fn apply_attrs_llfn(
&self,
cx: &CodegenCx<'ll, 'tcx>,
llfn: Value<'ll>,
instance: Option<ty::Instance<'tcx>>,
);
/// Apply attributes to a function call.
fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: Value<'ll>);
}
impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> Type<'ll> {
// Ignore "extra" args from the call site for C variadic functions.
// Only the "fixed" args are part of the LLVM function signature.
let args =
if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
// This capacity calculation is approximate.
let mut llargument_tys = Vec::with_capacity(
self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
);
let llreturn_ty = match &self.ret.mode {
PassMode::Ignore => cx.type_void(),
PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
PassMode::Cast { cast, pad_i32_count: _ } => cast.llvm_type(cx),
PassMode::Indirect { address_space, .. } => {
let ty = if let Some(address_space) = address_space {
cx.type_ptr_ext(*address_space)
} else {
cx.type_ptr()
};
llargument_tys.push(ty);
cx.type_void()
}
PassMode::IndirectUnsized { .. } => bug!("unsized returns are not supported"),
};
for arg in args {
// Note that the exact number of arguments pushed here is carefully synchronized with
// code all over the place, both in the codegen_llvm and codegen_ssa crates. That's how
// other code then knows which LLVM argument(s) correspond to the n-th Rust argument.
let llarg_ty = match &arg.mode {
PassMode::Ignore => continue,
PassMode::Direct(_) => {
// ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
// and for Scalar ABIs the LLVM type is fully determined by `layout.abi`,
// guaranteeing that we generate ABI-compatible LLVM IR.
arg.layout.immediate_llvm_type(cx)
}
PassMode::Pair(..) => {
// ABI-compatible Rust types have the same `layout.abi` (up to validity ranges),
// so for ScalarPair we can easily be sure that we are generating ABI-compatible
// LLVM IR.
llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
continue;
}
PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
// Construct the type of a (wide) pointer to `ty`, and pass its two fields.
// Any two ABI-compatible unsized types have the same metadata type and
// moreover the same metadata value leads to the same dynamic size and
// alignment, so this respects ABI compatibility.
let ptr_ty = Ty::new_mut_ptr(cx.tcx, arg.layout.ty);
let ptr_layout = cx.layout_of(ptr_ty);
llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
continue;
}
PassMode::Indirect { attrs: _, address_space, mode: _ } => {
if let Some(address_space) = address_space {
cx.type_ptr_ext(*address_space)
} else {
cx.type_ptr()
}
}
PassMode::Cast { cast, pad_i32_count } => {
// Add padding.
llargument_tys.extend(std::iter::repeat_n(
Reg::i32().llvm_type(cx),
usize::from(*pad_i32_count),
));
// Compute the LLVM type we use for this function from the cast type.
// We assume here that ABI-compatible Rust types have the same cast type.
cast.llvm_type(cx)
}
};
llargument_tys.push(llarg_ty);
}
if self.c_variadic {
cx.type_variadic_func(&llargument_tys, llreturn_ty)
} else {
cx.type_func(&llargument_tys, llreturn_ty)
}
}
fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> Type<'ll> {
cx.type_ptr_ext(cx.data_layout().instruction_address_space)
}
fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv {
to_llvm_calling_convention(cx.tcx.sess, self.conv)
}
fn apply_attrs_llfn(
&self,
cx: &CodegenCx<'ll, 'tcx>,
llfn: Value<'ll>,
instance: Option<ty::Instance<'tcx>>,
) {
let mut func_attrs = SmallVec::<[_; 3]>::new();
if self.ret.layout.is_uninhabited() {
func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
}
if !self.can_unwind {
func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
}
match self.conv {
CanonAbi::Interrupt(InterruptKind::RiscvMachine) => {
func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "machine"))
}
CanonAbi::Interrupt(InterruptKind::RiscvSupervisor) => {
func_attrs.push(llvm::CreateAttrStringValue(cx.llcx, "interrupt", "supervisor"))
}
CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) => {
func_attrs.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"))
}
_ => (),
}
attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
let mut i = 0;
let mut apply = |attrs: &ArgAttributes| {
attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
i += 1;
i - 1
};
let apply_range_attr = |idx: AttributePlace, scalar: rustc_abi::Scalar| {
if cx.sess().opts.optimize != config::OptLevel::No
&& matches!(scalar.primitive(), Primitive::Int(..))
// If the value is a boolean, the range is 0..2 and that ultimately
// become 0..0 when the type becomes i1, which would be rejected
// by the LLVM verifier.
&& !scalar.is_bool()
// LLVM also rejects full range.
&& !scalar.is_always_valid(cx)
{
attributes::apply_to_llfn(
llfn,
idx,
&[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
);
}
};
match &self.ret.mode {
PassMode::Direct(attrs) => {
attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
}
}
PassMode::Indirect { attrs, address_space: _, mode } => {
assert!(*mode == IndirectMode::Pointer);
let i = apply(attrs);
let sret =
llvm::CreateStructRetAttr(cx.llcx, cx.type_byte_array(self.ret.layout.size));
attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
if cx.sess().opts.optimize != config::OptLevel::No {
attributes::apply_to_llfn(
llfn,
llvm::AttributePlace::Argument(i),
&[
llvm::AttributeKind::Writable.create_attr(cx.llcx),
llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx),
],
);
}
}
PassMode::IndirectUnsized { .. } => bug!("unsized returns are not supported"),
PassMode::Cast { cast, pad_i32_count: _ } => {
cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
}
_ => {}
}
for arg in self.args.iter() {
match &arg.mode {
PassMode::Ignore => {}
PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::OnStack } => {
let i = apply(attrs);
let byval = llvm::CreateByValAttr(cx.llcx, cx.type_byte_array(arg.layout.size));
attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
}
PassMode::Indirect {
attrs,
address_space: _,
mode: IndirectMode::AmdgpuKernelArg,
} => {
let i = apply(attrs);
let byref = llvm::CreateByRefAttr(cx.llcx, cx.type_byte_array(arg.layout.size));
attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byref]);
}
PassMode::Direct(attrs) => {
let i = apply(attrs);
if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
}
}
PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::Pointer } => {
let i = apply(attrs);
if cx.sess().opts.optimize != config::OptLevel::No {
attributes::apply_to_llfn(
llfn,
llvm::AttributePlace::Argument(i),
&[llvm::AttributeKind::DeadOnReturn.create_attr(cx.llcx)],
);
}
}
PassMode::IndirectUnsized { attrs, meta_attrs } => {
apply(attrs);
apply(meta_attrs);
}
PassMode::Pair(a, b) => {
let i = apply(a);
let ii = apply(b);
if let BackendRepr::ScalarPair { a: scalar_a, b: scalar_b, b_offset: _ } =
arg.layout.backend_repr
{
apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
let primitive_b = scalar_b.primitive();
let scalar_b = if let rustc_abi::Primitive::Int(int, false) = primitive_b
&& let ty::Ref(_, pointee_ty, _) = *arg.layout.ty.kind()
&& let ty::Slice(element_ty) = *pointee_ty.kind()
&& let elem_size = cx.layout_of(element_ty).size
&& elem_size != rustc_abi::Size::ZERO
{
// Ideally the layout calculations would have set the range,
// but that's complicated due to cycles, so in the mean time
// we calculate and apply it here.
debug_assert!(scalar_b.is_always_valid(cx));
let isize_max = int.signed_max() as u64;
rustc_abi::Scalar::Initialized {
value: primitive_b,
valid_range: rustc_abi::WrappingRange {
start: 0,
end: u128::from(isize_max / elem_size.bytes()),
},
}
} else {
scalar_b
};
apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
}
}
PassMode::Cast { cast, pad_i32_count } => {
for _ in 0..*pad_i32_count {
apply(&ArgAttributes::new());
}
apply(&cast.attrs);
}
}
}
// If the declaration has an associated instance, compute extra attributes based on that.
if let Some(instance) = instance {
llfn_attrs_from_instance(
cx,
cx.tcx,
llfn,
&cx.tcx.codegen_instance_attrs(instance.def),
Some(instance),
cx.sanitizer_ignorelist.as_ref(),
);
}
}
fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: Value<'ll>) {
let mut func_attrs = SmallVec::<[_; 2]>::new();
if self.ret.layout.is_uninhabited() {
func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
}
if !self.can_unwind {
func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
}
attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
let mut i = 0;
let mut apply = |cx: &CodegenCx<'ll, '_>, attrs: &ArgAttributes| {
attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
i += 1;
i - 1
};
match &self.ret.mode {
PassMode::Direct(attrs) => {
attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
}
PassMode::Indirect { attrs, address_space: _, mode } => {
assert!(*mode == IndirectMode::Pointer);
let i = apply(bx.cx, attrs);
let sret = llvm::CreateStructRetAttr(
bx.cx.llcx,
bx.cx.type_byte_array(self.ret.layout.size),
);
attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
}
PassMode::IndirectUnsized { .. } => bug!("unsized returns are not supported"),
PassMode::Cast { cast, pad_i32_count: _ } => {
cast.attrs.apply_attrs_to_callsite(
llvm::AttributePlace::ReturnValue,
bx.cx,
callsite,
);
}
_ => {}
}
for arg in self.args.iter() {
match &arg.mode {
PassMode::Ignore => {}
PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::OnStack } => {
let i = apply(bx.cx, attrs);
let byval =
llvm::CreateByValAttr(bx.cx.llcx, bx.cx.type_byte_array(arg.layout.size));
attributes::apply_to_callsite(
callsite,
llvm::AttributePlace::Argument(i),
&[byval],
);
}
PassMode::Indirect {
attrs,
address_space: _,
mode: IndirectMode::AmdgpuKernelArg,
} => {
let i = apply(bx.cx, attrs);
let byref =
llvm::CreateByRefAttr(bx.cx.llcx, bx.cx.type_byte_array(arg.layout.size));
attributes::apply_to_callsite(
callsite,
llvm::AttributePlace::Argument(i),
&[byref],
);
}
PassMode::Direct(attrs)
| PassMode::Indirect { attrs, address_space: _, mode: IndirectMode::Pointer } => {
apply(bx.cx, attrs);
}
PassMode::IndirectUnsized { attrs, meta_attrs } => {
apply(bx.cx, attrs);
apply(bx.cx, meta_attrs);
}
PassMode::Pair(a, b) => {
apply(bx.cx, a);
apply(bx.cx, b);
}
PassMode::Cast { cast, pad_i32_count } => {
for _ in 0..*pad_i32_count {
apply(bx.cx, &ArgAttributes::new());
}
apply(bx.cx, &cast.attrs);
}
}
}
let cconv = self.llvm_cconv(bx.cx);
if cconv != llvm::CCallConv {
llvm::SetInstructionCallConv(callsite, cconv);
}
if self.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
// This will probably get ignored on all targets but those supporting the TrustZone-M
// extension (thumbv8m targets).
let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
attributes::apply_to_callsite(
callsite,
llvm::AttributePlace::Function,
&[cmse_nonsecure_call],
);
}
// Some intrinsics require that an elementtype attribute (with the pointee type of a
// pointer argument) is added to the callsite.
let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
if element_type_index >= 0 {
let arg_ty = self.args[element_type_index as usize].layout.ty;
let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument");
let element_type_attr = unsafe {
llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
};
attributes::apply_to_callsite(
callsite,
llvm::AttributePlace::Argument(element_type_index as u32),
&[element_type_attr],
);
}
}
}
impl AbiBuilderMethods for Builder<'_, '_, '_> {
fn get_param(&mut self, index: usize) -> Self::Value {
llvm::get_param(self.llfn(), index as c_uint)
}
}
/// Determines the appropriate [`llvm::CallConv`] to use for a given function
/// ABI, for the current target.
pub(crate) fn to_llvm_calling_convention(sess: &Session, abi: CanonAbi) -> llvm::CallConv {
match abi {
CanonAbi::C | CanonAbi::Rust => llvm::CCallConv,
CanonAbi::RustCold => llvm::PreserveMost,
CanonAbi::RustPreserveNone => match &sess.target.arch {
Arch::X86_64 | Arch::AArch64 => llvm::PreserveNone,
_ => llvm::CCallConv,
},
CanonAbi::RustTail => match &sess.target.arch {
Arch::X86 | Arch::X86_64 | Arch::AArch64 => llvm::Tail,
_ => sess.dcx().fatal("extern \"tail\" is only supported on x86, x86_64 and aarch64"),
},
// Functions with this calling convention can only be called from assembly, but it is
// possible to declare an `extern "custom"` block, so the backend still needs a calling
// convention for declaring foreign functions.
CanonAbi::Custom => llvm::CCallConv,
CanonAbi::Swift => llvm::SwiftCallConv,
CanonAbi::GpuKernel => match &sess.target.arch {
Arch::AmdGpu => llvm::AmdgpuKernel,
Arch::Nvptx64 => llvm::PtxKernel,
arch => panic!("Architecture {arch} does not support GpuKernel calling convention"),
},
CanonAbi::Interrupt(interrupt_kind) => match interrupt_kind {
InterruptKind::Avr => llvm::AvrInterrupt,
InterruptKind::AvrNonBlocking => llvm::AvrNonBlockingInterrupt,
InterruptKind::Msp430 => llvm::Msp430Intr,
InterruptKind::RiscvMachine | InterruptKind::RiscvSupervisor => llvm::CCallConv,
InterruptKind::X86 => llvm::X86_Intr,
},
CanonAbi::Arm(arm_call) => match arm_call {
ArmCall::Aapcs => llvm::ArmAapcsCallConv,
ArmCall::CCmseNonSecureCall | ArmCall::CCmseNonSecureEntry => llvm::CCallConv,
},
CanonAbi::X86(x86_call) => match x86_call {
X86Call::Fastcall => llvm::X86FastcallCallConv,
X86Call::Stdcall => llvm::X86StdcallCallConv,
X86Call::SysV64 => llvm::X86_64_SysV,
X86Call::Thiscall => llvm::X86_ThisCall,
X86Call::Vectorcall => llvm::X86_VectorCall,
X86Call::Win64 => llvm::X86_64_Win64,
},
}
}