Skip to main content

rustc_abi/
layout.rs

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