rustc_ty_utils/
layout.rs

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