Skip to main content

rustc_abi/
layout.rs

1use std::collections::BTreeSet;
2use std::fmt::{self, Write};
3use std::ops::{Bound, Deref};
4use std::{cmp, iter};
5
6use rustc_hashes::Hash64;
7use rustc_index::Idx;
8use rustc_index::bit_set::BitMatrix;
9use tracing::{debug, trace};
10
11use crate::{
12    AbiAlign, Align, BackendRepr, FieldsShape, HasDataLayout, IndexSlice, IndexVec, Integer,
13    LayoutData, Niche, NonZeroUsize, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding,
14    TargetDataLayout, Variants, WrappingRange,
15};
16
17mod coroutine;
18mod simple;
19
20#[cfg(feature = "nightly")]
21mod ty;
22
23#[cfg(feature = "nightly")]
24pub use ty::{Layout, TyAbiInterface, TyAndLayout};
25
26impl ::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! {
27    /// The *source-order* index of a field in a variant.
28    ///
29    /// This is how most code after type checking refers to fields, rather than
30    /// using names (as names have hygiene complications and more complex lookup).
31    ///
32    /// Particularly for `repr(Rust)` types, this may not be the same as *layout* order.
33    /// (It is for `repr(C)` `struct`s, however.)
34    ///
35    /// For example, in the following types,
36    /// ```rust
37    /// # enum Never {}
38    /// # #[repr(u16)]
39    /// enum Demo1 {
40    ///    Variant0 { a: Never, b: i32 } = 100,
41    ///    Variant1 { c: u8, d: u64 } = 10,
42    /// }
43    /// struct Demo2 { e: u8, f: u16, g: u8 }
44    /// ```
45    /// `b` is `FieldIdx(1)` in `VariantIdx(0)`,
46    /// `d` is `FieldIdx(1)` in `VariantIdx(1)`, and
47    /// `f` is `FieldIdx(1)` in `VariantIdx(0)`.
48    #[cfg_attr(feature = "nightly", derive(rustc_macros::HashStable_Generic))]
49    #[encodable]
50    #[orderable]
51    #[gate_rustc_only]
52    pub struct FieldIdx {}
53}
54
55impl FieldIdx {
56    /// The second field, at index 1.
57    ///
58    /// For use alongside [`FieldIdx::ZERO`], particularly with scalar pairs.
59    pub const ONE: FieldIdx = FieldIdx::from_u32(1);
60}
61
62impl ::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! {
63    /// The *source-order* index of a variant in a type.
64    ///
65    /// For enums, these are always `0..variant_count`, regardless of any
66    /// custom discriminants that may have been defined, and including any
67    /// variants that may end up uninhabited due to field types.  (Some of the
68    /// variants may not be present in a monomorphized ABI [`Variants`], but
69    /// those skipped variants are always counted when determining the *index*.)
70    ///
71    /// `struct`s, `tuples`, and `unions`s are considered to have a single variant
72    /// with variant index zero, aka [`FIRST_VARIANT`].
73    #[cfg_attr(feature = "nightly", derive(rustc_macros::HashStable_Generic))]
74    #[encodable]
75    #[orderable]
76    #[gate_rustc_only]
77    pub struct VariantIdx {
78        /// Equivalent to `VariantIdx(0)`.
79        const FIRST_VARIANT = 0;
80    }
81}
82
83// A variant is absent if it's uninhabited and only has ZST fields.
84// Present uninhabited variants only require space for their fields,
85// but *not* an encoding of the discriminant (e.g., a tag value).
86// See issue #49298 for more details on the need to leave space
87// for non-ZST uninhabited data (mostly partial initialization).
88fn absent<'a, FieldIdx, VariantIdx, F>(fields: &IndexSlice<FieldIdx, F>) -> bool
89where
90    FieldIdx: Idx,
91    VariantIdx: Idx,
92    F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
93{
94    let uninhabited = fields.iter().any(|f| f.is_uninhabited());
95    // We cannot ignore alignment; that might lead us to entirely discard a variant and
96    // produce an enum that is less aligned than it should be!
97    let is_1zst = fields.iter().all(|f| f.is_1zst());
98    uninhabited && is_1zst
99}
100
101/// Determines towards which end of a struct layout optimizations will try to place the best niches.
102enum NicheBias {
103    Start,
104    End,
105}
106
107#[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) -> LayoutCalculatorError<F> {
        match self {
            LayoutCalculatorError::UnexpectedUnsized(__self_0) =>
                LayoutCalculatorError::UnexpectedUnsized(::core::clone::Clone::clone(__self_0)),
            LayoutCalculatorError::SizeOverflow =>
                LayoutCalculatorError::SizeOverflow,
            LayoutCalculatorError::EmptyUnion =>
                LayoutCalculatorError::EmptyUnion,
            LayoutCalculatorError::ReprConflict =>
                LayoutCalculatorError::ReprConflict,
            LayoutCalculatorError::ZeroLengthSimdType =>
                LayoutCalculatorError::ZeroLengthSimdType,
            LayoutCalculatorError::OversizedSimdType { max_lanes: __self_0 }
                =>
                LayoutCalculatorError::OversizedSimdType {
                    max_lanes: ::core::clone::Clone::clone(__self_0),
                },
            LayoutCalculatorError::NonPrimitiveSimdType(__self_0) =>
                LayoutCalculatorError::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 {
            LayoutCalculatorError::UnexpectedUnsized(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "UnexpectedUnsized", &__self_0),
            LayoutCalculatorError::SizeOverflow =>
                ::core::fmt::Formatter::write_str(f, "SizeOverflow"),
            LayoutCalculatorError::EmptyUnion =>
                ::core::fmt::Formatter::write_str(f, "EmptyUnion"),
            LayoutCalculatorError::ReprConflict =>
                ::core::fmt::Formatter::write_str(f, "ReprConflict"),
            LayoutCalculatorError::ZeroLengthSimdType =>
                ::core::fmt::Formatter::write_str(f, "ZeroLengthSimdType"),
            LayoutCalculatorError::OversizedSimdType { max_lanes: __self_0 }
                =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OversizedSimdType", "max_lanes", &__self_0),
            LayoutCalculatorError::NonPrimitiveSimdType(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NonPrimitiveSimdType", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<F: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
    LayoutCalculatorError<F> {
    #[inline]
    fn eq(&self, other: &LayoutCalculatorError<F>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (LayoutCalculatorError::UnexpectedUnsized(__self_0),
                    LayoutCalculatorError::UnexpectedUnsized(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (LayoutCalculatorError::OversizedSimdType {
                    max_lanes: __self_0 },
                    LayoutCalculatorError::OversizedSimdType {
                    max_lanes: __arg1_0 }) => __self_0 == __arg1_0,
                (LayoutCalculatorError::NonPrimitiveSimdType(__self_0),
                    LayoutCalculatorError::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<u64>;
    }
}Eq)]
108pub enum LayoutCalculatorError<F> {
109    /// An unsized type was found in a location where a sized type was expected.
110    ///
111    /// This is not always a compile error, for example if there is a `[T]: Sized`
112    /// bound in a where clause.
113    ///
114    /// Contains the field that was unexpectedly unsized.
115    UnexpectedUnsized(F),
116
117    /// A type was too large for the target platform.
118    SizeOverflow,
119
120    /// A union had no fields.
121    EmptyUnion,
122
123    /// The fields or variants have irreconcilable reprs
124    ReprConflict,
125
126    /// The length of an SIMD type is zero
127    ZeroLengthSimdType,
128
129    /// The length of an SIMD type exceeds the maximum number of lanes
130    OversizedSimdType { max_lanes: u64 },
131
132    /// An element type of an SIMD type isn't a primitive
133    NonPrimitiveSimdType(F),
134}
135
136impl<F> LayoutCalculatorError<F> {
137    pub fn without_payload(&self) -> LayoutCalculatorError<()> {
138        use LayoutCalculatorError::*;
139        match *self {
140            UnexpectedUnsized(_) => UnexpectedUnsized(()),
141            SizeOverflow => SizeOverflow,
142            EmptyUnion => EmptyUnion,
143            ReprConflict => ReprConflict,
144            ZeroLengthSimdType => ZeroLengthSimdType,
145            OversizedSimdType { max_lanes } => OversizedSimdType { max_lanes },
146            NonPrimitiveSimdType(_) => NonPrimitiveSimdType(()),
147        }
148    }
149
150    /// Format an untranslated diagnostic for this type
151    ///
152    /// Intended for use by rust-analyzer, as neither it nor `rustc_abi` depend on fluent infra.
153    pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        use LayoutCalculatorError::*;
155        f.write_str(match self {
156            UnexpectedUnsized(_) => "an unsized type was found where a sized type was expected",
157            SizeOverflow => "size overflow",
158            EmptyUnion => "type is a union with no fields",
159            ReprConflict => "type has an invalid repr",
160            ZeroLengthSimdType | OversizedSimdType { .. } | NonPrimitiveSimdType(_) => {
161                "invalid simd type definition"
162            }
163        })
164    }
165}
166
167type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
168    Result<LayoutData<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
169
170#[derive(#[automatically_derived]
impl<Cx: ::core::clone::Clone> ::core::clone::Clone for LayoutCalculator<Cx> {
    #[inline]
    fn clone(&self) -> LayoutCalculator<Cx> {
        LayoutCalculator { 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)]
171pub struct LayoutCalculator<Cx> {
172    pub cx: Cx,
173}
174
175impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
176    pub fn new(cx: Cx) -> Self {
177        Self { cx }
178    }
179
180    pub fn array_like<FieldIdx: Idx, VariantIdx: Idx, F>(
181        &self,
182        element: &LayoutData<FieldIdx, VariantIdx>,
183        count_if_sized: Option<u64>, // None for slices
184    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
185        let count = count_if_sized.unwrap_or(0);
186        let size =
187            element.size.checked_mul(count, &self.cx).ok_or(LayoutCalculatorError::SizeOverflow)?;
188
189        Ok(LayoutData {
190            variants: Variants::Single { index: VariantIdx::new(0) },
191            fields: FieldsShape::Array { stride: element.size, count },
192            backend_repr: BackendRepr::Memory { sized: count_if_sized.is_some() },
193            largest_niche: element.largest_niche.filter(|_| count != 0),
194            uninhabited: element.uninhabited && count != 0,
195            align: element.align,
196            size,
197            max_repr_align: None,
198            unadjusted_abi_align: element.align.abi,
199            randomization_seed: element.randomization_seed.wrapping_add(Hash64::new(count)),
200        })
201    }
202
203    pub fn scalable_vector_type<FieldIdx, VariantIdx, F>(
204        &self,
205        element: F,
206        count: u64,
207    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
208    where
209        FieldIdx: Idx,
210        VariantIdx: Idx,
211        F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
212    {
213        vector_type_layout(VectorKind::Scalable, self.cx.data_layout(), element, count)
214    }
215
216    pub fn simd_type<FieldIdx, VariantIdx, F>(
217        &self,
218        element: F,
219        count: u64,
220        repr_packed: bool,
221    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
222    where
223        FieldIdx: Idx,
224        VariantIdx: Idx,
225        F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
226    {
227        let kind = if repr_packed { VectorKind::PackedFixed } else { VectorKind::Fixed };
228        vector_type_layout(kind, self.cx.data_layout(), element, count)
229    }
230
231    /// Compute the layout for a coroutine.
232    ///
233    /// This uses dedicated code instead of [`Self::layout_of_struct_or_enum`], as coroutine
234    /// fields may be shared between multiple variants (see the [`coroutine`] module for details).
235    pub fn coroutine<
236        'a,
237        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
238        VariantIdx: Idx,
239        FieldIdx: Idx,
240        LocalIdx: Idx,
241    >(
242        &self,
243        local_layouts: &IndexSlice<LocalIdx, F>,
244        prefix_layouts: IndexVec<FieldIdx, F>,
245        variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
246        storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
247        tag_to_layout: impl Fn(Scalar) -> F,
248    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
249        coroutine::layout(
250            self,
251            local_layouts,
252            prefix_layouts,
253            variant_fields,
254            storage_conflicts,
255            tag_to_layout,
256        )
257    }
258
259    pub fn univariant<
260        'a,
261        FieldIdx: Idx,
262        VariantIdx: Idx,
263        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
264    >(
265        &self,
266        fields: &IndexSlice<FieldIdx, F>,
267        repr: &ReprOptions,
268        kind: StructKind,
269    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
270        let dl = self.cx.data_layout();
271        let layout = self.univariant_biased(fields, repr, kind, NicheBias::Start);
272        // Enums prefer niches close to the beginning or the end of the variants so that other
273        // (smaller) data-carrying variants can be packed into the space after/before the niche.
274        // If the default field ordering does not give us a niche at the front then we do a second
275        // run and bias niches to the right and then check which one is closer to one of the
276        // struct's edges.
277        if let Ok(layout) = &layout {
278            // Don't try to calculate an end-biased layout for unsizable structs,
279            // otherwise we could end up with different layouts for
280            // Foo<Type> and Foo<dyn Trait> which would break unsizing.
281            if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    StructKind::MaybeUnsized => true,
    _ => false,
}matches!(kind, StructKind::MaybeUnsized) {
282                if let Some(niche) = layout.largest_niche {
283                    let head_space = niche.offset.bytes();
284                    let niche_len = niche.value.size(dl).bytes();
285                    let tail_space = layout.size.bytes() - head_space - niche_len;
286
287                    // This may end up doing redundant work if the niche is already in the last
288                    // field (e.g. a trailing bool) and there is tail padding. But it's non-trivial
289                    // to get the unpadded size so we try anyway.
290                    if fields.len() > 1 && head_space != 0 && tail_space > 0 {
291                        let alt_layout = self
292                            .univariant_biased(fields, repr, kind, NicheBias::End)
293                            .expect("alt layout should always work");
294                        let alt_niche = alt_layout
295                            .largest_niche
296                            .expect("alt layout should have a niche like the regular one");
297                        let alt_head_space = alt_niche.offset.bytes();
298                        let alt_niche_len = alt_niche.value.size(dl).bytes();
299                        let alt_tail_space =
300                            alt_layout.size.bytes() - alt_head_space - alt_niche_len;
301
302                        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());
303
304                        let prefer_alt_layout =
305                            alt_head_space > head_space && alt_head_space > tail_space;
306
307                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:307",
                        "rustc_abi::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(307u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
308                            "sz: {}, default_niche_at: {}+{}, default_tail_space: {}, alt_niche_at/head_space: {}+{}, alt_tail: {}, num_fields: {}, better: {}\n\
309                            layout: {}\n\
310                            alt_layout: {}\n",
311                            layout.size.bytes(),
312                            head_space,
313                            niche_len,
314                            tail_space,
315                            alt_head_space,
316                            alt_niche_len,
317                            alt_tail_space,
318                            layout.fields.count(),
319                            prefer_alt_layout,
320                            self.format_field_niches(layout, fields),
321                            self.format_field_niches(&alt_layout, fields),
322                        );
323
324                        if prefer_alt_layout {
325                            return Ok(alt_layout);
326                        }
327                    }
328                }
329            }
330        }
331        layout
332    }
333
334    pub fn layout_of_struct_or_enum<
335        'a,
336        FieldIdx: Idx,
337        VariantIdx: Idx,
338        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
339    >(
340        &self,
341        repr: &ReprOptions,
342        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
343        is_enum: bool,
344        is_special_no_niche: bool,
345        scalar_valid_range: (Bound<u128>, Bound<u128>),
346        discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
347        discriminants: impl Iterator<Item = (VariantIdx, i128)>,
348        always_sized: bool,
349    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
350        let (present_first, present_second) = {
351            let mut present_variants = variants.iter_enumerated().filter_map(|(i, v)| {
352                if !repr.inhibit_enum_layout_opt() && absent(v) { None } else { Some(i) }
353            });
354            (present_variants.next(), present_variants.next())
355        };
356        let present_first = match present_first {
357            Some(present_first) => present_first,
358            // Uninhabited because it has no variants, or only absent ones.
359            None if is_enum => {
360                return Ok(LayoutData::never_type(&self.cx));
361            }
362            // If it's a struct, still compute a layout so that we can still compute the
363            // field offsets.
364            None => VariantIdx::new(0),
365        };
366
367        // take the struct path if it is an actual struct
368        if !is_enum ||
369            // or for optimizing univariant enums
370            (present_second.is_none() && !repr.inhibit_enum_layout_opt())
371        {
372            self.layout_of_struct(
373                repr,
374                variants,
375                is_enum,
376                is_special_no_niche,
377                scalar_valid_range,
378                always_sized,
379                present_first,
380            )
381        } else {
382            // At this point, we have handled all unions and
383            // structs. (We have also handled univariant enums
384            // that allow representation optimization.)
385            if !is_enum { ::core::panicking::panic("assertion failed: is_enum") };assert!(is_enum);
386            self.layout_of_enum(repr, variants, discr_range_of_repr, discriminants)
387        }
388    }
389
390    pub fn layout_of_union<
391        'a,
392        FieldIdx: Idx,
393        VariantIdx: Idx,
394        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
395    >(
396        &self,
397        repr: &ReprOptions,
398        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
399    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
400        let dl = self.cx.data_layout();
401        let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
402        let mut max_repr_align = repr.align;
403
404        // If all the non-ZST fields have the same repr and union repr optimizations aren't
405        // disabled, we can use that common repr for the union as a whole.
406        struct AbiMismatch;
407        let mut common_non_zst_repr_and_align = if repr.inhibits_union_abi_opt() {
408            // Can't optimize
409            Err(AbiMismatch)
410        } else {
411            Ok(None)
412        };
413
414        let mut size = Size::ZERO;
415        let only_variant_idx = VariantIdx::new(0);
416        let only_variant = &variants[only_variant_idx];
417        for field in only_variant {
418            if field.is_unsized() {
419                return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
420            }
421
422            align = align.max(field.align.abi);
423            max_repr_align = max_repr_align.max(field.max_repr_align);
424            size = cmp::max(size, field.size);
425
426            if field.is_zst() {
427                // Nothing more to do for ZST fields
428                continue;
429            }
430
431            if let Ok(common) = common_non_zst_repr_and_align {
432                // Discard valid range information and allow undef
433                let field_abi = field.backend_repr.to_union();
434
435                if let Some((common_abi, common_align)) = common {
436                    if common_abi != field_abi {
437                        // Different fields have different ABI: disable opt
438                        common_non_zst_repr_and_align = Err(AbiMismatch);
439                    } else {
440                        // Fields with the same non-Aggregate ABI should also
441                        // have the same alignment
442                        if !#[allow(non_exhaustive_omitted_patterns)] match common_abi {
    BackendRepr::Memory { .. } => true,
    _ => false,
}matches!(common_abi, BackendRepr::Memory { .. }) {
443                            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!(
444                                common_align, field.align.abi,
445                                "non-Aggregate field with matching ABI but differing alignment"
446                            );
447                        }
448                    }
449                } else {
450                    // First non-ZST field: record its ABI and alignment
451                    common_non_zst_repr_and_align = Ok(Some((field_abi, field.align.abi)));
452                }
453            }
454        }
455
456        if let Some(pack) = repr.pack {
457            align = align.min(pack);
458        }
459        // The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
460        // See documentation on `LayoutData::unadjusted_abi_align`.
461        let unadjusted_abi_align = align;
462        if let Some(repr_align) = repr.align {
463            align = align.max(repr_align);
464        }
465        // `align` must not be modified after this, or `unadjusted_abi_align` could be inaccurate.
466        let align = align;
467
468        // If all non-ZST fields have the same ABI, we may forward that ABI
469        // for the union as a whole, unless otherwise inhibited.
470        let backend_repr = match common_non_zst_repr_and_align {
471            Err(AbiMismatch) | Ok(None) => BackendRepr::Memory { sized: true },
472            Ok(Some((repr, _))) => match repr {
473                // Mismatched alignment (e.g. union is #[repr(packed)]): disable opt
474                BackendRepr::Scalar(_) | BackendRepr::ScalarPair(_, _)
475                    if repr.scalar_align(dl).unwrap() != align =>
476                {
477                    BackendRepr::Memory { sized: true }
478                }
479                // Vectors require at least element alignment, else disable the opt
480                BackendRepr::SimdVector { element, count: _ } if element.align(dl).abi > align => {
481                    BackendRepr::Memory { sized: true }
482                }
483                // the alignment tests passed and we can use this
484                BackendRepr::Scalar(..)
485                | BackendRepr::ScalarPair(..)
486                | BackendRepr::SimdVector { .. }
487                | BackendRepr::ScalableVector { .. }
488                | BackendRepr::Memory { .. } => repr,
489            },
490        };
491
492        let Some(union_field_count) = NonZeroUsize::new(only_variant.len()) else {
493            return Err(LayoutCalculatorError::EmptyUnion);
494        };
495
496        let combined_seed = only_variant
497            .iter()
498            .map(|v| v.randomization_seed)
499            .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
500
501        Ok(LayoutData {
502            variants: Variants::Single { index: only_variant_idx },
503            fields: FieldsShape::Union(union_field_count),
504            backend_repr,
505            largest_niche: None,
506            uninhabited: false,
507            align: AbiAlign::new(align),
508            size: size.align_to(align),
509            max_repr_align,
510            unadjusted_abi_align,
511            randomization_seed: combined_seed,
512        })
513    }
514
515    /// single-variant enums are just structs, if you think about it
516    fn layout_of_struct<
517        'a,
518        FieldIdx: Idx,
519        VariantIdx: Idx,
520        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
521    >(
522        &self,
523        repr: &ReprOptions,
524        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
525        is_enum: bool,
526        is_special_no_niche: bool,
527        scalar_valid_range: (Bound<u128>, Bound<u128>),
528        always_sized: bool,
529        present_first: VariantIdx,
530    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
531        // Struct, or univariant enum equivalent to a struct.
532        // (Typechecking will reject discriminant-sizing attrs.)
533
534        let dl = self.cx.data_layout();
535        let v = present_first;
536        let kind = if is_enum || variants[v].is_empty() || always_sized {
537            StructKind::AlwaysSized
538        } else {
539            StructKind::MaybeUnsized
540        };
541
542        let mut st = self.univariant(&variants[v], repr, kind)?;
543        st.variants = Variants::Single { index: v };
544
545        if is_special_no_niche {
546            let hide_niches = |scalar: &mut _| match scalar {
547                Scalar::Initialized { value, valid_range } => {
548                    *valid_range = WrappingRange::full(value.size(dl))
549                }
550                // Already doesn't have any niches
551                Scalar::Union { .. } => {}
552            };
553            match &mut st.backend_repr {
554                BackendRepr::Scalar(scalar) => hide_niches(scalar),
555                BackendRepr::ScalarPair(a, b) => {
556                    hide_niches(a);
557                    hide_niches(b);
558                }
559                BackendRepr::SimdVector { element, .. }
560                | BackendRepr::ScalableVector { element, .. } => hide_niches(element),
561                BackendRepr::Memory { sized: _ } => {}
562            }
563            st.largest_niche = None;
564            return Ok(st);
565        }
566
567        let (start, end) = scalar_valid_range;
568        match st.backend_repr {
569            BackendRepr::Scalar(ref mut scalar) | BackendRepr::ScalarPair(ref mut scalar, _) => {
570                // Enlarging validity ranges would result in missed
571                // optimizations, *not* wrongly assuming the inner
572                // value is valid. e.g. unions already enlarge validity ranges,
573                // because the values may be uninitialized.
574                //
575                // Because of that we only check that the start and end
576                // of the range is representable with this scalar type.
577
578                let max_value = scalar.size(dl).unsigned_int_max();
579                if let Bound::Included(start) = start {
580                    // FIXME(eddyb) this might be incorrect - it doesn't
581                    // account for wrap-around (end < start) ranges.
582                    if !(start <= max_value) {
    {
        ::core::panicking::panic_fmt(format_args!("{0} > {1}", start,
                max_value));
    }
};assert!(start <= max_value, "{start} > {max_value}");
583                    scalar.valid_range_mut().start = start;
584                }
585                if let Bound::Included(end) = end {
586                    // FIXME(eddyb) this might be incorrect - it doesn't
587                    // account for wrap-around (end < start) ranges.
588                    if !(end <= max_value) {
    {
        ::core::panicking::panic_fmt(format_args!("{0} > {1}", end,
                max_value));
    }
};assert!(end <= max_value, "{end} > {max_value}");
589                    scalar.valid_range_mut().end = end;
590                }
591
592                // Update `largest_niche` if we have introduced a larger niche.
593                let niche = Niche::from_scalar(dl, Size::ZERO, *scalar);
594                if let Some(niche) = niche {
595                    match st.largest_niche {
596                        Some(largest_niche) => {
597                            // Replace the existing niche even if they're equal,
598                            // because this one is at a lower offset.
599                            if largest_niche.available(dl) <= niche.available(dl) {
600                                st.largest_niche = Some(niche);
601                            }
602                        }
603                        None => st.largest_niche = Some(niche),
604                    }
605                }
606            }
607            _ => if !(start == Bound::Unbounded && end == Bound::Unbounded) {
    {
        ::core::panicking::panic_fmt(format_args!("nonscalar layout for layout_scalar_valid_range type: {0:#?}",
                st));
    }
}assert!(
608                start == Bound::Unbounded && end == Bound::Unbounded,
609                "nonscalar layout for layout_scalar_valid_range type: {st:#?}",
610            ),
611        }
612
613        Ok(st)
614    }
615
616    fn layout_of_enum<
617        'a,
618        FieldIdx: Idx,
619        VariantIdx: Idx,
620        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
621    >(
622        &self,
623        repr: &ReprOptions,
624        variants: &IndexSlice<VariantIdx, IndexVec<FieldIdx, F>>,
625        discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
626        discriminants: impl Iterator<Item = (VariantIdx, i128)>,
627    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
628        let dl = self.cx.data_layout();
629        // bail if the enum has an incoherent repr that cannot be computed
630        if repr.packed() {
631            return Err(LayoutCalculatorError::ReprConflict);
632        }
633
634        let calculate_niche_filling_layout = || -> Option<LayoutData<FieldIdx, VariantIdx>> {
635            if repr.inhibit_enum_layout_opt() {
636                return None;
637            }
638
639            if variants.len() < 2 {
640                return None;
641            }
642
643            let mut align = dl.aggregate_align;
644            let mut max_repr_align = repr.align;
645            let mut unadjusted_abi_align = align;
646
647            let mut variant_layouts = variants
648                .iter_enumerated()
649                .map(|(j, v)| {
650                    let mut st = self.univariant(v, repr, StructKind::AlwaysSized).ok()?;
651                    st.variants = Variants::Single { index: j };
652
653                    align = align.max(st.align.abi);
654                    max_repr_align = max_repr_align.max(st.max_repr_align);
655                    unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
656
657                    Some(st)
658                })
659                .collect::<Option<IndexVec<VariantIdx, _>>>()?;
660
661            let largest_variant_index = variant_layouts
662                .iter_enumerated()
663                .max_by_key(|(_i, layout)| layout.size.bytes())
664                .map(|(i, _layout)| i)?;
665
666            let all_indices = variants.indices();
667            let needs_disc =
668                |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
669            let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
670                ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();
671
672            let count =
673                (niche_variants.end().index() as u128 - niche_variants.start().index() as u128) + 1;
674
675            // Use the largest niche in the largest variant.
676            let niche = variant_layouts[largest_variant_index].largest_niche?;
677            let (niche_start, niche_scalar) = niche.reserve(dl, count)?;
678            let niche_offset = niche.offset;
679            let niche_size = niche.value.size(dl);
680            let size = variant_layouts[largest_variant_index].size.align_to(align);
681
682            let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
683                if i == largest_variant_index {
684                    return true;
685                }
686
687                layout.largest_niche = None;
688
689                if layout.size <= niche_offset {
690                    // This variant will fit before the niche.
691                    return true;
692                }
693
694                // Determine if it'll fit after the niche.
695                let this_align = layout.align.abi;
696                let this_offset = (niche_offset + niche_size).align_to(this_align);
697
698                if this_offset + layout.size > size {
699                    return false;
700                }
701
702                // It'll fit, but we need to make some adjustments.
703                match layout.fields {
704                    FieldsShape::Arbitrary { ref mut offsets, .. } => {
705                        for offset in offsets.iter_mut() {
706                            *offset += this_offset;
707                        }
708                    }
709                    FieldsShape::Primitive | FieldsShape::Array { .. } | FieldsShape::Union(..) => {
710                        {
    ::core::panicking::panic_fmt(format_args!("Layout of fields should be Arbitrary for variants"));
}panic!("Layout of fields should be Arbitrary for variants")
711                    }
712                }
713
714                // It can't be a Scalar or ScalarPair because the offset isn't 0.
715                if !layout.is_uninhabited() {
716                    layout.backend_repr = BackendRepr::Memory { sized: true };
717                }
718                layout.size += this_offset;
719
720                true
721            });
722
723            if !all_variants_fit {
724                return None;
725            }
726
727            let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
728
729            let others_zst = variant_layouts
730                .iter_enumerated()
731                .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
732            let same_size = size == variant_layouts[largest_variant_index].size;
733            let same_align = align == variant_layouts[largest_variant_index].align.abi;
734
735            let uninhabited = variant_layouts.iter().all(|v| v.is_uninhabited());
736            let abi = if same_size && same_align && others_zst {
737                match variant_layouts[largest_variant_index].backend_repr {
738                    // When the total alignment and size match, we can use the
739                    // same ABI as the scalar variant with the reserved niche.
740                    BackendRepr::Scalar(_) => BackendRepr::Scalar(niche_scalar),
741                    BackendRepr::ScalarPair(first, second) => {
742                        // Only the niche is guaranteed to be initialised,
743                        // so use union layouts for the other primitive.
744                        if niche_offset == Size::ZERO {
745                            BackendRepr::ScalarPair(niche_scalar, second.to_union())
746                        } else {
747                            BackendRepr::ScalarPair(first.to_union(), niche_scalar)
748                        }
749                    }
750                    _ => BackendRepr::Memory { sized: true },
751                }
752            } else {
753                BackendRepr::Memory { sized: true }
754            };
755
756            let combined_seed = variant_layouts
757                .iter()
758                .map(|v| v.randomization_seed)
759                .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
760
761            let layout = LayoutData {
762                variants: Variants::Multiple {
763                    tag: niche_scalar,
764                    tag_encoding: TagEncoding::Niche {
765                        untagged_variant: largest_variant_index,
766                        niche_variants,
767                        niche_start,
768                    },
769                    tag_field: FieldIdx::new(0),
770                    variants: variant_layouts,
771                },
772                fields: FieldsShape::Arbitrary {
773                    offsets: [niche_offset].into(),
774                    in_memory_order: [FieldIdx::new(0)].into(),
775                },
776                backend_repr: abi,
777                largest_niche,
778                uninhabited,
779                size,
780                align: AbiAlign::new(align),
781                max_repr_align,
782                unadjusted_abi_align,
783                randomization_seed: combined_seed,
784            };
785
786            Some(layout)
787        };
788
789        let niche_filling_layout = calculate_niche_filling_layout();
790
791        let discr_type = repr.discr_type();
792        let discr_int = Integer::from_attr(dl, discr_type);
793        // Because we can only represent one range of valid values, we'll look for the
794        // largest range of invalid values and pick everything else as the range of valid
795        // values.
796
797        // First we need to sort the possible discriminant values so that we can look for the largest gap:
798        let valid_discriminants: BTreeSet<i128> = discriminants
799            .filter(|&(i, _)| repr.c() || variants[i].iter().all(|f| !f.is_uninhabited()))
800            .map(|(_, val)| {
801                if discr_type.is_signed() {
802                    // sign extend the raw representation to be an i128
803                    // FIXME: do this at the discriminant iterator creation sites
804                    discr_int.size().sign_extend(val as u128)
805                } else {
806                    val
807                }
808            })
809            .collect();
810        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:810",
                        "rustc_abi::layout", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(810u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
                        ::tracing_core::field::FieldSet::new(&["valid_discriminants"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&valid_discriminants)
                                            as &dyn Value))])
            });
    } else { ; }
};trace!(?valid_discriminants);
811        let discriminants = valid_discriminants.iter().copied();
812        //let next_discriminants = discriminants.clone().cycle().skip(1);
813        let next_discriminants =
814            discriminants.clone().chain(valid_discriminants.first().copied()).skip(1);
815        // Iterate over pairs of each discriminant together with the next one.
816        // Since they were sorted, we can now compute the niche sizes and pick the largest.
817        let discriminants = discriminants.zip(next_discriminants);
818        let largest_niche = discriminants.max_by_key(|&(start, end)| {
819            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:819",
                        "rustc_abi::layout", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(819u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
                        ::tracing_core::field::FieldSet::new(&["start", "end"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&start) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&end) as
                                            &dyn Value))])
            });
    } else { ; }
};trace!(?start, ?end);
820            // If this is a wraparound range, the niche size is `MAX - abs(diff)`, as the diff between
821            // the two end points is actually the size of the valid discriminants.
822            let dist = if start > end {
823                // Overflow can happen for 128 bit discriminants if `end` is negative.
824                // But in that case casting to `u128` still gets us the right value,
825                // as the distance must be positive if the lhs of the subtraction is larger than the rhs.
826                let dist = start.wrapping_sub(end);
827                if discr_type.is_signed() {
828                    discr_int.signed_max().wrapping_sub(dist) as u128
829                } else {
830                    discr_int.size().unsigned_int_max() - dist as u128
831                }
832            } else {
833                // Overflow can happen for 128 bit discriminants if `start` is negative.
834                // But in that case casting to `u128` still gets us the right value,
835                // as the distance must be positive if the lhs of the subtraction is larger than the rhs.
836                end.wrapping_sub(start) as u128
837            };
838            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:838",
                        "rustc_abi::layout", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(838u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
                        ::tracing_core::field::FieldSet::new(&["dist"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&dist) as
                                            &dyn Value))])
            });
    } else { ; }
};trace!(?dist);
839            dist
840        });
841        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:841",
                        "rustc_abi::layout", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(841u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout"),
                        ::tracing_core::field::FieldSet::new(&["largest_niche"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&largest_niche)
                                            as &dyn Value))])
            });
    } else { ; }
};trace!(?largest_niche);
842
843        // `max` is the last valid discriminant before the largest niche
844        // `min` is the first valid discriminant after the largest niche
845        let (max, min) = largest_niche
846            // We might have no inhabited variants, so pretend there's at least one.
847            .unwrap_or((0, 0));
848        let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::discr_range_of_repr(tcx, ty, &repr, min, max);
849
850        let mut align = dl.aggregate_align;
851        let mut max_repr_align = repr.align;
852        let mut unadjusted_abi_align = align;
853
854        let mut size = Size::ZERO;
855
856        // We're interested in the smallest alignment, so start large.
857        let mut start_align = Align::from_bytes(256).unwrap();
858        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);
859
860        // repr(C) on an enum tells us to make a (tag, union) layout,
861        // so we need to grow the prefix alignment to be at least
862        // the alignment of the union. (This value is used both for
863        // determining the alignment of the overall enum, and the
864        // determining the alignment of the payload after the tag.)
865        let mut prefix_align = min_ity.align(dl).abi;
866        if repr.c() {
867            for fields in variants {
868                for field in fields {
869                    prefix_align = prefix_align.max(field.align.abi);
870                }
871            }
872        }
873
874        // Create the set of structs that represent each variant.
875        let mut layout_variants = variants
876            .iter_enumerated()
877            .map(|(i, field_layouts)| {
878                let mut st = self.univariant(
879                    field_layouts,
880                    repr,
881                    StructKind::Prefixed(min_ity.size(), prefix_align),
882                )?;
883                st.variants = Variants::Single { index: i };
884                // Find the first field we can't move later
885                // to make room for a larger discriminant.
886                for field_idx in st.fields.index_by_increasing_offset() {
887                    let field = &field_layouts[FieldIdx::new(field_idx)];
888                    if !field.is_1zst() {
889                        start_align = start_align.min(field.align.abi);
890                        break;
891                    }
892                }
893                size = cmp::max(size, st.size);
894                align = align.max(st.align.abi);
895                max_repr_align = max_repr_align.max(st.max_repr_align);
896                unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align);
897                Ok(st)
898            })
899            .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
900
901        // Align the maximum variant size to the largest alignment.
902        size = size.align_to(align);
903
904        // FIXME(oli-obk): deduplicate and harden these checks
905        if size.bytes() >= dl.obj_size_bound() {
906            return Err(LayoutCalculatorError::SizeOverflow);
907        }
908
909        let typeck_ity = Integer::from_attr(dl, repr.discr_type());
910        if typeck_ity < min_ity {
911            // It is a bug if Layout decided on a greater discriminant size than typeck for
912            // some reason at this point (based on values discriminant can take on). Mostly
913            // because this discriminant will be loaded, and then stored into variable of
914            // type calculated by typeck. Consider such case (a bug): typeck decided on
915            // byte-sized discriminant, but layout thinks we need a 16-bit to store all
916            // discriminant values. That would be a bug, because then, in codegen, in order
917            // to store this 16-bit discriminant into 8-bit sized temporary some of the
918            // space necessary to represent would have to be discarded (or layout is wrong
919            // on thinking it needs 16 bits)
920            {
    ::core::panicking::panic_fmt(format_args!("layout decided on a larger discriminant type ({0:?}) than typeck ({1:?})",
            min_ity, typeck_ity));
};panic!(
921                "layout decided on a larger discriminant type ({min_ity:?}) than typeck ({typeck_ity:?})"
922            );
923            // However, it is fine to make discr type however large (as an optimisation)
924            // after this point – we’ll just truncate the value we load in codegen.
925        }
926
927        // Check to see if we should use a different type for the
928        // discriminant. We can safely use a type with the same size
929        // as the alignment of the first field of each variant.
930        // We increase the size of the discriminant to avoid LLVM copying
931        // padding when it doesn't need to. This normally causes unaligned
932        // load/stores and excessive memcpy/memset operations. By using a
933        // bigger integer size, LLVM can be sure about its contents and
934        // won't be so conservative.
935
936        // Use the initial field alignment
937        let mut ity = if repr.c() || repr.int.is_some() {
938            min_ity
939        } else {
940            Integer::for_align(dl, start_align).unwrap_or(min_ity)
941        };
942
943        // If the alignment is not larger than the chosen discriminant size,
944        // don't use the alignment as the final size.
945        if ity <= min_ity {
946            ity = min_ity;
947        } else {
948            // Patch up the variants' first few fields.
949            let old_ity_size = min_ity.size();
950            let new_ity_size = ity.size();
951            for variant in &mut layout_variants {
952                match variant.fields {
953                    FieldsShape::Arbitrary { ref mut offsets, .. } => {
954                        for i in offsets {
955                            if *i <= old_ity_size {
956                                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);
957                                *i = new_ity_size;
958                            }
959                        }
960                        // We might be making the struct larger.
961                        if variant.size <= old_ity_size {
962                            variant.size = new_ity_size;
963                        }
964                    }
965                    FieldsShape::Primitive | FieldsShape::Array { .. } | FieldsShape::Union(..) => {
966                        {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")
967                    }
968                }
969            }
970        }
971
972        let tag_mask = ity.size().unsigned_int_max();
973        let tag = Scalar::Initialized {
974            value: Primitive::Int(ity, signed),
975            valid_range: WrappingRange {
976                start: (min as u128 & tag_mask),
977                end: (max as u128 & tag_mask),
978            },
979        };
980        let mut abi = BackendRepr::Memory { sized: true };
981
982        let uninhabited = layout_variants.iter().all(|v| v.is_uninhabited());
983        if tag.size(dl) == size {
984            // Make sure we only use scalar layout when the enum is entirely its
985            // own tag (i.e. it has no padding nor any non-ZST variant fields).
986            abi = BackendRepr::Scalar(tag);
987        } else {
988            // Try to use a ScalarPair for all tagged enums.
989            // That's possible only if we can find a common primitive type for all variants.
990            let mut common_prim = None;
991            let mut common_prim_initialized_in_all_variants = true;
992            for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
993                let FieldsShape::Arbitrary { ref offsets, .. } = layout_variant.fields else {
994                    {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
};panic!("encountered a non-arbitrary layout during enum layout");
995                };
996                // We skip *all* ZST here and later check if we are good in terms of alignment.
997                // This lets us handle some cases involving aligned ZST.
998                let mut fields = iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst());
999                let (field, offset) = match (fields.next(), fields.next()) {
1000                    (None, None) => {
1001                        common_prim_initialized_in_all_variants = false;
1002                        continue;
1003                    }
1004                    (Some(pair), None) => pair,
1005                    _ => {
1006                        common_prim = None;
1007                        break;
1008                    }
1009                };
1010                let prim = match field.backend_repr {
1011                    BackendRepr::Scalar(scalar) => {
1012                        common_prim_initialized_in_all_variants &=
1013                            #[allow(non_exhaustive_omitted_patterns)] match scalar {
    Scalar::Initialized { .. } => true,
    _ => false,
}matches!(scalar, Scalar::Initialized { .. });
1014                        scalar.primitive()
1015                    }
1016                    _ => {
1017                        common_prim = None;
1018                        break;
1019                    }
1020                };
1021                if let Some((old_prim, common_offset)) = common_prim {
1022                    // All variants must be at the same offset
1023                    if offset != common_offset {
1024                        common_prim = None;
1025                        break;
1026                    }
1027                    // This is pretty conservative. We could go fancier
1028                    // by realising that (u8, u8) could just cohabit with
1029                    // u16 or even u32.
1030                    let new_prim = match (old_prim, prim) {
1031                        // Allow all identical primitives.
1032                        (x, y) if x == y => x,
1033                        // Allow integers of the same size with differing signedness.
1034                        // We arbitrarily choose the signedness of the first variant.
1035                        (p @ Primitive::Int(x, _), Primitive::Int(y, _)) if x == y => p,
1036                        // Allow integers mixed with pointers of the same layout.
1037                        // We must represent this using a pointer, to avoid
1038                        // roundtripping pointers through ptrtoint/inttoptr.
1039                        (p @ Primitive::Pointer(_), i @ Primitive::Int(..))
1040                        | (i @ Primitive::Int(..), p @ Primitive::Pointer(_))
1041                            if p.size(dl) == i.size(dl) && p.align(dl) == i.align(dl) =>
1042                        {
1043                            p
1044                        }
1045                        _ => {
1046                            common_prim = None;
1047                            break;
1048                        }
1049                    };
1050                    // We may be updating the primitive here, for example from int->ptr.
1051                    common_prim = Some((new_prim, common_offset));
1052                } else {
1053                    common_prim = Some((prim, offset));
1054                }
1055            }
1056            if let Some((prim, offset)) = common_prim {
1057                let prim_scalar = if common_prim_initialized_in_all_variants {
1058                    let size = prim.size(dl);
1059                    if !(size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
1060                    Scalar::Initialized { value: prim, valid_range: WrappingRange::full(size) }
1061                } else {
1062                    // Common prim might be uninit.
1063                    Scalar::Union { value: prim }
1064                };
1065                let pair =
1066                    LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, tag, prim_scalar);
1067                let pair_offsets = match pair.fields {
1068                    FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1069                        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)]);
1070                        offsets
1071                    }
1072                    _ => {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout"),
1073                };
1074                if pair_offsets[FieldIdx::new(0)] == Size::ZERO
1075                    && pair_offsets[FieldIdx::new(1)] == *offset
1076                    && align == pair.align.abi
1077                    && size == pair.size
1078                {
1079                    // We can use `ScalarPair` only when it matches our
1080                    // already computed layout (including `#[repr(C)]`).
1081                    abi = pair.backend_repr;
1082                }
1083            }
1084        }
1085
1086        // If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
1087        // variants to ensure they are consistent. This is because a downcast is
1088        // semantically a NOP, and thus should not affect layout.
1089        if #[allow(non_exhaustive_omitted_patterns)] match abi {
    BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..) => true,
    _ => false,
}matches!(abi, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1090            for variant in &mut layout_variants {
1091                // We only do this for variants with fields; the others are not accessed anyway.
1092                // Also do not overwrite any already existing "clever" ABIs.
1093                if variant.fields.count() > 0
1094                    && #[allow(non_exhaustive_omitted_patterns)] match variant.backend_repr {
    BackendRepr::Memory { .. } => true,
    _ => false,
}matches!(variant.backend_repr, BackendRepr::Memory { .. })
1095                {
1096                    variant.backend_repr = abi;
1097                    // Also need to bump up the size and alignment, so that the entire value fits
1098                    // in here.
1099                    variant.size = cmp::max(variant.size, size);
1100                    variant.align.abi = cmp::max(variant.align.abi, align);
1101                }
1102            }
1103        }
1104
1105        let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1106
1107        let combined_seed = layout_variants
1108            .iter()
1109            .map(|v| v.randomization_seed)
1110            .fold(repr.field_shuffle_seed, |acc, seed| acc.wrapping_add(seed));
1111
1112        let tagged_layout = LayoutData {
1113            variants: Variants::Multiple {
1114                tag,
1115                tag_encoding: TagEncoding::Direct,
1116                tag_field: FieldIdx::new(0),
1117                variants: layout_variants,
1118            },
1119            fields: FieldsShape::Arbitrary {
1120                offsets: [Size::ZERO].into(),
1121                in_memory_order: [FieldIdx::new(0)].into(),
1122            },
1123            largest_niche,
1124            uninhabited,
1125            backend_repr: abi,
1126            align: AbiAlign::new(align),
1127            size,
1128            max_repr_align,
1129            unadjusted_abi_align,
1130            randomization_seed: combined_seed,
1131        };
1132
1133        let best_layout = match (tagged_layout, niche_filling_layout) {
1134            (tl, Some(nl)) => {
1135                // Pick the smaller layout; otherwise,
1136                // pick the layout with the larger niche; otherwise,
1137                // pick tagged as it has simpler codegen.
1138                use cmp::Ordering::*;
1139                let niche_size = |l: &LayoutData<FieldIdx, VariantIdx>| {
1140                    l.largest_niche.map_or(0, |n| n.available(dl))
1141                };
1142                match (tl.size.cmp(&nl.size), niche_size(&tl).cmp(&niche_size(&nl))) {
1143                    (Greater, _) => nl,
1144                    (Equal, Less) => nl,
1145                    _ => tl,
1146                }
1147            }
1148            (tl, None) => tl,
1149        };
1150
1151        Ok(best_layout)
1152    }
1153
1154    fn univariant_biased<
1155        'a,
1156        FieldIdx: Idx,
1157        VariantIdx: Idx,
1158        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug + Copy,
1159    >(
1160        &self,
1161        fields: &IndexSlice<FieldIdx, F>,
1162        repr: &ReprOptions,
1163        kind: StructKind,
1164        niche_bias: NicheBias,
1165    ) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F> {
1166        let dl = self.cx.data_layout();
1167        let pack = repr.pack;
1168        let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
1169        let mut max_repr_align = repr.align;
1170        let mut in_memory_order: IndexVec<u32, FieldIdx> = fields.indices().collect();
1171        let optimize_field_order = !repr.inhibit_struct_field_reordering();
1172        let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
1173        let optimizing = &mut in_memory_order.raw[..end];
1174        let fields_excluding_tail = &fields.raw[..end];
1175        // unsizable tail fields are excluded so that we use the same seed for the sized and unsized layouts.
1176        let field_seed = fields_excluding_tail
1177            .iter()
1178            .fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
1179
1180        if optimize_field_order && fields.len() > 1 {
1181            // If `-Z randomize-layout` was enabled for the type definition we can shuffle
1182            // the field ordering to try and catch some code making assumptions about layouts
1183            // we don't guarantee.
1184            if repr.can_randomize_type_layout() && truecfg!(feature = "randomize") {
1185                #[cfg(feature = "randomize")]
1186                {
1187                    use rand::SeedableRng;
1188                    use rand::seq::SliceRandom;
1189                    // `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field
1190                    // ordering.
1191                    let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
1192                        field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
1193                    );
1194
1195                    // Shuffle the ordering of the fields.
1196                    optimizing.shuffle(&mut rng);
1197                }
1198                // Otherwise we just leave things alone and actually optimize the type's fields
1199            } else {
1200                // To allow unsizing `&Foo<Type>` -> `&Foo<dyn Trait>`, the layout of the struct must
1201                // not depend on the layout of the tail.
1202                let max_field_align =
1203                    fields_excluding_tail.iter().map(|f| f.align.bytes()).max().unwrap_or(1);
1204                let largest_niche_size = fields_excluding_tail
1205                    .iter()
1206                    .filter_map(|f| f.largest_niche)
1207                    .map(|n| n.available(dl))
1208                    .max()
1209                    .unwrap_or(0);
1210
1211                // Calculates a sort key to group fields by their alignment or possibly some
1212                // size-derived pseudo-alignment.
1213                let alignment_group_key = |layout: &F| {
1214                    // The two branches here return values that cannot be meaningfully compared with
1215                    // each other. However, we know that consistently for all executions of
1216                    // `alignment_group_key`, one or the other branch will be taken, so this is okay.
1217                    if let Some(pack) = pack {
1218                        // Return the packed alignment in bytes.
1219                        layout.align.abi.min(pack).bytes()
1220                    } else {
1221                        // Returns `log2(effective-align)`. The calculation assumes that size is an
1222                        // integer multiple of align, except for ZSTs.
1223                        let align = layout.align.bytes();
1224                        let size = layout.size.bytes();
1225                        let niche_size = layout.largest_niche.map(|n| n.available(dl)).unwrap_or(0);
1226                        // Group [u8; 4] with align-4 or [u8; 6] with align-2 fields.
1227                        let size_as_align = align.max(size).trailing_zeros();
1228                        let size_as_align = if largest_niche_size > 0 {
1229                            match niche_bias {
1230                                // Given `A(u8, [u8; 16])` and `B(bool, [u8; 16])` we want to bump the
1231                                // array to the front in the first case (for aligned loads) but keep
1232                                // the bool in front in the second case for its niches.
1233                                NicheBias::Start => {
1234                                    max_field_align.trailing_zeros().min(size_as_align)
1235                                }
1236                                // When moving niches towards the end of the struct then for
1237                                // A((u8, u8, u8, bool), (u8, bool, u8)) we want to keep the first tuple
1238                                // in the align-1 group because its bool can be moved closer to the end.
1239                                NicheBias::End if niche_size == largest_niche_size => {
1240                                    align.trailing_zeros()
1241                                }
1242                                NicheBias::End => size_as_align,
1243                            }
1244                        } else {
1245                            size_as_align
1246                        };
1247                        size_as_align as u64
1248                    }
1249                };
1250
1251                match kind {
1252                    StructKind::AlwaysSized | StructKind::MaybeUnsized => {
1253                        // Currently `LayoutData` only exposes a single niche so sorting is usually
1254                        // sufficient to get one niche into the preferred position. If it ever
1255                        // supported multiple niches then a more advanced pick-and-pack approach could
1256                        // provide better results. But even for the single-niche cache it's not
1257                        // optimal. E.g. for A(u32, (bool, u8), u16) it would be possible to move the
1258                        // bool to the front but it would require packing the tuple together with the
1259                        // u16 to build a 4-byte group so that the u32 can be placed after it without
1260                        // padding. This kind of packing can't be achieved by sorting.
1261                        optimizing.sort_by_key(|&x| {
1262                            let f = &fields[x];
1263                            let field_size = f.size.bytes();
1264                            let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1265                            let niche_size_key = match niche_bias {
1266                                // large niche first
1267                                NicheBias::Start => !niche_size,
1268                                // large niche last
1269                                NicheBias::End => niche_size,
1270                            };
1271                            let inner_niche_offset_key = match niche_bias {
1272                                NicheBias::Start => f.largest_niche.map_or(0, |n| n.offset.bytes()),
1273                                NicheBias::End => f.largest_niche.map_or(0, |n| {
1274                                    !(field_size - n.value.size(dl).bytes() - n.offset.bytes())
1275                                }),
1276                            };
1277
1278                            (
1279                                // Then place largest alignments first.
1280                                cmp::Reverse(alignment_group_key(f)),
1281                                // Then prioritize niche placement within alignment group according to
1282                                // `niche_bias_start`.
1283                                niche_size_key,
1284                                // Then among fields with equally-sized niches prefer the ones
1285                                // closer to the start/end of the field.
1286                                inner_niche_offset_key,
1287                            )
1288                        });
1289                    }
1290
1291                    StructKind::Prefixed(..) => {
1292                        // Sort in ascending alignment so that the layout stays optimal
1293                        // regardless of the prefix.
1294                        // And put the largest niche in an alignment group at the end
1295                        // so it can be used as discriminant in jagged enums
1296                        optimizing.sort_by_key(|&x| {
1297                            let f = &fields[x];
1298                            let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
1299                            (alignment_group_key(f), niche_size)
1300                        });
1301                    }
1302                }
1303
1304                // FIXME(Kixiron): We can always shuffle fields within a given alignment class
1305                //                 regardless of the status of `-Z randomize-layout`
1306            }
1307        }
1308        // in_memory_order holds field indices by increasing memory offset.
1309        // That is, if field 5 has offset 0, the first element of in_memory_order is 5.
1310        // We now write field offsets to the corresponding offset slot;
1311        // field 5 with offset 0 puts 0 in offsets[5].
1312        let mut unsized_field = None::<&F>;
1313        let mut offsets = IndexVec::from_elem(Size::ZERO, fields);
1314        let mut offset = Size::ZERO;
1315        let mut largest_niche = None;
1316        let mut largest_niche_available = 0;
1317        if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1318            let prefix_align =
1319                if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
1320            align = align.max(prefix_align);
1321            offset = prefix_size.align_to(prefix_align);
1322        }
1323        for &i in &in_memory_order {
1324            let field = &fields[i];
1325            if let Some(unsized_field) = unsized_field {
1326                return Err(LayoutCalculatorError::UnexpectedUnsized(*unsized_field));
1327            }
1328
1329            if field.is_unsized() {
1330                if let StructKind::MaybeUnsized = kind {
1331                    unsized_field = Some(field);
1332                } else {
1333                    return Err(LayoutCalculatorError::UnexpectedUnsized(*field));
1334                }
1335            }
1336
1337            // Invariant: offset < dl.obj_size_bound() <= 1<<61
1338            let field_align = if let Some(pack) = pack {
1339                field.align.min(AbiAlign::new(pack))
1340            } else {
1341                field.align
1342            };
1343            offset = offset.align_to(field_align.abi);
1344            align = align.max(field_align.abi);
1345            max_repr_align = max_repr_align.max(field.max_repr_align);
1346
1347            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:1347",
                        "rustc_abi::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1347u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("univariant offset: {0:?} field: {1:#?}",
                                                    offset, field) as &dyn Value))])
            });
    } else { ; }
};debug!("univariant offset: {:?} field: {:#?}", offset, field);
1348            offsets[i] = offset;
1349
1350            if let Some(mut niche) = field.largest_niche {
1351                let available = niche.available(dl);
1352                // Pick up larger niches.
1353                let prefer_new_niche = match niche_bias {
1354                    NicheBias::Start => available > largest_niche_available,
1355                    // if there are several niches of the same size then pick the last one
1356                    NicheBias::End => available >= largest_niche_available,
1357                };
1358                if prefer_new_niche {
1359                    largest_niche_available = available;
1360                    niche.offset += offset;
1361                    largest_niche = Some(niche);
1362                }
1363            }
1364
1365            offset =
1366                offset.checked_add(field.size, dl).ok_or(LayoutCalculatorError::SizeOverflow)?;
1367        }
1368
1369        // The unadjusted ABI alignment does not include repr(align), but does include repr(pack).
1370        // See documentation on `LayoutData::unadjusted_abi_align`.
1371        let unadjusted_abi_align = align;
1372        if let Some(repr_align) = repr.align {
1373            align = align.max(repr_align);
1374        }
1375        // `align` must not be modified after this point, or `unadjusted_abi_align` could be inaccurate.
1376        let align = align;
1377
1378        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_abi/src/layout.rs:1378",
                        "rustc_abi::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_abi/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1378u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("univariant min_size: {0:?}",
                                                    offset) as &dyn Value))])
            });
    } else { ; }
};debug!("univariant min_size: {:?}", offset);
1379        let min_size = offset;
1380        let size = min_size.align_to(align);
1381        // FIXME(oli-obk): deduplicate and harden these checks
1382        if size.bytes() >= dl.obj_size_bound() {
1383            return Err(LayoutCalculatorError::SizeOverflow);
1384        }
1385        let mut layout_of_single_non_zst_field = None;
1386        let sized = unsized_field.is_none();
1387        let mut abi = BackendRepr::Memory { sized };
1388
1389        let optimize_abi = !repr.inhibit_newtype_abi_optimization();
1390
1391        // Try to make this a Scalar/ScalarPair.
1392        if sized && size.bytes() > 0 {
1393            // We skip *all* ZST here and later check if we are good in terms of alignment.
1394            // This lets us handle some cases involving aligned ZST.
1395            let mut non_zst_fields = fields.iter_enumerated().filter(|&(_, f)| !f.is_zst());
1396
1397            match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1398                // We have exactly one non-ZST field.
1399                (Some((i, field)), None, None) => {
1400                    layout_of_single_non_zst_field = Some(field);
1401
1402                    // Field fills the struct and it has a scalar or scalar pair ABI.
1403                    if offsets[i].bytes() == 0 && align == field.align.abi && size == field.size {
1404                        match field.backend_repr {
1405                            // For plain scalars, or vectors of them, we can't unpack
1406                            // newtypes for `#[repr(C)]`, as that affects C ABIs.
1407                            BackendRepr::Scalar(_) | BackendRepr::SimdVector { .. }
1408                                if optimize_abi =>
1409                            {
1410                                abi = field.backend_repr;
1411                            }
1412                            // But scalar pairs are Rust-specific and get
1413                            // treated as aggregates by C ABIs anyway.
1414                            BackendRepr::ScalarPair(..) => {
1415                                abi = field.backend_repr;
1416                            }
1417                            _ => {}
1418                        }
1419                    }
1420                }
1421
1422                // Two non-ZST fields, and they're both scalars.
1423                (Some((i, a)), Some((j, b)), None) => {
1424                    match (a.backend_repr, b.backend_repr) {
1425                        (BackendRepr::Scalar(a), BackendRepr::Scalar(b)) => {
1426                            // Order by the memory placement, not source order.
1427                            let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1428                                ((i, a), (j, b))
1429                            } else {
1430                                ((j, b), (i, a))
1431                            };
1432                            let pair =
1433                                LayoutData::<FieldIdx, VariantIdx>::scalar_pair(&self.cx, a, b);
1434                            let pair_offsets = match pair.fields {
1435                                FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
1436                                    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!(
1437                                        in_memory_order.raw,
1438                                        [FieldIdx::new(0), FieldIdx::new(1)]
1439                                    );
1440                                    offsets
1441                                }
1442                                FieldsShape::Primitive
1443                                | FieldsShape::Array { .. }
1444                                | FieldsShape::Union(..) => {
1445                                    {
    ::core::panicking::panic_fmt(format_args!("encountered a non-arbitrary layout during enum layout"));
}panic!("encountered a non-arbitrary layout during enum layout")
1446                                }
1447                            };
1448                            if offsets[i] == pair_offsets[FieldIdx::new(0)]
1449                                && offsets[j] == pair_offsets[FieldIdx::new(1)]
1450                                && align == pair.align.abi
1451                                && size == pair.size
1452                            {
1453                                // We can use `ScalarPair` only when it matches our
1454                                // already computed layout (including `#[repr(C)]`).
1455                                abi = pair.backend_repr;
1456                            }
1457                        }
1458                        _ => {}
1459                    }
1460                }
1461
1462                _ => {}
1463            }
1464        }
1465        let uninhabited = fields.iter().any(|f| f.is_uninhabited());
1466
1467        let unadjusted_abi_align = if repr.transparent() {
1468            match layout_of_single_non_zst_field {
1469                Some(l) => l.unadjusted_abi_align,
1470                None => {
1471                    // `repr(transparent)` with all ZST fields.
1472                    align
1473                }
1474            }
1475        } else {
1476            unadjusted_abi_align
1477        };
1478
1479        let seed = field_seed.wrapping_add(repr.field_shuffle_seed);
1480
1481        Ok(LayoutData {
1482            variants: Variants::Single { index: VariantIdx::new(0) },
1483            fields: FieldsShape::Arbitrary { offsets, in_memory_order },
1484            backend_repr: abi,
1485            largest_niche,
1486            uninhabited,
1487            align: AbiAlign::new(align),
1488            size,
1489            max_repr_align,
1490            unadjusted_abi_align,
1491            randomization_seed: seed,
1492        })
1493    }
1494
1495    fn format_field_niches<
1496        'a,
1497        FieldIdx: Idx,
1498        VariantIdx: Idx,
1499        F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1500    >(
1501        &self,
1502        layout: &LayoutData<FieldIdx, VariantIdx>,
1503        fields: &IndexSlice<FieldIdx, F>,
1504    ) -> String {
1505        let dl = self.cx.data_layout();
1506        let mut s = String::new();
1507        for i in layout.fields.index_by_increasing_offset() {
1508            let offset = layout.fields.offset(i);
1509            let f = &fields[FieldIdx::new(i)];
1510            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();
1511            if let Some(n) = f.largest_niche {
1512                s.write_fmt(format_args!(" n{0}b{1}s{2}", n.offset.bytes(),
        n.available(dl).ilog2(), n.value.size(dl).bytes()))write!(
1513                    s,
1514                    " n{}b{}s{}",
1515                    n.offset.bytes(),
1516                    n.available(dl).ilog2(),
1517                    n.value.size(dl).bytes()
1518                )
1519                .unwrap();
1520            }
1521            s.write_fmt(format_args!("] "))write!(s, "] ").unwrap();
1522        }
1523        s
1524    }
1525}
1526
1527enum VectorKind {
1528    /// `#[rustc_scalable_vector]`
1529    Scalable,
1530    /// `#[repr(simd, packed)]`
1531    PackedFixed,
1532    /// `#[repr(simd)]`
1533    Fixed,
1534}
1535
1536fn vector_type_layout<FieldIdx, VariantIdx, F>(
1537    kind: VectorKind,
1538    dl: &TargetDataLayout,
1539    element: F,
1540    count: u64,
1541) -> LayoutCalculatorResult<FieldIdx, VariantIdx, F>
1542where
1543    FieldIdx: Idx,
1544    VariantIdx: Idx,
1545    F: AsRef<LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
1546{
1547    let elt = element.as_ref();
1548    if count == 0 {
1549        return Err(LayoutCalculatorError::ZeroLengthSimdType);
1550    } else if count > crate::MAX_SIMD_LANES {
1551        return Err(LayoutCalculatorError::OversizedSimdType { max_lanes: crate::MAX_SIMD_LANES });
1552    }
1553
1554    let BackendRepr::Scalar(element) = elt.backend_repr else {
1555        return Err(LayoutCalculatorError::NonPrimitiveSimdType(element));
1556    };
1557
1558    // Compute the size and alignment of the vector
1559    let size =
1560        elt.size.checked_mul(count, dl).ok_or_else(|| LayoutCalculatorError::SizeOverflow)?;
1561    let (repr, align) = match kind {
1562        VectorKind::Scalable => {
1563            (BackendRepr::ScalableVector { element, count }, dl.llvmlike_vector_align(size))
1564        }
1565        // Non-power-of-two vectors have padding up to the next power-of-two.
1566        // If we're a packed repr, remove the padding while keeping the alignment as close
1567        // to a vector as possible.
1568        VectorKind::PackedFixed if !count.is_power_of_two() => {
1569            (BackendRepr::Memory { sized: true }, Align::max_aligned_factor(size))
1570        }
1571        VectorKind::PackedFixed | VectorKind::Fixed => {
1572            (BackendRepr::SimdVector { element, count }, dl.llvmlike_vector_align(size))
1573        }
1574    };
1575    let size = size.align_to(align);
1576
1577    Ok(LayoutData {
1578        variants: Variants::Single { index: VariantIdx::new(0) },
1579        fields: FieldsShape::Arbitrary {
1580            offsets: [Size::ZERO].into(),
1581            in_memory_order: [FieldIdx::new(0)].into(),
1582        },
1583        backend_repr: repr,
1584        largest_niche: elt.largest_niche,
1585        uninhabited: false,
1586        size,
1587        align: AbiAlign::new(align),
1588        max_repr_align: None,
1589        unadjusted_abi_align: elt.align.abi,
1590        randomization_seed: elt.randomization_seed.wrapping_add(Hash64::new(count)),
1591    })
1592}