Skip to main content

rustc_ty_utils/
layout.rs

1use std::range::{RangeFrom, RangeToInclusive};
2
3use rustc_abi::Integer::{I8, I32};
4use rustc_abi::Primitive::{self, Float, Int, Pointer};
5use rustc_abi::{
6    self as abi, AddressSpace, BackendRepr, FIRST_VARIANT, FieldIdx, FieldsShape, HasDataLayout,
7    Layout, LayoutCalculatorError, LayoutData, Niche, NicheOptimizations, ReprOptions, Scalar,
8    Size, StructKind, TagEncoding, VariantIdx, Variants, WrappingRange,
9};
10use rustc_attr_ir::find_attr;
11use rustc_attr_ir::lang_items::LangItem;
12use rustc_hashes::Hash64;
13use rustc_hir::def_id::DefId;
14use rustc_index::{Idx as _, IndexVec};
15use rustc_middle::query::Providers;
16use rustc_middle::traits::ObligationCause;
17use rustc_middle::ty::layout::{
18    FloatExt, HasTyCtxt, IntegerExt, LayoutCx, LayoutError, LayoutOf, SimdLayoutError, TyAndLayout,
19};
20use rustc_middle::ty::print::with_no_trimmed_paths;
21use rustc_middle::ty::{
22    self, AdtDef, CoroutineArgsExt, EarlyBinder, PseudoCanonicalInput, Ty, TyCtxt,
23    TypeVisitableExt, Unnormalized,
24};
25use rustc_session::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
26use rustc_span::{Symbol, bug, sym};
27use rustc_structures::Limit;
28use rustc_target::spec::{Arch, HasTargetSpec};
29use tracing::{debug, instrument};
30
31use crate::diagnostics::NonPrimitiveSimdType;
32
33mod invariant;
34
35pub(crate) fn provide(providers: &mut Providers) {
36    *providers = Providers { layout_of, ..*providers };
37}
38
39{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("layout_of",
                                    "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(39u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let PseudoCanonicalInput { typing_env, value: original_ty } =
                query;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:45",
                                    "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                                    ::tracing_core::__macro_support::Option::Some(45u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::layout"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("original_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("original_ty");
                                                        NAME.as_str()
                                                    }], ::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(&::tracing::field::debug(&original_ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let PseudoCanonicalInput { typing_env, value: unnormalized_ty } =
                typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(tcx,
                    original_ty);
            let unnormalized_ty = ty::Unnormalized::new_wip(unnormalized_ty);
            let normalized_ty =
                match tcx.try_normalize_erasing_regions(typing_env,
                        unnormalized_ty) {
                    Ok(t) => t,
                    Err(normalization_error) => {
                        return Err(tcx.arena.alloc(LayoutError::NormalizationFailure(unnormalized_ty.skip_normalization(),
                                        normalization_error)));
                    }
                };
            if normalized_ty != original_ty {
                return tcx.layout_of(typing_env.as_query_input(normalized_ty));
            }
            match typing_env.typing_mode() {
                ty::TypingMode::Codegen => {
                    let with_postanalysis =
                        ty::TypingEnv::new(typing_env.param_env,
                            ty::TypingMode::PostAnalysis);
                    let res =
                        tcx.layout_of(with_postanalysis.as_query_input(normalized_ty));
                    match res {
                        Err(LayoutError::TooGeneric(_)) => {}
                        _ => return res,
                    };
                }
                ty::TypingMode::Coherence | ty::TypingMode::Typeck { .. } |
                    ty::TypingMode::PostTypeckThroughBorrowck { .. } |
                    ty::TypingMode::PostBorrowck { .. } |
                    ty::TypingMode::Reflection |
                    ty::TypingMode::ErasedNotCoherence(_) |
                    ty::TypingMode::PostAnalysis => {}
            }
            let cx = LayoutCx::new(tcx, typing_env);
            let layout = layout_of_uncached(&cx, normalized_ty)?;
            let layout = TyAndLayout { ty: normalized_ty, layout };
            if cx.tcx().sess.opts.unstable_opts.print_type_sizes {
                record_layout_for_printing(&cx, layout);
            }
            invariant::layout_sanity_check(&cx, &layout);
            Ok(layout)
        }
    }
}#[instrument(skip(tcx, query), level = "debug")]
40fn layout_of<'tcx>(
41    tcx: TyCtxt<'tcx>,
42    query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
43) -> Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>> {
44    let PseudoCanonicalInput { typing_env, value: original_ty } = query;
45    debug!(?original_ty);
46
47    // Optimization: We convert to TypingMode::PostAnalysis and convert opaque types in
48    // the where bounds to their hidden types. This reduces overall uncached invocations
49    // of `layout_of` and is thus a small performance improvement.
50    //
51    // Switching to `PostAnalysis` typing mode will reveal opaque types that's marked
52    // as rigid in the original typing env.
53    let PseudoCanonicalInput { typing_env, value: unnormalized_ty } =
54        typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(tcx, original_ty);
55    let unnormalized_ty = ty::Unnormalized::new_wip(unnormalized_ty);
56
57    // FIXME: We might want to have two different versions of `layout_of`:
58    // One that can be called after typecheck has completed and can use
59    // `normalize_erasing_regions` here and another one that can be called
60    // before typecheck has completed and uses `try_normalize_erasing_regions`.
61    let normalized_ty = match tcx.try_normalize_erasing_regions(typing_env, unnormalized_ty) {
62        Ok(t) => t,
63        Err(normalization_error) => {
64            return Err(tcx.arena.alloc(LayoutError::NormalizationFailure(
65                unnormalized_ty.skip_normalization(),
66                normalization_error,
67            )));
68        }
69    };
70
71    if normalized_ty != original_ty {
72        // Ensure this layout is also cached for the normalized type.
73        return tcx.layout_of(typing_env.as_query_input(normalized_ty));
74    }
75
76    match typing_env.typing_mode() {
77        ty::TypingMode::Codegen => {
78            let with_postanalysis =
79                ty::TypingEnv::new(typing_env.param_env, ty::TypingMode::PostAnalysis);
80            let res = tcx.layout_of(with_postanalysis.as_query_input(normalized_ty));
81            match res {
82                Err(LayoutError::TooGeneric(_)) => {}
83                _ => return res,
84            };
85        }
86        ty::TypingMode::Coherence
87        | ty::TypingMode::Typeck { .. }
88        | ty::TypingMode::PostTypeckThroughBorrowck { .. }
89        | ty::TypingMode::PostBorrowck { .. }
90        | ty::TypingMode::Reflection
91        | ty::TypingMode::ErasedNotCoherence(_)
92        | ty::TypingMode::PostAnalysis => {}
93    }
94
95    let cx = LayoutCx::new(tcx, typing_env);
96
97    let layout = layout_of_uncached(&cx, normalized_ty)?;
98    let layout = TyAndLayout { ty: normalized_ty, layout };
99
100    // If we are running with `-Zprint-type-sizes`, maybe record layouts
101    // for dumping later.
102    if cx.tcx().sess.opts.unstable_opts.print_type_sizes {
103        record_layout_for_printing(&cx, layout);
104    }
105
106    invariant::layout_sanity_check(&cx, &layout);
107
108    Ok(layout)
109}
110
111fn error<'tcx>(cx: &LayoutCx<'tcx>, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
112    cx.tcx().arena.alloc(err)
113}
114
115fn map_error<'tcx>(
116    cx: &LayoutCx<'tcx>,
117    ty: Ty<'tcx>,
118    err: LayoutCalculatorError<TyAndLayout<'tcx>>,
119) -> &'tcx LayoutError<'tcx> {
120    let err = match err {
121        LayoutCalculatorError::SizeOverflow => {
122            // This is sometimes not a compile error in `check` builds.
123            // See `tests/ui/limits/huge-enum.rs` for an example.
124            LayoutError::SizeOverflow(ty)
125        }
126        LayoutCalculatorError::UnexpectedUnsized(field) => {
127            // This is sometimes not a compile error if there are trivially false where clauses.
128            // See `tests/ui/layout/trivial-bounds-sized.rs` for an example.
129            if !field.layout.is_unsized() {
    {
        ::core::panicking::panic_fmt(format_args!("invalid layout error {0:#?}",
                err));
    }
};assert!(field.layout.is_unsized(), "invalid layout error {err:#?}");
130            if cx.typing_env.param_env.is_empty() {
131                cx.tcx().dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("encountered unexpected unsized field in layout of {0:?}: {1:#?}",
                ty, field))
    })format!(
132                    "encountered unexpected unsized field in layout of {ty:?}: {field:#?}"
133                ));
134            }
135            LayoutError::Unknown(ty)
136        }
137        LayoutCalculatorError::EmptyUnion => {
138            // This is always a compile error.
139            let guar =
140                cx.tcx().dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("computed layout of empty union: {0:?}",
                ty))
    })format!("computed layout of empty union: {ty:?}"));
