1use std::fmt::{self, Write};
2use std::num::NonZero;
3use std::ops::Deref;
4use std::range::{RangeFrom, RangeInclusive, RangeToInclusive};
5use std::{cmp, iter};
6
7use rustc_hashes::Hash64;
8use rustc_index::Idx;
9use rustc_index::bit_set::BitMatrix;
10use tracing::{debug, trace};
11
12use crate::{
13 AbiAlign, Align, BackendLaneCount, BackendRepr, FieldsShape, HasDataLayout, IndexSlice,
14 IndexVec, Integer, LayoutData, Niche, NicheOptimizations, NumScalableVectors, Primitive,
15 ReprOptions, Scalar, Size, StructKind, TagEncoding, TargetDataLayout, VariantLayout, Variants,
16 WrappingRange,
17};
18
19mod coroutine;
20mod simple;
21
22#[cfg(feature = "nightly")]
23mod ty;
24
25#[cfg(feature = "nightly")]
26pub use ty::{Layout, TyAbiInterface, TyAndLayout};
27
28#[automatically_derived]
impl ::core::marker::Copy for FieldIdx { }
impl FieldIdx {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
pub const ZERO: Self = Self::from_u32(0);
#[doc = r" Creates a new index from a given `usize`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
};
unsafe { Self::from_u32_unchecked(value as u32) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u16`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc =
r" The provided value must be less than or equal to the maximum value for the newtype."]
#[doc =
r" Providing a value outside this range is undefined due to layout restrictions."]
#[doc = r""]
#[doc = r" Prefer using `from_u32`."]
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self {
private_use_as_methods_instead: unsafe {
std::mem::transmute(value)
},
}
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
pub const fn as_u32(self) -> u32 {
unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for FieldIdx {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for FieldIdx {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for FieldIdx {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for FieldIdx {
#[inline]
fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
<usize as
::std::iter::Step>::steps_between(&Self::index(*start),
&Self::index(*end))
}
#[inline]
fn forward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_add(u).map(Self::from_usize)
}
#[inline]
fn backward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_sub(u).map(Self::from_usize)
}
#[inline]
fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_add(u);
(Self::from_usize(s), o)
}
#[inline]
fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_sub(u);
(Self::from_usize(s), o)
}
}
impl ::std::cmp::Ord for FieldIdx {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_u32().cmp(&other.as_u32())
}
}
impl ::std::cmp::PartialOrd for FieldIdx {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::rustc_data_structures::stable_hash::StableHash for FieldIdx {
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
hcx: &mut __Hcx,
hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
self.as_u32().stable_hash(hcx, hasher)
}
}
impl From<FieldIdx> for u32 {
#[inline]
fn from(v: FieldIdx) -> u32 { v.as_u32() }
}
impl From<FieldIdx> for usize {
#[inline]
fn from(v: FieldIdx) -> usize { v.as_usize() }
}
impl From<usize> for FieldIdx {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for FieldIdx {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for FieldIdx {}
impl ::std::cmp::PartialEq for FieldIdx {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for FieldIdx { }
impl ::std::hash::Hash for FieldIdx {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
FieldIdx {
fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
FieldIdx {
fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::std::fmt::Debug for FieldIdx {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
29 #[stable_hash]
51 #[encodable]
52 #[orderable]
53 #[gate_rustc_only]
54 pub struct FieldIdx {}
55}
56
57impl FieldIdx {
58 pub const ONE: FieldIdx = FieldIdx::from_u32(1);
62}
63
64#[automatically_derived]
impl ::core::marker::Copy for VariantIdx { }
#[doc = " Equivalent to `VariantIdx(0)`."]
pub const FIRST_VARIANT: VariantIdx = VariantIdx::from_u32(0);
impl VariantIdx {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
pub const ZERO: Self = Self::from_u32(0);
#[doc = r" Creates a new index from a given `usize`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
};
unsafe { Self::from_u32_unchecked(value as u32) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u16`."]
#[doc = r""]
#[doc = r" # Panics"]
#[doc = r""]
#[doc = r" Will panic if `value` exceeds `MAX`."]
#[inline]
pub const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
unsafe { Self::from_u32_unchecked(value) }
}
#[doc = r" Creates a new index from a given `u32`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc =
r" The provided value must be less than or equal to the maximum value for the newtype."]
#[doc =
r" Providing a value outside this range is undefined due to layout restrictions."]
#[doc = r""]
#[doc = r" Prefer using `from_u32`."]
#[inline]
pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
Self {
private_use_as_methods_instead: unsafe {
std::mem::transmute(value)
},
}
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
pub const fn as_u32(self) -> u32 {
unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
}
#[doc = r" Extracts the value of this index as a `usize`."]
#[inline]
pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for VariantIdx {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for VariantIdx {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for VariantIdx {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for VariantIdx {
#[inline]
fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
<usize as
::std::iter::Step>::steps_between(&Self::index(*start),
&Self::index(*end))
}
#[inline]
fn forward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_add(u).map(Self::from_usize)
}
#[inline]
fn backward_checked(start: Self, u: usize) -> Option<Self> {
Self::index(start).checked_sub(u).map(Self::from_usize)
}
#[inline]
fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_add(u);
(Self::from_usize(s), o)
}
#[inline]
fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
let (s, o) = Self::index(start).overflowing_sub(u);
(Self::from_usize(s), o)
}
}
impl ::std::cmp::Ord for VariantIdx {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_u32().cmp(&other.as_u32())
}
}
impl ::std::cmp::PartialOrd for VariantIdx {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::rustc_data_structures::stable_hash::StableHash for VariantIdx {
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
hcx: &mut __Hcx,
hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
self.as_u32().stable_hash(hcx, hasher)
}
}
impl From<VariantIdx> for u32 {
#[inline]
fn from(v: VariantIdx) -> u32 { v.as_u32() }
}
impl From<VariantIdx> for usize {
#[inline]
fn from(v: VariantIdx) -> usize { v.as_usize() }
}
impl From<usize> for VariantIdx {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for VariantIdx {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for VariantIdx {}
impl ::std::cmp::PartialEq for VariantIdx {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for VariantIdx { }
impl ::std::hash::Hash for VariantIdx {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
VariantIdx {
fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
VariantIdx {
fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::std::fmt::Debug for VariantIdx {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
65 #[stable_hash]
76 #[encodable]
77 #[orderable]
78 #[gate_rustc_only]
79 pub struct VariantIdx {
80 const FIRST_VARIANT = 0;
82 }
83}
84
85fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool
91where
92 FieldIdx: Idx,
93 VariantIdx: Idx,
94 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
95{
96 let uninhabited = fields.iter().any(|f| f.is_uninhabited());
97 let is_1zst = fields.iter().all(|f| f.is_1zst());
100 uninhabited && is_1zst
101}
102
103enum NicheBias {
105 Start,
106 End,
107}
108
109#[derive(#[automatically_derived]
impl<F: ::core::marker::Copy> ::core::marker::Copy for
LayoutCalculatorError<F> {
}Copy, #[automatically_derived]
impl<F: ::core::clone::Clone> ::core::clone::Clone for
LayoutCalculatorError<F> {
#[inline]
fn clone(&self) -> Self {
match self {
Self::UnexpectedUnsized(__self_0) =>
Self::UnexpectedUnsized(::core::clone::Clone::clone(__self_0)),
Self::SizeOverflow => Self::SizeOverflow,
Self::EmptyUnion => Self::EmptyUnion,
Self::ReprConflict => Self::ReprConflict,
Self::ZeroLengthSimdType => Self::ZeroLengthSimdType,
Self::OversizedSimdType { max_lanes: __self_0 } =>
Self::OversizedSimdType {
max_lanes: ::core::clone::Clone::clone(__self_0),
},
Self::NonPrimitiveSimdType(__self_0) =>
Self::NonPrimitiveSimdType(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl<F: ::core::fmt::Debug> ::core::fmt::Debug for LayoutCalculatorError<F> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::UnexpectedUnsized(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"UnexpectedUnsized", &__self_0),
Self::SizeOverflow =>
::core::fmt::Formatter::write_str(f, "SizeOverflow"),
Self::EmptyUnion =>
::core::fmt::Formatter::write_str(f, "EmptyUnion"),
Self::ReprConflict =>
::core::fmt::Formatter::write_str(f, "ReprConflict"),
Self::ZeroLengthSimdType =>
::core::fmt::Formatter::write_str(f, "ZeroLengthSimdType"),
Self::OversizedSimdType { max_lanes: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OversizedSimdType", "max_lanes", &__self_0),
Self::NonPrimitiveSimdType(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonPrimitiveSimdType", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
LayoutCalculatorError<F> {
}
#[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
LayoutCalculatorError<F> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::UnexpectedUnsized(__self_0),
Self::UnexpectedUnsized(__arg1_0)) => __self_0 == __arg1_0,
(Self::OversizedSimdType { max_lanes: __self_0 },
Self::OversizedSimdType { max_lanes: __arg1_0 }) =>
__self_0 == __arg1_0,
(Self::NonPrimitiveSimdType(__self_0),
Self::NonPrimitiveSimdType(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<F: ::core::cmp::Eq> ::core::cmp::Eq for LayoutCalculatorError<F> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<F>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq)]
110pub enum LayoutCalculatorError<F> {
111 UnexpectedUnsized(F),
118
119 SizeOverflow,
121
122 EmptyUnion,
124
125 ReprConflict,
127
128 ZeroLengthSimdType,
130
131 OversizedSimdType { max_lanes: usize },
133
134 NonPrimitiveSimdType(F),
136}
137
138impl<F> LayoutCalculatorError<F> {
139 pub fn without_payload(&self) -> LayoutCalculatorError<()> {
140 use LayoutCalculatorError::*;
141 match *self {
142 UnexpectedUnsized(_) => UnexpectedUnsized(()),
143 SizeOverflow => SizeOverflow,
144 EmptyUnion => EmptyUnion,
145 ReprConflict => ReprConflict,
146 ZeroLengthSimdType => ZeroLengthSimdType,
147 OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
148 NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
149 }
150 }
151
152 pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 use LayoutCalculatorError::*;
157 f.write_str(match self {
158 UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
159 SizeOverflow => "size overflow",
160 EmptyUnion => "type is a union with no fields",
161 ReprConflict => "type has an invalid repr",
162 ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
163 "invalid simd type definition"
164 }
165 })
166 }
167}
168
169type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
170 Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
171
172#[derive(#[automatically_derived]
impl<Cx: ::core::clone::Clone> ::core::clone::Clone for LayoutCalculator<Cx> {
#[inline]
fn clone(&self) -> Self {
Self { cx: ::core::clone::Clone::clone(&self.cx) }
}
}Clone, #[automatically_derived]
impl<Cx: ::core::marker::Copy> ::core::marker::Copy for LayoutCalculator<Cx> {
}Copy, #[automatically_derived]
impl<Cx: ::core::fmt::Debug> ::core::fmt::Debug for LayoutCalculator<Cx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"LayoutCalculator", "cx", &&self.cx)
}
}Debug)]
173pub struct LayoutCalculator<Cx> {
174 pub cx: Cx,
175}
176
177impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
178 pub fn new(cx: Cx) -> Self {
179 Self { cx }
180 }
181
182 pub fn layout_of_array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
183 &self,
184 element: &LayoutData<FieldIdx, VariantIdx>,
185 count_if_sized: Option<u64>, ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
187 let count = count_if_sized.unwrap_or(0);
188 let size =
189 element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
190
191 Ok(LayoutData {
192 variants: Variants::Single { index: VariantIdx::new(0) },
193 fields: FieldsShape::Array { stride: element.size, count },
194 backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
195 largest_niche: element.largest_niche.filter(|_| count != 0),
196 uninhabited: element.uninhabited && count != 0,
197 align: element.align,
198 size,
199 max_repr_align: None,
200 unadjusted_abi_align: element.align.abi,
201 randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
202 })
203 }
204
205 pub fn layout_of_scalable_vector_type<FieldIdx, VariantIdx, F>(
206 &self,
207 element: F,
208 count: u64,
209 number_of_vectors: NumScalableVectors,
210 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
211 where
212 FieldIdx: Idx,
213 VariantIdx: Idx,
214 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
215 {
216 vector_type_layout(
217 SimdVectorKind::Scalable(number_of_vectors),
218 self.cx.data_layout(),
219 element,
220 count,
221 )
222 }
223
224 pub fn layout_of_simd_type<FieldIdx, VariantIdx, F>(
225 &self,
226 element: F,
227 count: u64,
228 repr_packed: bool,
229 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
230 where
231 FieldIdx: Idx,
232 VariantIdx: Idx,
233 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
234 {
235 let kind = if repr_packed { SimdVectorKind::PackedFixed } else { SimdVectorKind::Fixed };
236 vector_type_layout(kind, self.cx.data_layout(), element, count)
237 }
238
239 pub fn layout_of_coroutine<'a, F, VariantIdx, FieldIdx, LocalIdx>(
244 &self,
245 local_layouts: &IndexSlice<LocalIdx, F>,
246 prefix_layouts: IndexVec<FieldIdx, F>,
247 variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
248 storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
249 tag_to_layout: impl Fn(Scalar) -> F,
250 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
251 where
252 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
253 VariantIdx: Idx,
254 FieldIdx: Idx,
255 LocalIdx: Idx,
256 {
257 coroutine::layout(
258 self,
259 local_layouts,
260 prefix_layouts,
261 variant_fields,
262 storage_conflicts,
263 tag_to_layout,
264 )
265 }
266
267 pub fn layout_of_univariant<'a, FieldIdx, VariantIdx, F>(
273 &self,
274 fields: &IndexSlice<FieldIdx, F>,
275 repr: &ReprOptions,
276 kind: StructKind,
277 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
278 where
279 FieldIdx: Idx,
280 VariantIdx: Idx,
281 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
282 {
283 let dl = self.cx.data_layout();
284 let layout = self.layout_of_univariant_biased(fields, repr, kind, NicheBias::Start);
285 if let Ok(layout) = &layout
291 && !#[allow(non_exhaustive_omitted_patterns)] match kind {
StructKind::MaybeUnsized => true,
_ => false,
}matches!(kind, StructKind::MaybeUnsized)
295 && let Some(niche) = layout.largest_niche
296 && let head_space = niche.offset.bytes()
297 && let niche_len = niche.value.size(dl).bytes()
298 && let tail_space = layout.size.bytes() - head_space - niche_len
299 && (fields.len() > 1 && head_space != 0 && tail_space > 0)
303 {
304 let alt_layout = self
305 .layout_of_univariant_biased(fields, repr, kind, NicheBias::End)
306 .expect("alt layout should always work");
307 let alt_niche = alt_layout
308 .largest_niche
309 .expect("alt layout should have a niche like the regular one");
310 let alt_head_space = alt_niche.offset.bytes();
311 let alt_niche_len = alt_niche.value.size(dl).bytes();
312 let alt_tail_space = alt_layout.size.bytes() - alt_head_space - alt_niche_len;
313
314 if true {
{
match (&layout.size.bytes(), &alt_layout.size.bytes()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(layout.size.bytes(), alt_layout.size.bytes());
315
316 let prefer_alt_layout = alt_head_space > head_space && alt_head_space > tail_space;
317
318 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:318",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(318u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("sz: {0}, default_niche_at: {1}+{2}, default_tail_space: {3}, alt_niche_at/head_space: {4}+{5}, alt_tail: {6}, num_fields: {7}, better: {8}\nlayout: {9}\nalt_layout: {10}\n",
layout.size.bytes(), head_space, niche_len, tail_space,
alt_head_space, alt_niche_len, alt_tail_space,
layout.fields.count(), prefer_alt_layout,
self.format_field_niches(layout, fields),
self.format_field_niches(&alt_layout, fields)) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
319 "sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
320 layout: {}\n\
321 alt_layout: {}\n",
322 layout.size.bytes(),
323 head_space,
324 niche_len,
325 tail_space,
326 alt_head_space,
327 alt_niche_len,
328 alt_tail_space,
329 layout.fields.count(),
330 prefer_alt_layout,
331 self.format_field_niches(layout, fields),
332 self.format_field_niches(&alt_layout, fields),
333 );
334
335 if prefer_alt_layout {
336 return Ok(alt_layout);
337 }
338 }
339 layout
340 }
341
342 pub fn layout_of_struct_or_enum<'a, FieldIdx, VariantIdx, F>(
343 &self,
344 repr: &ReprOptions,
345 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
346 is_enum: bool,
347 niche_optimizations: NicheOptimizations,
348 discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
349 discriminants: impl Iterator<Item = (VariantIdx, u128)>,
350 always_sized: bool,
351 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
352 where
353 FieldIdx: Idx,
354 VariantIdx: Idx,
355 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
356 {
357 let (present_first, present_second) = {
358 let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
359 if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
360 });
361 (present_variants.next(), present_variants.next())
362 };
363 let present_first = match present_first {
364 Some(present_first) => present_first,
365 None if is_enum => {
367 return Ok(LayoutData::never_type(&self.cx));
368 }
369 None => VariantIdx::new(0),
372 };
373
374 if !is_enum ||
376 (present_second.is_none() && !repr.inhibit_enum_layout_opt())
378 {
379 self.layout_of_struct(
380 repr,
381 variants,
382 present_first,
383 is_enum,
384 niche_optimizations,
385 always_sized,
386 )
387 } else {
388 if !is_enum { ::core::panicking::panic("assertion failed: is_enum") };assert!(is_enum);
392 self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
393 }
394 }
395
396 pub fn layout_of_union<'a, FieldIdx, VariantIdx, F>(
397 &self,
398 repr: &ReprOptions,
399 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
400 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
401 where
402 FieldIdx: Idx,
403 VariantIdx: Idx,
404 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
405 {
406 let dl = self.cx.data_layout();
407 let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
408 let mut max_repr_align = repr.align;
409
410 struct AbiMismatch;
413 let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
414 Err(AbiMismatch)
416 } else {
417 Ok(None)
418 };
419
420 let mut size = Size::ZERO;
421 let only_variant_idx = VariantIdx::new(0);
422 let only_variant = &variants[only_variant_idx];
423 for field in only_variant {
424 if field.is_unsized() {
425 return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
426 }
427
428 align = align.max(field.align.abi);
429 max_repr_align = max_repr_align.max(field.max_repr_align);
430 size = cmp::max(size, field.size);
431
432 if field.is_zst() {
433 continue;
435 }
436
437 if let Ok(common) = common_non_zst_repr_and_align {
438 let field_abi = field.backend_repr.to_union();
440
441 if let Some((common_abi, common_align)) = common {
442 if common_abi != field_abi {
443 common_non_zst_repr_and_align = Err(AbiMismatch);
445 } else {
446 if !#[allow(non_exhaustive_omitted_patterns)] match common_abi {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(common_abi, BackendRepr::Memory { .. }) {
449 {
match (&common_align, &field.align.abi) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("non-Aggregate field with matching ABI but differing alignment")));
}
}
}
};assert_eq!(
450 common_align, field.align.abi,
451 "non-Aggregate field with matching ABI but differing alignment"
452 );
453 }
454 }
455 } else {
456 common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
458 }
459 }
460 }
461
462 if let Some(pack) = repr.pack {
463 align = align.min(pack);
464 }
465 let unadjusted_abi_align = align;
468 if let Some(repr_align) = repr.align {
469 align = align.max(repr_align);
470 }
471 let align = align;
473
474 let backend_repr = match common_non_zst_repr_and_align {
477 Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
478 Ok(Some((repr, _))) => match repr {
479 BackendRepr::Scalar(_) | BackendRepr::ScalarPair { .. }
481 if repr.scalar_platform_align(dl).unwrap() != align =>
482 {
483 BackendRepr::Memory { sized: true }
484 }
485 BackendRepr::SimdVector { element, count: _ }
487 if element.default_align(dl).abi > align =>
488 {
489 BackendRepr::Memory { sized: true }
490 }
491 BackendRepr::Scalar(..)
493 | BackendRepr::ScalarPair { .. }
494 | BackendRepr::SimdVector { .. }
495 | BackendRepr::SimdScalableVector { .. }
496 | BackendRepr::Memory { .. } => repr,
497 },
498 };
499
500 let Some(union_field_count) = NonZero::new(only_variant.len()) else {
501 return Err(LayoutCalculatorError::EmptyUnion);
502 };
503
504 let combined_seed = only_variant
505 .iter()
506 .map(|v| v.randomization_seed)
507 .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
508
509 Ok(LayoutData {
510 variants: Variants::Single { index: only_variant_idx },
511 fields: FieldsShape::Union(union_field_count),
512 backend_repr,
513 largest_niche: None,
514 uninhabited: false,
515 align: AbiAlign::new(align),
516 size: size.align_to(align),
517 max_repr_align,
518 unadjusted_abi_align,
519 randomization_seed: combined_seed,
520 })
521 }
522
523 fn layout_of_struct<'a, FieldIdx, VariantIdx, F>(
528 &self,
529 repr: &ReprOptions,
530 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
531 variant_idx: VariantIdx,
532 is_enum: bool,
533 niche_optimizations: NicheOptimizations,
534 always_sized: bool,
535 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
536 where
537 FieldIdx: Idx,
538 VariantIdx: Idx,
539 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
540 {
541 let dl = self.cx.data_layout();
542 let v = variant_idx;
543 let kind = if is_enum || variants[v].is_empty() || always_sized {
544 StructKind::AlwaysSized
545 } else {
546 StructKind::MaybeUnsized
547 };
548
549 let mut st = self.layout_of_univariant(&variants[v], repr, kind)?;
550 st.variants = Variants::Single { index: v };
551
552 if niche_optimizations == NicheOptimizations::Disabled {
553 let hide_niches = |scalar: &mut _| match scalar {
554 Scalar::Initialized { value, valid_range } => {
555 *valid_range = WrappingRange::full(value.size(dl))
556 }
557 Scalar::Union { .. } => {}
559 };
560 match &mut st.backend_repr {
561 BackendRepr::Scalar(scalar) => hide_niches(scalar),
562 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
563 hide_niches(a);
564 hide_niches(b);
565 }
566 BackendRepr::SimdVector { element, .. }
567 | BackendRepr::SimdScalableVector { element, .. } => hide_niches(element),
568 BackendRepr::Memory { sized: _ } => {}
569 }
570 st.largest_niche = None;
571 return Ok(st);
572 }
573
574 Ok(st)
575 }
576
577 fn layout_of_enum<'a, FieldIdx, VariantIdx, F>(
578 &self,
579 repr: &ReprOptions,
580 variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
581 discr_range_of_repr: impl Fn(RangeFrom<i128>, RangeToInclusive<u128>) -> (Integer, bool),
582 discriminants: impl Iterator<Item = (VariantIdx, u128)>,
583 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
584 where
585 FieldIdx: Idx,
586 VariantIdx: Idx,
587 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
588 {
589 let dl = self.cx.data_layout();
590 if repr.packed() {
592 return Err(LayoutCalculatorError::ReprConflict);
593 }
594
595 let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
596 struct VariantLayoutInfo {
597 align_abi: Align,
598 }
599
600 if repr.inhibit_enum_layout_opt() {
601 return None;
602 }
603
604 if variants.len() < 2 {
605 return None;
606 }
607
608 let mut align = dl.aggregate_align;
609 let mut max_repr_align = repr.align;
610 let mut unadjusted_abi_align = align;
611 let mut combined_seed = repr.field_shuffle_seed;
612
613 let mut variants_info = IndexVec::<VariantIdx, _>::with_capacity(variants.len());
614 let mut variant_layouts = variants
615 .iter()
616 .map(|v| {
617 let st = self.layout_of_univariant(v, repr, StructKind::AlwaysSized).ok()?;
618
619 variants_info.push(VariantLayoutInfo { align_abi: st.align.abi });
620
621 align = align.max(st.align.abi);
622 max_repr_align = max_repr_align.max(st.max_repr_align);
623 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
624 combined_seed = combined_seed.wrapping_add(st.randomization_seed);
625
626 Some(VariantLayout::from_layout(st))
627 })
628 .collect::<Option<IndexVec<VariantIdx, _>>>()?;
629
630 let largest_variant_index = variant_layouts
631 .iter_enumerated()
632 .max_by_key(|(_i, layout)| layout.size.bytes())
633 .map(|(i, _layout)| i)?;
634
635 let all_indices = variants.indices();
636 let needs_disc =
637 |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
638 let niche_variants = RangeInclusive {
639 start: all_indices.clone().find(|v| needs_disc(*v)).unwrap(),
640 last: all_indices.rev().find(|v| needs_disc(*v)).unwrap(),
641 };
642
643 let count =
644 (niche_variants.last.index() as u128 - niche_variants.start.index() as u128) + 1;
645
646 let niche = variant_layouts[largest_variant_index].largest_niche?;
648 let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
649 let niche_offset = niche.offset;
650 let niche_size = niche.value.size(dl);
651 let size = variant_layouts[largest_variant_index].size.align_to(align);
652
653 let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
654 if i == largest_variant_index {
655 return true;
656 }
657
658 layout.largest_niche = None;
659
660 if layout.size <= niche_offset {
661 return true;
663 }
664
665 let this_align = variants_info[i].align_abi;
667 let this_offset = (niche_offset + niche_size).align_to(this_align);
668
669 if this_offset + layout.size > size {
670 return false;
671 }
672
673 for offset in layout.field_offsets.iter_mut() {
675 *offset += this_offset;
676 }
677
678 if !layout.is_uninhabited() {
680 layout.backend_repr = BackendRepr::Memory { sized: true };
681 }
682 layout.size += this_offset;
683
684 true
685 });
686
687 if !all_variants_fit {
688 return None;
689 }
690
691 let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
692
693 let others_zst = variant_layouts
694 .iter_enumerated()
695 .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
696 let same_size = size == variant_layouts[largest_variant_index].size;
697 let same_align = align == variants_info[largest_variant_index].align_abi;
698
699 let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
700 let abi = if same_size && same_align && others_zst {
701 match variant_layouts[largest_variant_index].backend_repr {
702 BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
705 BackendRepr::ScalarPair { a: first, b: second, b_offset } => {
706 if niche_offset == Size::ZERO {
709 BackendRepr::ScalarPair {
710 a: niche_scalar,
711 b: second.to_union(),
712 b_offset,
713 }
714 } else {
715 BackendRepr::ScalarPair {
716 a: first.to_union(),
717 b: niche_scalar,
718 b_offset,
719 }
720 }
721 }
722 _ => BackendRepr::Memory { sized: true },
723 }
724 } else {
725 BackendRepr::Memory { sized: true }
726 };
727
728 let layout = LayoutData {
729 variants: Variants::Multiple {
730 tag: niche_scalar,
731 tag_encoding: TagEncoding::Niche {
732 untagged_variant: largest_variant_index,
733 niche_variants,
734 niche_start,
735 },
736 tag_field: FieldIdx::new(0),
737 variants: variant_layouts,
738 },
739 fields: FieldsShape::Arbitrary {
740 offsets: [niche_offset].into(),
741 in_memory_order: [FieldIdx::new(0)].into(),
742 },
743 backend_repr: abi,
744 largest_niche,
745 uninhabited,
746 size,
747 align: AbiAlign::new(align),
748 max_repr_align,
749 unadjusted_abi_align,
750 randomization_seed: combined_seed,
751 };
752
753 Some(layout)
754 };
755
756 let niche_filling_layout = calculate_niche_filling_layout();
757
758 let discr_type = repr.discr_type();
759 let discr_size = Integer::from_attr(dl, discr_type).size();
760
761 let necessary_discriminants: Vec<u128> = discriminants
762 .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
763 .map(|(_, val)| val)
764 .collect();
765
766 let (min_negative, max_positive): (i128, u128) = if discr_type.is_signed() {
769 necessary_discriminants.iter().copied().map(|val| discr_size.sign_extend(val)).fold(
770 (0_i128, 0_u128),
771 |(min, max), val| {
772 if let Ok(val) = u128::try_from(val) {
773 (min, max.max(val))
774 } else {
775 (min.min(val), max)
776 }
777 },
778 )
779 } else {
780 (0, necessary_discriminants.iter().copied().max().unwrap_or(0))
782 };
783 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:783",
"rustc_abi::layout", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(783u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("min_negative")
}> =
::tracing::__macro_support::FieldName::new("min_negative");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("max_positive")
}> =
::tracing::__macro_support::FieldName::new("max_positive");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_negative)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&max_positive)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!(?min_negative, ?max_positive);
784
785 let (min_ity, signed) = discr_range_of_repr(
786 RangeFrom { start: min_negative },
787 RangeToInclusive { last: max_positive },
788 ); let mut align = dl.aggregate_align;
791 let mut max_repr_align = repr.align;
792 let mut unadjusted_abi_align = align;
793 let mut combined_seed = repr.field_shuffle_seed;
794
795 let mut size = Size::ZERO;
796
797 let mut start_align = Align::from_bytes(256).unwrap();
799 {
match (&Integer::for_align(dl, start_align), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(Integer::for_align(dl, start_align), None);
800
801 let mut prefix_align = min_ity.align(dl).abi;
807 if repr.c() {
808 for fields in variants {
809 for field in fields {
810 prefix_align = prefix_align.max(field.align.abi);
811 }
812 }
813 }
814
815 let mut layout_variants = variants
817 .iter()
818 .map(|field_layouts| {
819 let st = self.layout_of_univariant(
820 field_layouts,
821 repr,
822 StructKind::Prefixed(min_ity.size(), prefix_align),
823 )?;
824 for field_idx in st.fields.index_by_increasing_offset() {
827 let field = &field_layouts[FieldIdx::new(field_idx)];
828 if !field.is_1zst() {
829 start_align = start_align.min(field.align.abi);
830 break;
831 }
832 }
833 size = cmp::max(size, st.size);
834 align = align.max(st.align.abi);
835 max_repr_align = max_repr_align.max(st.max_repr_align);
836 unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
837 combined_seed = combined_seed.wrapping_add(st.randomization_seed);
838 Ok(VariantLayout::from_layout(st))
839 })
840 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
841
842 size = size.align_to(align);
844
845 if size.bytes() >= dl.obj_size_bound() {
847 return Err(LayoutCalculatorError::SizeOverflow);
848 }
849
850 let typeck_ity = Integer::from_attr(dl, repr.discr_type());
851 if typeck_ity < min_ity {
852 {
::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
min_ity, typeck_ity));
};panic!(
862 "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
863 );
864 }
867
868 let mut ity = if repr.c() || repr.int.is_some() {
879 min_ity
880 } else {
881 Integer::for_align(dl, start_align).unwrap_or(min_ity)
882 };
883
884 if ity <= min_ity {
887 ity = min_ity;
888 } else {
889 let old_ity_size = min_ity.size();
891 let new_ity_size = ity.size();
892 for variant in &mut layout_variants {
893 for i in &mut variant.field_offsets {
894 if *i <= old_ity_size {
895 {
match (&*i, &old_ity_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(*i, old_ity_size);
896 *i = new_ity_size;
897 }
898 }
899 if variant.size <= old_ity_size {
901 variant.size = new_ity_size;
902 }
903 }
904 }
905
906 let tag_valid_range = {
907 let tag_size = ity.size();
908 let tags = necessary_discriminants.into_iter().map(|d| tag_size.truncate(d));
909 WrappingRange::smallest_range_containing(tags, tag_size)
910 .unwrap_or(WrappingRange { start: 0, end: 0 })
912 };
913 let tag = Scalar::Initialized {
914 value: Primitive::Int(ity, signed),
915 valid_range: tag_valid_range,
916 };
917 let mut abi = BackendRepr::Memory { sized: true };
918
919 let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
920 if tag.size(dl) == size {
921 abi = BackendRepr::Scalar(tag);
924 } else {
925 let mut common_prim = None;
928 let mut common_prim_initialized_in_all_variants = true;
929 for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
930 let mut fields = iter::zip(field_layouts, &layout_variant.field_offsets)
933 .filter(|p| !p.0.is_zst());
934 let (field, offset) = match (fields.next(), fields.next()) {
935 (None, None) => {
936 common_prim_initialized_in_all_variants = false;
937 continue;
938 }
939 (Some(pair), None) => pair,
940 _ => {
941 common_prim = None;
942 break;
943 }
944 };
945 let prim = match field.backend_repr {
946 BackendRepr::Scalar(scalar) => {
947 common_prim_initialized_in_all_variants &=
948 #[allow(non_exhaustive_omitted_patterns)] match scalar {
Scalar::Initialized { .. } => true,
_ => false,
}matches!(scalar, Scalar::Initialized { .. });
949 scalar.primitive()
950 }
951 _ => {
952 common_prim = None;
953 break;
954 }
955 };
956 if let Some((old_prim, common_offset)) = common_prim {
957 if offset != common_offset {
959 common_prim = None;
960 break;
961 }
962 let new_prim = match (old_prim, prim) {
966 (x, y) if x == y => x,
968 (p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
971 (p @ Primitive::Pointer(_), i @ Primitive::Int(..))
975 | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
976 if p.size(dl) == i.size(dl)
977 && p.default_align(dl) == i.default_align(dl) =>
978 {
979 p
980 }
981 _ => {
982 common_prim = None;
983 break;
984 }
985 };
986 common_prim = Some((new_prim, common_offset));
988 } else {
989 common_prim = Some((prim, offset));
990 }
991 }
992 if let Some((prim, offset)) = common_prim {
993 let prim_scalar = if common_prim_initialized_in_all_variants {
994 let size = prim.size(dl);
995 if !(size.bits() <= 128) {
::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
996 Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
997 } else {
998 Scalar::Union { value: prim }
1000 };
1001 let pair =
1002 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1003 let pair_offsets = match pair.fields {
1004 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1005 {
match (&in_memory_order.raw, &[FieldIdx::new(0), FieldIdx::new(1)]) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(in_memory_order.raw, [FieldIdx::new(0), FieldIdx::new(1)]);
1006 offsets
1007 }
1008 _ => {
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
1009 };
1010 if pair_offsets[FieldIdx::new(0)] == Size::ZERO
1011 && pair_offsets[FieldIdx::new(1)] == *offset
1012 && align == pair.align.abi
1013 && size == pair.size
1014 {
1015 abi = pair.backend_repr;
1018 }
1019 }
1020 }
1021
1022 if #[allow(non_exhaustive_omitted_patterns)] match abi {
BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } => true,
_ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) {
1026 for variant in &mut layout_variants {
1027 if #[allow(non_exhaustive_omitted_patterns)] match variant.backend_repr {
BackendRepr::Memory { .. } if variant.has_fields() => true,
_ => false,
}matches!(variant.backend_repr, BackendRepr::Memory { .. } if variant.has_fields())
1030 {
1031 variant.backend_repr = abi;
1032 variant.size = cmp::max(variant.size, size);
1034 }
1035 }
1036 }
1037
1038 let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1039
1040 let tagged_layout = LayoutData {
1041 variants: Variants::Multiple {
1042 tag,
1043 tag_encoding: TagEncoding::Direct,
1044 tag_field: FieldIdx::new(0),
1045 variants: layout_variants,
1046 },
1047 fields: FieldsShape::Arbitrary {
1048 offsets: [Size::ZERO].into(),
1049 in_memory_order: [FieldIdx::new(0)].into(),
1050 },
1051 largest_niche,
1052 uninhabited,
1053 backend_repr: abi,
1054 align: AbiAlign::new(align),
1055 size,
1056 max_repr_align,
1057 unadjusted_abi_align,
1058 randomization_seed: combined_seed,
1059 };
1060
1061 let best_layout = match (tagged_layout, niche_filling_layout) {
1062 (tl, Some(nl)) => {
1063 use cmp::Ordering::*;
1067 let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1068 l.largest_niche.map_or(0, |n| n.available(dl))
1069 };
1070 match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1071 (Greater, _) => nl,
1072 (Equal, Less) => nl,
1073 _ => tl,
1074 }
1075 }
1076 (tl, None) => tl,
1077 };
1078
1079 Ok(best_layout)
1080 }
1081
1082 fn layout_of_univariant_biased<'a, FieldIdx, VariantIdx, F>(
1083 &self,
1084 fields: &IndexSlice<FieldIdx, F>,
1085 repr: &ReprOptions,
1086 kind: StructKind,
1087 niche_bias: NicheBias,
1088 ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1089 where
1090 FieldIdx: Idx,
1091 VariantIdx: Idx,
1092 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1093 {
1094 let dl = self.cx.data_layout();
1095 let pack = repr.pack;
1096 let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1097 let mut max_repr_align = repr.align;
1098 let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
1099 let optimize_field_order = !repr.inhibit_struct_field_reordering();
1100 let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1101 let optimizing = &mut in_memory_order.raw[..end];
1102 let fields_excluding_tail = &fields.raw[..end];
1103 let field_seed = fields_excluding_tail
1105 .iter()
1106 .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
1107
1108 if optimize_field_order && fields.len() > 1 {
1109 if repr.can_randomize_type_layout() && truecfg!(feature = "randomize") {
1118 #[cfg(feature = "randomize")]
1119 {
1120 use rand::SeedableRng;
1121 use rand::seq::SliceRandom;
1122 let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1125 field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1126 );
1127
1128 optimizing.shuffle(&mut rng);
1130 }
1131 } else {
1133 let max_field_align =
1136 fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
1137 let largest_niche_size = fields_excluding_tail
1138 .iter()
1139 .filter_map(|f| f.largest_niche)
1140 .map(|n| n.available(dl))
1141 .max()
1142 .unwrap_or(0);
1143
1144 let alignment_group_key = |layout: &F| {
1147 if let Some(pack) = pack {
1151 layout.align.abi.min(pack).bytes()
1153 } else {
1154 let align = layout.align.bytes();
1157 let size = layout.size.bytes();
1158 let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1159 let size_as_align = align.max(size).trailing_zeros();
1161 let size_as_align = if largest_niche_size > 0 {
1162 match niche_bias {
1163 NicheBias::Start => {
1167 max_field_align.trailing_zeros().min(size_as_align)
1168 }
1169 NicheBias::End if niche_size == largest_niche_size => {
1173 align.trailing_zeros()
1174 }
1175 NicheBias::End => size_as_align,
1176 }
1177 } else {
1178 size_as_align
1179 };
1180 size_as_align as u64
1181 }
1182 };
1183
1184 match kind {
1185 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1186 optimizing.sort_by_key(|&x| {
1195 let f = &fields[x];
1196 let field_size = f.size.bytes();
1197 let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1198 let niche_size_key = match niche_bias {
1199 NicheBias::Start => !niche_size,
1201 NicheBias::End => niche_size,
1203 };
1204 let inner_niche_offset_key = match niche_bias {
1205 NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1206 NicheBias::End => f.largest_niche.map_or(0, |n| {
1207 !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1208 }),
1209 };
1210
1211 (
1212 cmp::Reverse(alignment_group_key(f)),
1214 niche_size_key,
1217 inner_niche_offset_key,
1220 )
1221 });
1222 }
1223
1224 StructKind::Prefixed(..) => {
1225 optimizing.sort_by_key(|&x| {
1230 let f = &fields[x];
1231 let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1232 (alignment_group_key(f), niche_size)
1233 });
1234 }
1235 }
1236
1237 }
1240 }
1241 let mut unsized_field = None::<&F>;
1246 let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1247 let mut offset = Size::ZERO;
1248 let mut largest_niche = None;
1249 let mut largest_niche_available = 0;
1250 if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1251 let prefix_align =
1252 if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1253 align = align.max(prefix_align);
1254 offset = prefix_size.align_to(prefix_align);
1255 }
1256 for &i in &in_memory_order {
1257 let field = &fields[i];
1258 if let Some(unsized_field) = unsized_field {
1259 return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1260 }
1261
1262 if field.is_unsized() {
1263 if let StructKind::MaybeUnsized = kind {
1264 unsized_field = Some(field);
1265 } else {
1266 return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1267 }
1268 }
1269
1270 let field_align = if let Some(pack) = pack {
1272 field.align.min(AbiAlign::new(pack))
1273 } else {
1274 field.align
1275 };
1276 offset = offset.align_to(field_align.abi);
1277 align = align.max(field_align.abi);
1278 max_repr_align = max_repr_align.max(field.max_repr_align);
1279
1280 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:1280",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1280u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("univariant offset: {0:?} field: {1:#?}",
offset, field) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("univariant offset: {:?} field: {:#?}", offset, field);
1281 offsets[i] = offset;
1282
1283 if let Some(mut niche) = field.largest_niche {
1284 let available = niche.available(dl);
1285 let prefer_new_niche = match niche_bias {
1287 NicheBias::Start => available > largest_niche_available,
1288 NicheBias::End => available >= largest_niche_available,
1290 };
1291 if prefer_new_niche {
1292 largest_niche_available = available;
1293 niche.offset += offset;
1294 largest_niche = Some(niche);
1295 }
1296 }
1297
1298 offset =
1299 offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1300 }
1301
1302 let unadjusted_abi_align = align;
1305 if let Some(repr_align) = repr.align {
1306 align = align.max(repr_align);
1307 }
1308 let align = align;
1310
1311 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs:1311",
"rustc_abi::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout.rs"),
::tracing_core::__macro_support::Option::Some(1311u32),
::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("univariant min_size: {0:?}",
offset) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("univariant min_size: {:?}", offset);
1312 let min_size = offset;
1313 let size = min_size.align_to(align);
1314 if size.bytes() >= dl.obj_size_bound() {
1316 return Err(LayoutCalculatorError::SizeOverflow);
1317 }
1318 let mut layout_of_single_non_zst_field = None;
1319 let sized = unsized_field.is_none();
1320 let mut abi = BackendRepr::Memory { sized };
1321
1322 let optimize_abi = !repr.inhibit_newtype_abi_optimization();
1323
1324 if sized && size.bytes() > 0 {
1326 let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
1329
1330 match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1331 (Some((i, field)), None, None) => {
1333 layout_of_single_non_zst_field = Some(field);
1334
1335 if offsets[i].bytes() == 0 && align == field.align.abi && size == field.size {
1337 match field.backend_repr {
1338 BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1341 if optimize_abi =>
1342 {
1343 abi = field.backend_repr;
1344 }
1345 BackendRepr::ScalarPair { .. } => {
1348 abi = field.backend_repr;
1349 }
1350 _ => {}
1351 }
1352 }
1353 }
1354
1355 (Some((i, a)), Some((j, b)), None) => {
1357 match (a.backend_repr, b.backend_repr) {
1358 (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1359 let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1361 ((i, a), (j, b))
1362 } else {
1363 ((j, b), (i, a))
1364 };
1365 let pair =
1366 LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1367 let pair_offsets = match pair.fields {
1368 FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1369 {
match (&in_memory_order.raw, &[FieldIdx::new(0), FieldIdx::new(1)]) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(
1370 in_memory_order.raw,
1371 [FieldIdx::new(0), FieldIdx::new(1)]
1372 );
1373 offsets
1374 }
1375 FieldsShape::Primitive
1376 | FieldsShape::Array { .. }
1377 | FieldsShape::Union(..) => {
1378 {
::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")
1379 }
1380 };
1381 if offsets[i] == pair_offsets[FieldIdx::new(0)]
1382 && offsets[j] == pair_offsets[FieldIdx::new(1)]
1383 && align == pair.align.abi
1384 && size == pair.size
1385 {
1386 abi = pair.backend_repr;
1389 }
1390 }
1391 _ => {}
1392 }
1393 }
1394
1395 _ => {}
1396 }
1397 }
1398 let uninhabited = fields.iter().any(|f| f.is_uninhabited());
1399
1400 let unadjusted_abi_align = if repr.transparent() {
1401 match layout_of_single_non_zst_field {
1402 Some(l) => l.unadjusted_abi_align,
1403 None => {
1404 align
1406 }
1407 }
1408 } else {
1409 unadjusted_abi_align
1410 };
1411
1412 let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
1413
1414 Ok(LayoutData {
1415 variants: Variants::Single { index: VariantIdx::new(0) },
1416 fields: FieldsShape::Arbitrary { offsets, in_memory_order },
1417 backend_repr: abi,
1418 largest_niche,
1419 uninhabited,
1420 align: AbiAlign::new(align),
1421 size,
1422 max_repr_align,
1423 unadjusted_abi_align,
1424 randomization_seed: seed,
1425 })
1426 }
1427
1428 fn format_field_niches<'a, FieldIdx, VariantIdx, F>(
1429 &self,
1430 layout: &LayoutData<FieldIdx, VariantIdx>,
1431 fields: &IndexSlice<FieldIdx, F>,
1432 ) -> String
1433 where
1434 FieldIdx: Idx,
1435 VariantIdx: Idx,
1436 F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1437 {
1438 let dl = self.cx.data_layout();
1439 let mut s = String::new();
1440 for i in layout.fields.index_by_increasing_offset() {
1441 let offset = layout.fields.offset(i);
1442 let f = &fields[FieldIdx::new(i)];
1443 s.write_fmt(format_args!("[o{0}a{1}s{2}", offset.bytes(), f.align.bytes(),
f.size.bytes()))write!(s, "[o{}a{}s{}", offset.bytes(), f.align.bytes(), f.size.bytes()).unwrap();
1444 if let Some(n) = f.largest_niche {
1445 s.write_fmt(format_args!(" n{0}b{1}s{2}", n.offset.bytes(),
n.available(dl).ilog2(), n.value.size(dl).bytes()))write!(
1446 s,
1447 " n{}b{}s{}",
1448 n.offset.bytes(),
1449 n.available(dl).ilog2(),
1450 n.value.size(dl).bytes()
1451 )
1452 .unwrap();
1453 }
1454 s.write_fmt(format_args!("] "))write!(s, "] ").unwrap();
1455 }
1456 s
1457 }
1458}
1459
1460enum SimdVectorKind {
1461 Scalable(NumScalableVectors),
1463 PackedFixed,
1465 Fixed,
1467}
1468
1469fn vector_type_layout<FieldIdx, VariantIdx, F>(
1470 kind: SimdVectorKind,
1471 dl: &TargetDataLayout,
1472 element: F,
1473 count: u64,
1474) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1475where
1476 FieldIdx: Idx,
1477 VariantIdx: Idx,
1478 F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1479{
1480 let elt = element.as_ref();
1481 let count = BackendLaneCount::new(count)?;
1482
1483 let BackendRepr::Scalar(element) = elt.backend_repr else {
1484 return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
1485 };
1486
1487 let size =
1489 elt.size.checked_mul(count.as_u64(), dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1490 let (repr, size, align) = match kind {
1491 SimdVectorKind::Scalable(number_of_vectors) => (
1492 BackendRepr::SimdScalableVector { element, count, number_of_vectors },
1493 size.checked_mul(number_of_vectors.0 as u64, dl)
1494 .ok_or(LayoutCalculatorError::SizeOverflow)?,
1495 dl.rust_vector_align(size),
1496 ),
1497 SimdVectorKind::PackedFixed if !count.is_power_of_two() => {
1501 (BackendRepr::Memory { sized: true }, size, Align::max_aligned_factor(size))
1502 }
1503 SimdVectorKind::PackedFixed | SimdVectorKind::Fixed => {
1504 (BackendRepr::SimdVector { element, count }, size, dl.rust_vector_align(size))
1505 }
1506 };
1507 let size = size.align_to(align);
1508
1509 Ok(LayoutData {
1510 variants: Variants::Single { index: VariantIdx::new(0) },
1511 fields: FieldsShape::Arbitrary {
1512 offsets: [Size::ZERO].into(),
1513 in_memory_order: [FieldIdx::new(0)].into(),
1514 },
1515 backend_repr: repr,
1516 largest_niche: elt.largest_niche,
1517 uninhabited: false,
1518 size,
1519 align: AbiAlign::new(align),
1520 max_repr_align: None,
1521 unadjusted_abi_align: elt.align.abi,
1522 randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count.as_u64())),
1523 })
1524}