141            LayoutError::ReferencesError(guar)
142        }
143        LayoutCalculatorError::ReprConflict => {
144            // packed enums are the only known trigger of this, but others might arise
145            let guar = cx
146                .tcx()
147                .dcx()
148                .delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("computed impossible repr (packed enum?): {0:?}",
                ty))
    })format!("computed impossible repr (packed enum?): {ty:?}"));
149            LayoutError::ReferencesError(guar)
150        }
151        LayoutCalculatorError::ZeroLengthSimdType => {
152            // Can't be caught in typeck if the array length is generic.
153            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength }
154        }
155        LayoutCalculatorError::OversizedSimdType { max_lanes } => {
156            // Can't be caught in typeck if the array length is generic.
157            LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(Limit(max_lanes)) }
158        }
159        LayoutCalculatorError::NonPrimitiveSimdType(field) => {
160            // This error isn't caught in typeck, e.g., if
161            // the element type of the vector is generic.
162            cx.tcx().dcx().emit_fatal(NonPrimitiveSimdType { ty, e_ty: field.ty })
163        }
164    };
165    error(cx, err)
166}
167
168fn extract_const_value<'tcx>(
169    cx: &LayoutCx<'tcx>,
170    ty: Ty<'tcx>,
171    ct: ty::Const<'tcx>,
172) -> Result<ty::Value<'tcx>, &'tcx LayoutError<'tcx>> {
173    match ct.kind() {
174        ty::ConstKind::Value(cv) => Ok(cv),
175        ty::ConstKind::Param(_) | ty::ConstKind::Expr(_) => {
176            if !ct.has_param() {
177                ::rustc_span::macros::bug_impl(None,
    format_args!("failed to normalize const, but it is not generic: {0:?}",
        ct), Location::caller());bug!("failed to normalize const, but it is not generic: {ct:?}");
178            }
179            Err(error(cx, LayoutError::TooGeneric(ty)))
180        }
181        ty::ConstKind::Alias(_, _) => {
182            let err = if ct.has_param() {
183                LayoutError::TooGeneric(ty)
184            } else {
185                // This case is reachable with unsatisfiable predicates and GCE (which will
186                // cause anon consts to inherit the unsatisfiable predicates). For example
187                // if we have an unsatisfiable `u8: Trait` bound, then it's not a compile
188                // error to mention `[u8; <u8 as Trait>::CONST]`, but we can't compute its
189                // layout.
190                LayoutError::Unknown(ty)
191            };
192            Err(error(cx, err))
193        }
194        ty::ConstKind::Infer(_)
195        | ty::ConstKind::Bound(..)
196        | ty::ConstKind::Placeholder(_)
197        | ty::ConstKind::Error(_) => {
198            // `ty::ConstKind::Error` is handled at the top of `layout_of_uncached`
199            // (via `ty.error_reported()`).
200            ::rustc_span::macros::bug_impl(None,
    format_args!("layout_of: unexpected const: {0:?}", ct),
    Location::caller());bug!("layout_of: unexpected const: {ct:?}");
201        }
202    }
203}
204
205fn layout_of_uncached<'tcx>(
206    cx: &LayoutCx<'tcx>,
207    ty: Ty<'tcx>,
208) -> Result<Layout<'tcx>, &'tcx LayoutError<'tcx>> {
209    // Types that reference `ty::Error` pessimistically don't have a meaningful layout.
210    // The only side-effect of this is possibly worse diagnostics in case the layout
211    // was actually computable (like if the `ty::Error` showed up only in a `PhantomData`).
212    if let Err(guar) = ty.error_reported() {
213        return Err(error(cx, LayoutError::ReferencesError(guar)));
214    }
215
216    let tcx = cx.tcx();
217
218    // layout of `async_drop_in_place<T>::{closure}` in case,
219    // when T is a coroutine, contains this internal coroutine's ref
220
221    let dl = cx.data_layout();
222    let map_layout = |result: Result<_, _>| match result {
223        Ok(layout) => Ok(tcx.mk_layout(layout)),
224        Err(err) => Err(map_error(cx, ty, err)),
225    };
226    let scalar_unit = |value: Primitive| {
227        let size = value.size(dl);
228        if !(size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: size.bits() <= 128")
};assert!(size.bits() <= 128);
229        Scalar::Initialized { value, valid_range: WrappingRange::full(size) }
230    };
231    let scalar = |value: Primitive| tcx.mk_layout(LayoutData::scalar(cx, scalar_unit(value)));
232
233    let univariant = |tys: &[Ty<'tcx>], kind| {
234        let fields = tys.iter().map(|ty| cx.layout_of(*ty)).try_collect::<IndexVec<_, _>>()?;
235        let repr = ReprOptions::default();
236        map_layout(cx.calc.layout_of_univariant(&fields, &repr, kind))
237    };
238    if true {
    if !!ty.has_non_region_infer() {
        ::core::panicking::panic("assertion failed: !ty.has_non_region_infer()")
    };
};debug_assert!(!ty.has_non_region_infer());
239
240    Ok(match *ty.kind() {
241        ty::Pat(ty, pat) => {
242            let layout = cx.layout_of(ty)?.layout;
243            let mut layout = LayoutData::clone(&layout.0);
244            match *pat {
245                ty::PatternKind::Range { start, end } => {
246                    if let BackendRepr::Scalar(scalar) = &mut layout.backend_repr {
247                        scalar.valid_range_mut().start = extract_const_value(cx, ty, start)?
248                            .try_to_bits(tcx, cx.typing_env)
249                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
250
251                        scalar.valid_range_mut().end = extract_const_value(cx, ty, end)?
252                            .try_to_bits(tcx, cx.typing_env)
253                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
254
255                        // FIXME(pattern_types): create implied bounds from pattern types in signatures
256                        // that require that the range end is >= the range start so that we can't hit
257                        // this error anymore without first having hit a trait solver error.
258                        // Very fuzzy on the details here, but pattern types are an internal impl detail,
259                        // so we can just go with this for now
260                        if scalar.is_signed() {
261                            let range = scalar.valid_range_mut();
262                            let start = layout.size.sign_extend(range.start);
263                            let end = layout.size.sign_extend(range.end);
264                            if end < start {
265                                let guar = tcx.dcx().err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pattern type ranges cannot wrap: {0}..={1}",
                start, end))
    })format!(
266                                    "pattern type ranges cannot wrap: {start}..={end}"
267                                ));
268
269                                return Err(error(cx, LayoutError::ReferencesError(guar)));
270                            }
271                        } else {
272                            let range = scalar.valid_range_mut();
273                            if range.end < range.start {
274                                let guar = tcx.dcx().err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pattern type ranges cannot wrap: {0}..={1}",
                range.start, range.end))
    })format!(
275                                    "pattern type ranges cannot wrap: {}..={}",
276                                    range.start, range.end
277                                ));
278
279                                return Err(error(cx, LayoutError::ReferencesError(guar)));
280                            }
281                        };
282
283                        let niche = Niche {
284                            offset: Size::ZERO,
285                            value: scalar.primitive(),
286                            valid_range: scalar.valid_range(cx),
287                        };
288
289                        layout.largest_niche = Some(niche);
290                    } else {
291                        ::rustc_span::macros::bug_impl(None,
    format_args!("pattern type with range but not scalar layout: {0:?}, {1:?}",
        ty, layout), Location::caller())bug!("pattern type with range but not scalar layout: {ty:?}, {layout:?}")
292                    }
293                }
294                ty::PatternKind::NotNull => {
295                    if let BackendRepr::Scalar(scalar)
296                    | BackendRepr::ScalarPair { a: scalar, b: _, b_offset: _ } =
297                        &mut layout.backend_repr
298                    {
299                        scalar.valid_range_mut().start = 1;
300                        let niche = Niche {
301                            offset: Size::ZERO,
302                            value: scalar.primitive(),
303                            valid_range: scalar.valid_range(cx),
304                        };
305
306                        layout.largest_niche = Some(niche);
307                    } else {
308                        ::rustc_span::macros::bug_impl(None,
    format_args!("pattern type with `!null` pattern but not scalar/pair layout: {0:?}, {1:?}",
        ty, layout), Location::caller())bug!(
309                            "pattern type with `!null` pattern but not scalar/pair layout: {ty:?}, {layout:?}"
310                        )
311                    }
312                }
313
314                ty::PatternKind::Or(variants) => match *variants[0] {
315                    ty::PatternKind::Range { .. } => {
316                        if let BackendRepr::Scalar(scalar) = &mut layout.backend_repr {
317                            let variants: Result<Vec<_>, _> = variants
318                                .iter()
319                                .map(|pat| match *pat {
320                                    ty::PatternKind::Range { start, end } => Ok((
321                                        extract_const_value(cx, ty, start)
322                                            .unwrap()
323                                            .try_to_bits(tcx, cx.typing_env)
324                                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?,
325                                        extract_const_value(cx, ty, end)
326                                            .unwrap()
327                                            .try_to_bits(tcx, cx.typing_env)
328                                            .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?,
329                                    )),
330                                    ty::PatternKind::NotNull | ty::PatternKind::Or(_) => {
331                                        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("mixed or patterns are not allowed")));
}unreachable!("mixed or patterns are not allowed")
332                                    }
333                                })
334                                .collect();
335                            let mut variants = variants?;
336                            if !scalar.is_signed() {
337                                let guar = tcx.dcx().err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only signed integer base types are allowed for or-pattern pattern types at present"))
    })format!(
338                                    "only signed integer base types are allowed for or-pattern pattern types at present"
339                                ));
340
341                                return Err(error(cx, LayoutError::ReferencesError(guar)));
342                            }
343                            variants.sort();
344                            if variants.len() != 2 {
345                                let guar = tcx
346                                .dcx()
347                                .err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the only or-pattern types allowed are two range patterns that are directly connected at their overflow site"))
    })format!("the only or-pattern types allowed are two range patterns that are directly connected at their overflow site"));
348
349                                return Err(error(cx, LayoutError::ReferencesError(guar)));
350                            }
351
352                            // first is the one starting at the signed in range min
353                            let mut first = variants[0];
354                            let mut second = variants[1];
355                            if second.0
356                                == layout.size.truncate(layout.size.signed_int_min() as u128)
357                            {
358                                (second, first) = (first, second);
359                            }
360
361                            if layout.size.sign_extend(first.1) >= layout.size.sign_extend(second.0)
362                            {
363                                let guar = tcx.dcx().err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only non-overlapping pattern type ranges are allowed at present"))
    })format!(
364                                    "only non-overlapping pattern type ranges are allowed at present"
365                                ));
366
367                                return Err(error(cx, LayoutError::ReferencesError(guar)));
368                            }
369                            if layout.size.signed_int_max() as u128 != second.1 {
370                                let guar = tcx.dcx().err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("one pattern needs to end at `{1}::MAX`, but was {0} instead",
                second.1, ty))
    })format!(
371                                    "one pattern needs to end at `{ty}::MAX`, but was {} instead",
372                                    second.1
373                                ));
374
375                                return Err(error(cx, LayoutError::ReferencesError(guar)));
376                            }
377
378                            // Now generate a wrapping range (which aren't allowed in surface syntax).
379                            scalar.valid_range_mut().start = second.0;
380                            scalar.valid_range_mut().end = first.1;
381
382                            let niche = Niche {
383                                offset: Size::ZERO,
384                                value: scalar.primitive(),
385                                valid_range: scalar.valid_range(cx),
386                            };
387
388                            layout.largest_niche = Some(niche);
389                        } else {
390                            ::rustc_span::macros::bug_impl(None,
    format_args!("pattern type with range but not scalar layout: {0:?}, {1:?}",
        ty, layout), Location::caller())bug!(
391                                "pattern type with range but not scalar layout: {ty:?}, {layout:?}"
392                            )
393                        }
394                    }
395                    ty::PatternKind::NotNull => ::rustc_span::macros::bug_impl(None,
    format_args!("or patterns can\'t contain `!null` patterns"),
    Location::caller())bug!("or patterns can't contain `!null` patterns"),
396                    ty::PatternKind::Or(..) => ::rustc_span::macros::bug_impl(None,
    format_args!("patterns cannot have nested or patterns"),
    Location::caller())bug!("patterns cannot have nested or patterns"),
397                },
398            }
399            // Pattern types contain their base as their sole field.
400            // This allows the rest of the compiler to process pattern types just like
401            // single field transparent Adts, and only the parts of the compiler that
402            // specifically care about pattern types will have to handle it.
403            layout.fields = FieldsShape::Arbitrary {
404                offsets: [Size::ZERO].into_iter().collect(),
405                in_memory_order: [FieldIdx::new(0)].into_iter().collect(),
406            };
407            tcx.mk_layout(layout)
408        }
409
410        // Basic scalars.
411        ty::Bool => tcx.mk_layout(LayoutData::scalar(
412            cx,
413            Scalar::Initialized {
414                value: Int(I8, false),
415                valid_range: WrappingRange { start: 0, end: 1 },
416            },
417        )),
418        ty::Char => tcx.mk_layout(LayoutData::scalar(
419            cx,
420            Scalar::Initialized {
421                value: Int(I32, false),
422                valid_range: WrappingRange { start: 0, end: 0x10FFFF },
423            },
424        )),
425        ty::Int(ity) => scalar(Int(abi::Integer::from_int_ty(dl, ity), true)),
426        ty::Uint(ity) => scalar(Int(abi::Integer::from_uint_ty(dl, ity), false)),
427        ty::Float(fty) => scalar(Float(abi::Float::from_float_ty(fty))),
428        ty::FnPtr(..) => {
429            let mut ptr = scalar_unit(Pointer(dl.instruction_address_space));
430            ptr.valid_range_mut().start = 1;
431            tcx.mk_layout(LayoutData::scalar(cx, ptr))
432        }
433
434        // The never type.
435        ty::Never => tcx.mk_layout(LayoutData::never_type()),
436
437        // Potentially-wide pointers.
438        ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
439            let mut data_ptr = scalar_unit(Pointer(AddressSpace::ZERO));
440            if !ty.is_raw_ptr() {
441                data_ptr.valid_range_mut().start = 1;
442            }
443
444            if pointee.is_sized(tcx, cx.typing_env) {
445                return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr)));
446            }
447
448            let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type() {
449                let pointee_metadata =
450                    Ty::new_projection(tcx, ty::IsRigid::No, metadata_def_id, [pointee]);
451                let metadata_ty = match tcx.try_normalize_erasing_regions(
452                    cx.typing_env,
453                    Unnormalized::new_wip(pointee_metadata),
454                ) {
455                    Ok(metadata_ty) => metadata_ty,
456                    Err(mut err) => {
457                        // Usually `<Ty as Pointee>::Metadata` can't be normalized because
458                        // its struct tail cannot be normalized either, so try to get a
459                        // more descriptive layout error here, which will lead to less confusing
460                        // diagnostics.
461                        //
462                        // We use the raw struct tail function here to get the first tail
463                        // that is an alias, which is likely the cause of the normalization
464                        // error.
465                        match tcx.try_normalize_erasing_regions(
466                            cx.typing_env,
467                            Unnormalized::new_wip(tcx.struct_tail_raw(
468                                pointee,
469                                &ObligationCause::dummy(),
470                                |ty| ty.skip_norm_wip(),
471                                || {},
472                            )),
473                        ) {
474                            Ok(_) => {}
475                            Err(better_err) => {
476                                err = better_err;
477                            }
478                        }
479                        return Err(error(cx, LayoutError::NormalizationFailure(pointee, err)));
480                    }
481                };
482
483                let metadata_layout = cx.layout_of(metadata_ty)?;
484                // If the metadata is a 1-zst, then the pointer is thin.
485                if metadata_layout.is_1zst() {
486                    return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr)));
487                }
488
489                let BackendRepr::Scalar(metadata) = metadata_layout.backend_repr else {
490                    return Err(error(cx, LayoutError::Unknown(pointee)));
491                };
492
493                metadata
494            } else {
495                let unsized_part = tcx.struct_tail_for_codegen(pointee, cx.typing_env);
496
497                match unsized_part.kind() {
498                    ty::Foreign(..) => {
499                        return Ok(tcx.mk_layout(LayoutData::scalar(cx, data_ptr)));
500                    }
501                    ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)),
502                    ty::Dynamic(..) => {
503                        let mut vtable = scalar_unit(Pointer(AddressSpace::ZERO));
504                        vtable.valid_range_mut().start = 1;
505                        vtable
506                    }
507                    _ => {
508                        return Err(error(cx, LayoutError::Unknown(pointee)));
509                    }
510                }
511            };
512
513            // Effectively a (ptr, meta) tuple.
514            tcx.mk_layout(LayoutData::scalar_pair(cx, data_ptr, metadata))
515        }
516
517        // Arrays and slices.
518        ty::Array(element, count) => {
519            let count = extract_const_value(cx, ty, count)?
520                .try_to_target_usize(tcx)
521                .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
522
523            let element = cx.layout_of(element)?;
524            map_layout(cx.calc.layout_of_array_like(&element, Some(count)))?
525        }
526        ty::Slice(element) => {
527            let element = cx.layout_of(element)?;
528            map_layout(cx.calc.layout_of_array_like(&element, None).map(|mut layout| {
529                // a randomly chosen value to distinguish slices
530                layout.randomization_seed = Hash64::new(0x2dcba99c39784102);
531                layout
532            }))?
533        }
534        ty::Str => {
535            let element = scalar(Int(I8, false));
536            map_layout(cx.calc.layout_of_array_like(&element, None).map(|mut layout| {
537                // another random value
538                layout.randomization_seed = Hash64::new(0xc1325f37d127be22);
539                layout
540            }))?
541        }
542
543        // Odd unit types.
544        ty::FnDef(..) | ty::Dynamic(_, _) | ty::Foreign(..) => {
545            let sized = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::FnDef(..) => true,
    _ => false,
}matches!(ty.kind(), ty::FnDef(..));
546            tcx.mk_layout(LayoutData::unit(sized))
547        }
548
549        ty::Coroutine(def_id, args) => {
550            match cx.typing_env.typing_mode() {
551                ty::TypingMode::Codegen => {}
552                ty::TypingMode::Coherence
553                | ty::TypingMode::Typeck { .. }
554                | ty::TypingMode::PostTypeckThroughBorrowck { .. }
555                | ty::TypingMode::PostBorrowck { .. }
556                | ty::TypingMode::Reflection
557                | ty::TypingMode::ErasedNotCoherence(_)
558                | ty::TypingMode::PostAnalysis => {
559                    return Err(error(cx, LayoutError::TooGeneric(ty)));
560                }
561            }
562
563            use rustc_middle::ty::layout::PrimitiveExt as _;
564
565            let info = tcx.coroutine_layout(def_id, args)?;
566
567            let local_layouts = info
568                .field_tys
569                .iter()
570                .map(|local| {
571                    let field_ty = EarlyBinder::bind(tcx, local.ty);
572                    let uninit_ty =
573                        Ty::new_maybe_uninit(tcx, field_ty.instantiate(tcx, args).skip_norm_wip());
574                    cx.spanned_layout_of(uninit_ty, local.source_info.span)
575                })
576                .try_collect::<IndexVec<_, _>>()?;
577
578            let prefix_layouts = args
579                .as_coroutine()
580                .upvar_tys()
581                .iter()
582                .map(|ty| cx.layout_of(ty))
583                .try_collect::<IndexVec<_, _>>()?;
584
585            let layout = cx
586                .calc
587                .layout_of_coroutine(
588                    &local_layouts,
589                    prefix_layouts,
590                    &info.variant_fields,
591                    &info.storage_conflicts,
592                    |tag| TyAndLayout {
593                        ty: tag.primitive().to_ty(tcx),
594                        layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
595                    },
596                )
597                .map(|mut layout| {
598                    // this is similar to how ReprOptions populates its field_shuffle_seed
599                    layout.randomization_seed = tcx.def_path_hash(def_id).0.to_smaller_hash();
600                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:600",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(600u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("coroutine layout ({0:?}): {1:#?}",
                                                    ty, layout) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coroutine layout ({:?}): {:#?}", ty, layout);
601                    layout
602                });
603            map_layout(layout)?
604        }
605
606        ty::Closure(_, args) => univariant(args.as_closure().upvar_tys(), StructKind::AlwaysSized)?,
607
608        ty::CoroutineClosure(_, args) => {
609            univariant(args.as_coroutine_closure().upvar_tys(), StructKind::AlwaysSized)?
610        }
611
612        ty::Tuple(tys) => {
613            let kind =
614                if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized };
615
616            univariant(tys, kind)?
617        }
618
619        // Scalable vector types
620        //
621        // ```rust (ignore, example)
622        // #[rustc_scalable_vector(3)]
623        // struct svuint32_t(u32);
624        //
625        // #[rustc_scalable_vector]
626        // struct svuint32x2_t(svuint32_t, svuint32_t);
627        // ```
628        ty::Adt(def, _args) if def.repr().scalable() => {
629            let Some((element_count, element_ty, number_of_vectors)) =
630                ty.scalable_vector_parts(tcx)
631            else {
632                let guar = tcx
633                    .dcx()
634                    .delayed_bug("`#[rustc_scalable_vector]` was applied to an invalid type");
635                return Err(error(cx, LayoutError::ReferencesError(guar)));
636            };
637
638            let element_layout = cx.layout_of(element_ty)?;
639            map_layout(cx.calc.layout_of_scalable_vector_type(
640                element_layout,
641                element_count as u64,
642                number_of_vectors,
643            ))?
644        }
645
646        // SIMD vector types.
647        ty::Adt(def, args) if def.repr().simd() => {
648            // Supported SIMD vectors are ADTs with a single array field:
649            //
650            // * #[repr(simd)] struct S([T; 4])
651            //
652            // where T is a primitive scalar (integer/float/pointer).
653            let field_ty = def
654                .is_struct()
655                .then(|| &def.variant(FIRST_VARIANT).fields)
656                .filter(|fields| fields.len() == 1)
657                .map(|fields| {
658                    // The fields type is not part of ty, so the normalization of ty in
659                    // layout_of has not covered it.
660                    let field_ty = fields[FieldIdx::ZERO].ty(tcx, args);
661                    tcx.try_normalize_erasing_regions(cx.typing_env, field_ty).map_err(|err| {
662                        let field_ty = field_ty.skip_normalization();
663                        error(cx, LayoutError::NormalizationFailure(field_ty, err))
664                    })
665                })
666                .transpose()?;
667            let Some(&ty::Array(e_ty, e_len)) = field_ty.map(|field_ty| field_ty.kind()) else {
668                // Invalid SIMD types should have been caught by typeck by now.
669                let guar = tcx.dcx().delayed_bug("#[repr(simd)] was applied to an invalid ADT");
670                return Err(error(cx, LayoutError::ReferencesError(guar)));
671            };
672
673            if let Err(guar) = e_len.error_reported() {
674                return Err(error(cx, LayoutError::ReferencesError(guar)));
675            }
676
677            let e_len = extract_const_value(cx, ty, e_len)?
678                .try_to_target_usize(tcx)
679                .ok_or_else(|| error(cx, LayoutError::Unknown(ty)))?;
680
681            let e_ly = cx.layout_of(e_ty)?;
682
683            // Check for the rustc_simd_monomorphize_lane_limit attribute and check the lane limit
684            if let Some(limit) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def.did(), &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcSimdMonomorphizeLaneLimit(limit))
                        => {
                        break 'done Some(limit);
                    }
                    ::rustc_attr_ir::Attribute::Tool { .. } |
                        ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(
685                tcx, def.did(),
686                RustcSimdMonomorphizeLaneLimit(limit) => limit
687            ) {
688                if !limit.value_within_limit(e_len as usize) {
689                    return Err(map_error(
690                        &cx,
691                        ty,
692                        rustc_abi::LayoutCalculatorError::OversizedSimdType { max_lanes: limit.0 },
693                    ));
694                }
695            }
696
697            map_layout(cx.calc.layout_of_simd_type(e_ly, e_len, def.repr().packed()))?
698        }
699
700        // ADTs.
701        ty::Adt(def, args) => {
702            // Cache the field layouts.
703            let variants = def
704                .variants()
705                .iter()
706                .map(|v| {
707                    v.fields
708                        .iter()
709                        .map(|field| cx.layout_of(field.ty(tcx, args).skip_norm_wip()))
710                        .try_collect::<IndexVec<_, _>>()
711                })
712                .try_collect::<IndexVec<VariantIdx, _>>()?;
713
714            if def.is_union() {
715                if def.repr().pack.is_some() && def.repr().align.is_some() {
716                    let guar = tcx.dcx().span_delayed_bug(
717                        tcx.def_span(def.did()),
718                        "union cannot be packed and aligned",
719                    );
720                    return Err(error(cx, LayoutError::ReferencesError(guar)));
721                }
722
723                return map_layout(cx.calc.layout_of_union(&def.repr(), &variants));
724            }
725
726            // UnsafeCell and UnsafePinned both disable niche optimizations
727            let niche_optimizations = match def.is_unsafe_cell() || def.is_unsafe_pinned() {
728                true => NicheOptimizations::Disabled,
729                false => NicheOptimizations::Enabled,
730            };
731
732            let discr_range_of_repr = |min: RangeFrom<i128>, max: RangeToInclusive<u128>| {
733                abi::Integer::discr_range_of_repr(tcx, ty, &def.repr(), min.start, max.last)
734            };
735
736            // We shouldn't be computing the layout of discrs that fail typeck
737            if def.is_enum() {
738                for v in def.variants() {
739                    if let ty::VariantDiscr::Explicit(def_id) = v.discr
740                        && let Some(local_did) = def_id.as_local()
741                        && let Some(guar) = tcx.typeck(local_did).tainted_by_errors
742                    {
743                        return Err(error(cx, LayoutError::ReferencesError(guar)));
744                    }
745                }
746            }
747
748            let discriminants_iter = || {
749                def.is_enum()
750                    .then(|| def.discriminants(tcx).map(|(v, d)| (v, d.val)))
751                    .into_flat_iter()
752            };
753
754            let maybe_unsized = def.is_struct()
755                && def.non_enum_variant().tail_opt().is_some_and(|last_field| {
756                    let typing_env = ty::TypingEnv::new(
757                        tcx.param_env_normalized_for_post_analysis(def.did()),
758                        cx.typing_env.typing_mode(),
759                    );
760                    !tcx.type_of(last_field.did)
761                        .instantiate_identity()
762                        .skip_norm_wip()
763                        .is_sized(tcx, typing_env)
764                });
765
766            let mut layout = cx
767                .calc
768                .layout_of_struct_or_enum(
769                    &def.repr(),
770                    &variants,
771                    def.is_enum(),
772                    niche_optimizations,
773                    discr_range_of_repr,
774                    discriminants_iter(),
775                    !maybe_unsized,
776                )
777                .map_err(|err| map_error(cx, ty, err))?;
778
779            if !maybe_unsized && layout.is_unsized() {
780                ::rustc_span::macros::bug_impl(None,
    format_args!("got unsized layout for type that cannot be unsized {0:?}: {1:#?}",
        ty, layout), Location::caller());bug!("got unsized layout for type that cannot be unsized {ty:?}: {layout:#?}");
781            }
782
783            // If the struct tail is sized and can be unsized, check that unsizing doesn't move the fields around.
784            if truecfg!(debug_assertions)
785                && maybe_unsized
786                && def
787                    .non_enum_variant()
788                    .tail()
789                    .ty(tcx, args)
790                    .skip_norm_wip()
791                    .is_sized(tcx, cx.typing_env)
792            {
793                let mut variants = variants;
794                let tail_replacement = cx.layout_of(Ty::new_slice(tcx, tcx.types.u8)).unwrap();
795                *variants[FIRST_VARIANT].raw.last_mut().unwrap() = tail_replacement;
796
797                let Ok(unsized_layout) = cx.calc.layout_of_struct_or_enum(
798                    &def.repr(),
799                    &variants,
800                    def.is_enum(),
801                    niche_optimizations,
802                    discr_range_of_repr,
803                    discriminants_iter(),
804                    !maybe_unsized,
805                ) else {
806                    ::rustc_span::macros::bug_impl(None,
    format_args!("failed to compute unsized layout of {0:?}", ty),
    Location::caller());bug!("failed to compute unsized layout of {ty:?}");
807                };
808
809                let FieldsShape::Arbitrary { offsets: sized_offsets, .. } = &layout.fields else {
810                    ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected FieldsShape for sized layout of {1:?}: {0:?}",
        layout.fields, ty), Location::caller());bug!("unexpected FieldsShape for sized layout of {ty:?}: {:?}", layout.fields);
811                };
812                let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } =
813                    &unsized_layout.fields
814                else {
815                    ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected FieldsShape for unsized layout of {1:?}: {0:?}",
        unsized_layout.fields, ty), Location::caller());bug!(
816                        "unexpected FieldsShape for unsized layout of {ty:?}: {:?}",
817                        unsized_layout.fields
818                    );
819                };
820
821                let (sized_tail, sized_fields) = sized_offsets.raw.split_last().unwrap();
822                let (unsized_tail, unsized_fields) = unsized_offsets.raw.split_last().unwrap();
823
824                if sized_fields != unsized_fields {
825                    ::rustc_span::macros::bug_impl(None,
    format_args!("unsizing {0:?} changed field order!\n{1:?}\n{2:?}", ty,
        layout, unsized_layout), Location::caller());bug!("unsizing {ty:?} changed field order!\n{layout:?}\n{unsized_layout:?}");
826                }
827
828                if sized_tail < unsized_tail {
829                    ::rustc_span::macros::bug_impl(None,
    format_args!("unsizing {0:?} moved tail backwards!\n{1:?}\n{2:?}", ty,
        layout, unsized_layout), Location::caller());bug!("unsizing {ty:?} moved tail backwards!\n{layout:?}\n{unsized_layout:?}");
830                }
831            }
832
833            if tcx.is_lang_item(def.did(), LangItem::F16B) {
834                let bfloat = scalar_unit(Primitive::Float(abi::Float::F16B));
835                {
    match (&layout.size, &abi::Float::F16B.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!(layout.size, abi::Float::F16B.size());
836                layout.align = abi::Float::F16B.align(cx);
837                layout.backend_repr = BackendRepr::Scalar(bfloat);
838            }
839
840            let arch = &tcx.target_spec().arch;
841
842            if tcx.is_lang_item(def.did(), LangItem::PpcF128) {
843                {
    match arch {
        Arch::PowerPC | Arch::PowerPC64 => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Arch::PowerPC | Arch::PowerPC64",
                ::core::option::Option::None);
        }
    }
};std::assert_matches!(arch, Arch::PowerPC | Arch::PowerPC64);
844
845                let ppcf128 = scalar_unit(Primitive::Float(abi::Float::PpcF128));
846                {
    match (&layout.size, &abi::Float::PpcF128.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!(layout.size, abi::Float::PpcF128.size());
847                layout.align = abi::Float::PpcF128.align(cx);
848                layout.backend_repr = BackendRepr::Scalar(ppcf128);
849            }
850
851            if tcx.is_lang_item(def.did(), LangItem::X87F80Raw) {
852                {
    match arch {
        Arch::X86 | Arch::X86_64 => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Arch::X86 | Arch::X86_64", ::core::option::Option::None);
        }
    }
};std::assert_matches!(arch, Arch::X86 | Arch::X86_64);
853
854                // The lang item has no fields: give it a scalar layout.
855                return Ok(scalar(Primitive::Float(abi::Float::X87F80)));
856            }
857
858            if tcx.is_lang_item(def.did(), LangItem::X87F80) {
859                {
    match arch {
        Arch::X86 | Arch::X86_64 => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Arch::X86 | Arch::X86_64", ::core::option::Option::None);
        }
    }
};std::assert_matches!(arch, Arch::X86 | Arch::X86_64);
860
861                // A wrapper around `x87_f80_raw` that adds the target-specific alignment.
862                // It is an ordinary aggregate with trailing padding.
863                {
    match (&layout.size, &abi::Float::X87F80.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!(layout.size, abi::Float::X87F80.size());
864                layout.align = cx.data_layout().x87_f80_align;
865                layout.unadjusted_abi_align = layout.align;
866                layout.size = layout.size.align_to(layout.align);
867                layout.backend_repr = BackendRepr::Memory { sized: true };
868                layout.largest_niche = None;
869            }
870
871            tcx.mk_layout(layout)
872        }
873
874        ty::UnsafeBinder(bound_ty) => {
875            let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
876            cx.layout_of(ty)?.layout
877        }
878
879        // Types with no meaningful known layout.
880        ty::Param(_) | ty::Placeholder(..) => {
881            return Err(error(cx, LayoutError::TooGeneric(ty)));
882        }
883
884        ty::Alias(..) => {
885            // In case we're still in a generic context, aliases might be rigid. E.g.
886            // if we've got a `T: Trait` where-bound, `T::Assoc` cannot be normalized
887            // in the current context.
888            //
889            // For some builtin traits, generic aliases can be rigid even in an empty environment,
890            // e.g. `<T as Pointee>::Metadata`.
891            //
892            // Due to trivial bounds, this can even be the case if the alias does not reference
893            // any generic parameters, e.g. a `for<'a> u32: Trait<'a>` where-bound means that
894            // `<u32 as Trait<'static>>::Assoc` is rigid.
895            let err = if ty.has_param() || !cx.typing_env.param_env.is_empty() {
896                LayoutError::TooGeneric(ty)
897            } else {
898                LayoutError::ReferencesError(cx.tcx().dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected rigid alias in layout_of after normalization: {0:?}",
                ty))
    })format!(
899                    "unexpected rigid alias in layout_of after normalization: {ty:?}"
900                )))
901            };
902            return Err(error(cx, err));
903        }
904
905        ty::Bound(..) | ty::CoroutineWitness(..) | ty::Infer(_) | ty::Error(_) => {
906            // `ty::Error` is handled at the top of this function.
907            ::rustc_span::macros::bug_impl(None,
    format_args!("layout_of: unexpected type `{0}`", ty), Location::caller())bug!("layout_of: unexpected type `{ty}`")
908        }
909
910        // FIXME(scrabsha)
911        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
912    })
913}
914
915fn record_layout_for_printing<'tcx>(cx: &LayoutCx<'tcx>, layout: TyAndLayout<'tcx>) {
916    // Ignore layouts that are done with non-empty environments or
917    // non-monomorphic layouts, as the user only wants to see the stuff
918    // resulting from the final codegen session.
919    if layout.ty.has_non_region_param() || !cx.typing_env.param_env.is_empty() {
920        return;
921    }
922
923    // (delay format until we actually need it)
924    let record = |kind, packed, opt_discr_size, variants| {
925        let type_desc = {
    let _guard = NoTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("{0}", layout.ty))
        })
}with_no_trimmed_paths!(format!("{}", layout.ty));
926        cx.tcx().sess.code_stats.record_type_size(
927            kind,
928            type_desc,
929            layout.align,
930            layout.size,
931            packed,
932            opt_discr_size,
933            variants,
934        );
935    };
936
937    match *layout.ty.kind() {
938        ty::Adt(adt_def, _) => {
939            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:939",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(939u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("print-type-size t: `{0:?}` process adt",
                                                    layout.ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` process adt", layout.ty);
940            let adt_kind = adt_def.adt_kind();
941            let adt_packed = adt_def.repr().pack.is_some();
942            let (variant_infos, opt_discr_size) = variant_info_for_adt(cx, layout, adt_def);
943            record(adt_kind.into(), adt_packed, opt_discr_size, variant_infos);
944        }
945
946        ty::Coroutine(def_id, args) => {
947            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:947",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(947u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("print-type-size t: `{0:?}` record coroutine",
                                                    layout.ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` record coroutine", layout.ty);
948            // Coroutines always have a begin/poisoned/end state with additional suspend points
949            let (variant_infos, opt_discr_size) =
950                variant_info_for_coroutine(cx, layout, def_id, args);
951            record(DataTypeKind::Coroutine, false, opt_discr_size, variant_infos);
952        }
953
954        ty::Closure(..) => {
955            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:955",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(955u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("print-type-size t: `{0:?}` record closure",
                                                    layout.ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` record closure", layout.ty);
956            record(DataTypeKind::Closure, false, None, ::alloc::vec::Vec::new()vec![]);
957        }
958
959        _ => {
960            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:960",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(960u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("print-type-size t: `{0:?}` skip non-nominal",
                                                    layout.ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("print-type-size t: `{:?}` skip non-nominal", layout.ty);
961        }
962    };
963}
964
965fn variant_info_for_adt<'tcx>(
966    cx: &LayoutCx<'tcx>,
967    layout: TyAndLayout<'tcx>,
968    adt_def: AdtDef<'tcx>,
969) -> (Vec<VariantInfo>, Option<Size>) {
970    let build_variant_info = |n: Option<Symbol>, flds: &[Symbol], layout: TyAndLayout<'tcx>| {
971        let mut min_size = Size::ZERO;
972        let field_info: Vec<_> = flds
973            .iter()
974            .enumerate()
975            .map(|(i, &name)| {
976                let field_layout = layout.field(cx, i);
977                let offset = layout.fields.offset(i);
978                min_size = min_size.max(offset + field_layout.size);
979                FieldInfo {
980                    kind: FieldKind::AdtField,
981                    name,
982                    offset: offset.bytes(),
983                    size: field_layout.size.bytes(),
984                    align: field_layout.align.bytes(),
985                    type_name: None,
986                }
987            })
988            .collect();
989
990        VariantInfo {
991            name: n,
992            kind: if layout.is_unsized() { SizeKind::Min } else { SizeKind::Exact },
993            align: layout.align.bytes(),
994            size: if min_size.bytes() == 0 { layout.size.bytes() } else { min_size.bytes() },
995            fields: field_info,
996        }
997    };
998
999    match layout.variants {
1000        Variants::Empty => (::alloc::vec::Vec::new()vec![], None),
1001
1002        Variants::Single { index } => {
1003            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:1003",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1003u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("print-type-size `{0:#?}` variant {1}",
                                                    layout, adt_def.variant(index).name) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("print-type-size `{:#?}` variant {}", layout, adt_def.variant(index).name);
1004            let variant_def = &adt_def.variant(index);
1005            let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
1006            (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [build_variant_info(Some(variant_def.name), &fields, layout)]))vec![build_variant_info(Some(variant_def.name), &fields, layout)], None)
1007        }
1008
1009        Variants::Multiple { tag, ref tag_encoding, .. } => {
1010            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs:1010",
                        "rustc_ty_utils::layout", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_ty_utils/src/layout.rs"),
                        ::tracing_core::__macro_support::Option::Some(1010u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::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!("print-type-size `{0:#?}` adt general variants def {1}",
                                                    layout.ty, adt_def.variants().len()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1011                "print-type-size `{:#?}` adt general variants def {}",
1012                layout.ty,
1013                adt_def.variants().len()
1014            );
1015            let variant_infos: Vec<_> = adt_def
1016                .variants()
1017                .iter_enumerated()
1018                .map(|(i, variant_def)| {
1019                    let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
1020                    build_variant_info(Some(variant_def.name), &fields, layout.for_variant(cx, i))
1021                })
1022                .collect();
1023
1024            (
1025                variant_infos,
1026                match tag_encoding {
1027                    TagEncoding::Direct => Some(tag.size(cx)),
1028                    _ => None,
1029                },
1030            )
1031        }
1032    }
1033}
1034
1035fn variant_info_for_coroutine<'tcx>(
1036    cx: &LayoutCx<'tcx>,
1037    layout: TyAndLayout<'tcx>,
1038    def_id: DefId,
1039    args: ty::GenericArgs<'tcx>,
1040) -> (Vec<VariantInfo>, Option<Size>) {
1041    use itertools::Itertools;
1042
1043    let Variants::Multiple { tag, ref tag_encoding, tag_field, .. } = layout.variants else {
1044        return (::alloc::vec::Vec::new()vec![], None);
1045    };
1046
1047    let coroutine = cx.tcx().coroutine_layout(def_id, args).unwrap();
1048    let upvar_names = cx.tcx().closure_saved_names_of_captured_variables(def_id);
1049
1050    let mut upvars_size = Size::ZERO;
1051    let upvar_fields: Vec<_> = args
1052        .as_coroutine()
1053        .upvar_tys()
1054        .iter()
1055        .zip_eq(upvar_names)
1056        .enumerate()
1057        .map(|(field_idx, (_, name))| {
1058            let field_layout = layout.field(cx, field_idx);
1059            let offset = layout.fields.offset(field_idx);
1060            upvars_size = upvars_size.max(offset + field_layout.size);
1061            FieldInfo {
1062                kind: FieldKind::Upvar,
1063                name: *name,
1064                offset: offset.bytes(),
1065                size: field_layout.size.bytes(),
1066                align: field_layout.align.bytes(),
1067                type_name: None,
1068            }
1069        })
1070        .collect();
1071
1072    let mut variant_infos: Vec<_> = coroutine
1073        .variant_fields
1074        .iter_enumerated()
1075        .map(|(variant_idx, variant_def)| {
1076            let variant_layout = layout.for_variant(cx, variant_idx);
1077            let mut variant_size = Size::ZERO;
1078            let fields = variant_def
1079                .iter()
1080                .enumerate()
1081                .map(|(field_idx, local)| {
1082                    let field_name = coroutine.field_tys[*local].debuginfo_name;
1083                    let field_layout = variant_layout.field(cx, field_idx);
1084                    let offset = variant_layout.fields.offset(field_idx);
1085                    // The struct is as large as the last field's end
1086                    variant_size = variant_size.max(offset + field_layout.size);
1087                    FieldInfo {
1088                        kind: FieldKind::CoroutineLocal,
1089                        name: field_name.unwrap_or_else(|| {
1090                            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".coroutine_field{0}",
                local.as_usize()))
    })format!(".coroutine_field{}", local.as_usize()))
1091                        }),
1092                        offset: offset.bytes(),
1093                        size: field_layout.size.bytes(),
1094                        align: field_layout.align.bytes(),
1095                        // Include the type name if there is no field name, or if the name is the
1096                        // __awaitee placeholder symbol which means a child future being `.await`ed.
1097                        type_name: (field_name.is_none() || field_name == Some(sym::__awaitee))
1098                            .then(|| Symbol::intern(&field_layout.ty.to_string())),
1099                    }
1100                })
1101                .chain(upvar_fields.iter().copied())
1102                .collect();
1103
1104            // If the variant has no state-specific fields, then it's the size of the upvars.
1105            if variant_size == Size::ZERO {
1106                variant_size = upvars_size;
1107            }
1108
1109            // This `if` deserves some explanation.
1110            //
1111            // The layout code has a choice of where to place the discriminant of this coroutine.
1112            // If the discriminant of the coroutine is placed early in the layout (before the
1113            // variant's own fields), then it'll implicitly be counted towards the size of the
1114            // variant, since we use the maximum offset to calculate size.
1115            //    (side-note: I know this is a bit problematic given upvars placement, etc).
1116            //
1117            // This is important, since the layout printing code always subtracts this discriminant
1118            // size from the variant size if the struct is "enum"-like, so failing to account for it
1119            // will either lead to numerical underflow, or an underreported variant size...
1120            //
1121            // However, if the discriminant is placed past the end of the variant, then we need
1122            // to factor in the size of the discriminant manually. This really should be refactored
1123            // better, but this "works" for now.
1124            if layout.fields.offset(tag_field.as_usize()) >= variant_size {
1125                variant_size += match tag_encoding {
1126                    TagEncoding::Direct => tag.size(cx),
1127                    _ => Size::ZERO,
1128                };
1129            }
1130
1131            VariantInfo {
1132                name: Some(Symbol::intern(&ty::CoroutineArgs::variant_name(variant_idx))),
1133                kind: SizeKind::Exact,
1134                size: variant_size.bytes(),
1135                align: variant_layout.align.bytes(),
1136                fields,
1137            }
1138        })
1139        .collect();
1140
1141    // The first three variants are hardcoded to be `UNRESUMED`, `RETURNED` and `POISONED`.
1142    // We will move the `RETURNED` and `POISONED` elements to the end so we
1143    // are left with a sorting order according to the coroutines yield points:
1144    // First `Unresumed`, then the `SuspendN` followed by `Returned` and `Panicked` (POISONED).
1145    let end_states = variant_infos.drain(1..=2);
1146    let end_states: Vec<_> = end_states.collect();
1147    variant_infos.extend(end_states);
1148
1149    (
1150        variant_infos,
1151        match tag_encoding {
1152            TagEncoding::Direct => Some(tag.size(cx)),
1153            _ => None,
1154        },
1155    )
1156}