]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/layout.rs
make rustc_target usable outside of rustc
[rust.git] / compiler / rustc_ty_utils / src / layout.rs
1 use rustc_hir as hir;
2 use rustc_index::bit_set::BitSet;
3 use rustc_index::vec::{Idx, IndexVec};
4 use rustc_middle::mir::{GeneratorLayout, GeneratorSavedLocal};
5 use rustc_middle::ty::layout::{
6     IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES,
7 };
8 use rustc_middle::ty::{
9     self, subst::SubstsRef, EarlyBinder, ReprOptions, Ty, TyCtxt, TypeVisitable,
10 };
11 use rustc_session::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
12 use rustc_span::symbol::Symbol;
13 use rustc_span::DUMMY_SP;
14 use rustc_target::abi::*;
15
16 use std::cmp::{self, Ordering};
17 use std::iter;
18 use std::num::NonZeroUsize;
19 use std::ops::Bound;
20
21 use rand::{seq::SliceRandom, SeedableRng};
22 use rand_xoshiro::Xoshiro128StarStar;
23
24 use crate::layout_sanity_check::sanity_check_layout;
25
26 pub fn provide(providers: &mut ty::query::Providers) {
27     *providers = ty::query::Providers { layout_of, ..*providers };
28 }
29
30 #[instrument(skip(tcx, query), level = "debug")]
31 fn layout_of<'tcx>(
32     tcx: TyCtxt<'tcx>,
33     query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
34 ) -> Result<TyAndLayout<'tcx>, LayoutError<'tcx>> {
35     let (param_env, ty) = query.into_parts();
36     debug!(?ty);
37
38     let param_env = param_env.with_reveal_all_normalized(tcx);
39     let unnormalized_ty = ty;
40
41     // FIXME: We might want to have two different versions of `layout_of`:
42     // One that can be called after typecheck has completed and can use
43     // `normalize_erasing_regions` here and another one that can be called
44     // before typecheck has completed and uses `try_normalize_erasing_regions`.
45     let ty = match tcx.try_normalize_erasing_regions(param_env, ty) {
46         Ok(t) => t,
47         Err(normalization_error) => {
48             return Err(LayoutError::NormalizationFailure(ty, normalization_error));
49         }
50     };
51
52     if ty != unnormalized_ty {
53         // Ensure this layout is also cached for the normalized type.
54         return tcx.layout_of(param_env.and(ty));
55     }
56
57     let cx = LayoutCx { tcx, param_env };
58
59     let layout = layout_of_uncached(&cx, ty)?;
60     let layout = TyAndLayout { ty, layout };
61
62     record_layout_for_printing(&cx, layout);
63
64     sanity_check_layout(&cx, &layout);
65
66     Ok(layout)
67 }
68
69 #[derive(Copy, Clone, Debug)]
70 enum StructKind {
71     /// A tuple, closure, or univariant which cannot be coerced to unsized.
72     AlwaysSized,
73     /// A univariant, the last field of which may be coerced to unsized.
74     MaybeUnsized,
75     /// A univariant, but with a prefix of an arbitrary size & alignment (e.g., enum tag).
76     Prefixed(Size, Align),
77 }
78
79 // Invert a bijective mapping, i.e. `invert(map)[y] = x` if `map[x] = y`.
80 // This is used to go between `memory_index` (source field order to memory order)
81 // and `inverse_memory_index` (memory order to source field order).
82 // See also `FieldsShape::Arbitrary::memory_index` for more details.
83 // FIXME(eddyb) build a better abstraction for permutations, if possible.
84 fn invert_mapping(map: &[u32]) -> Vec<u32> {
85     let mut inverse = vec![0; map.len()];
86     for i in 0..map.len() {
87         inverse[map[i] as usize] = i as u32;
88     }
89     inverse
90 }
91
92 fn scalar_pair<'tcx>(
93     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
94     a: Scalar,
95     b: Scalar,
96 ) -> LayoutS<VariantIdx> {
97     let dl = cx.data_layout();
98     let b_align = b.align(dl);
99     let align = a.align(dl).max(b_align).max(dl.aggregate_align);
100     let b_offset = a.size(dl).align_to(b_align.abi);
101     let size = (b_offset + b.size(dl)).align_to(align.abi);
102
103     // HACK(nox): We iter on `b` and then `a` because `max_by_key`
104     // returns the last maximum.
105     let largest_niche = Niche::from_scalar(dl, b_offset, b)
106         .into_iter()
107         .chain(Niche::from_scalar(dl, Size::ZERO, a))
108         .max_by_key(|niche| niche.available(dl));
109
110     LayoutS {
111         variants: Variants::Single { index: VariantIdx::new(0) },
112         fields: FieldsShape::Arbitrary {
113             offsets: vec![Size::ZERO, b_offset],
114             memory_index: vec![0, 1],
115         },
116         abi: Abi::ScalarPair(a, b),
117         largest_niche,
118         align,
119         size,
120     }
121 }
122
123 fn univariant_uninterned<'tcx>(
124     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
125     ty: Ty<'tcx>,
126     fields: &[TyAndLayout<'_>],
127     repr: &ReprOptions,
128     kind: StructKind,
129 ) -> Result<LayoutS<VariantIdx>, LayoutError<'tcx>> {
130     let dl = cx.data_layout();
131     let pack = repr.pack;
132     if pack.is_some() && repr.align.is_some() {
133         cx.tcx.sess.delay_span_bug(DUMMY_SP, "struct cannot be packed and aligned");
134         return Err(LayoutError::Unknown(ty));
135     }
136
137     let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
138
139     let mut inverse_memory_index: Vec<u32> = (0..fields.len() as u32).collect();
140
141     let optimize = !repr.inhibit_struct_field_reordering_opt();
142     if optimize {
143         let end = if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
144         let optimizing = &mut inverse_memory_index[..end];
145         let effective_field_align = |f: &TyAndLayout<'_>| {
146             if let Some(pack) = pack {
147                 // return the packed alignment in bytes
148                 f.align.abi.min(pack).bytes()
149             } else {
150                 // returns log2(effective-align).
151                 // This is ok since `pack` applies to all fields equally.
152                 // The calculation assumes that size is an integer multiple of align, except for ZSTs.
153                 //
154                 // group [u8; 4] with align-4 or [u8; 6] with align-2 fields
155                 f.align.abi.bytes().max(f.size.bytes()).trailing_zeros() as u64
156             }
157         };
158
159         // If `-Z randomize-layout` was enabled for the type definition we can shuffle
160         // the field ordering to try and catch some code making assumptions about layouts
161         // we don't guarantee
162         if repr.can_randomize_type_layout() {
163             // `ReprOptions.layout_seed` is a deterministic seed that we can use to
164             // randomize field ordering with
165             let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed);
166
167             // Shuffle the ordering of the fields
168             optimizing.shuffle(&mut rng);
169
170             // Otherwise we just leave things alone and actually optimize the type's fields
171         } else {
172             match kind {
173                 StructKind::AlwaysSized | StructKind::MaybeUnsized => {
174                     optimizing.sort_by_key(|&x| {
175                         // Place ZSTs first to avoid "interesting offsets",
176                         // especially with only one or two non-ZST fields.
177                         // Then place largest alignments first, largest niches within an alignment group last
178                         let f = &fields[x as usize];
179                         let niche_size = f.largest_niche.map_or(0, |n| n.available(cx));
180                         (!f.is_zst(), cmp::Reverse(effective_field_align(f)), niche_size)
181                     });
182                 }
183
184                 StructKind::Prefixed(..) => {
185                     // Sort in ascending alignment so that the layout stays optimal
186                     // regardless of the prefix.
187                     // And put the largest niche in an alignment group at the end
188                     // so it can be used as discriminant in jagged enums
189                     optimizing.sort_by_key(|&x| {
190                         let f = &fields[x as usize];
191                         let niche_size = f.largest_niche.map_or(0, |n| n.available(cx));
192                         (effective_field_align(f), niche_size)
193                     });
194                 }
195             }
196
197             // FIXME(Kixiron): We can always shuffle fields within a given alignment class
198             //                 regardless of the status of `-Z randomize-layout`
199         }
200     }
201
202     // inverse_memory_index holds field indices by increasing memory offset.
203     // That is, if field 5 has offset 0, the first element of inverse_memory_index is 5.
204     // We now write field offsets to the corresponding offset slot;
205     // field 5 with offset 0 puts 0 in offsets[5].
206     // At the bottom of this function, we invert `inverse_memory_index` to
207     // produce `memory_index` (see `invert_mapping`).
208
209     let mut sized = true;
210     let mut offsets = vec![Size::ZERO; fields.len()];
211     let mut offset = Size::ZERO;
212     let mut largest_niche = None;
213     let mut largest_niche_available = 0;
214
215     if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
216         let prefix_align =
217             if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
218         align = align.max(AbiAndPrefAlign::new(prefix_align));
219         offset = prefix_size.align_to(prefix_align);
220     }
221
222     for &i in &inverse_memory_index {
223         let field = fields[i as usize];
224         if !sized {
225             cx.tcx.sess.delay_span_bug(
226                 DUMMY_SP,
227                 &format!(
228                     "univariant: field #{} of `{}` comes after unsized field",
229                     offsets.len(),
230                     ty
231                 ),
232             );
233         }
234
235         if field.is_unsized() {
236             sized = false;
237         }
238
239         // Invariant: offset < dl.obj_size_bound() <= 1<<61
240         let field_align = if let Some(pack) = pack {
241             field.align.min(AbiAndPrefAlign::new(pack))
242         } else {
243             field.align
244         };
245         offset = offset.align_to(field_align.abi);
246         align = align.max(field_align);
247
248         debug!("univariant offset: {:?} field: {:#?}", offset, field);
249         offsets[i as usize] = offset;
250
251         if let Some(mut niche) = field.largest_niche {
252             let available = niche.available(dl);
253             if available > largest_niche_available {
254                 largest_niche_available = available;
255                 niche.offset += offset;
256                 largest_niche = Some(niche);
257             }
258         }
259
260         offset = offset.checked_add(field.size, dl).ok_or(LayoutError::SizeOverflow(ty))?;
261     }
262
263     if let Some(repr_align) = repr.align {
264         align = align.max(AbiAndPrefAlign::new(repr_align));
265     }
266
267     debug!("univariant min_size: {:?}", offset);
268     let min_size = offset;
269
270     // As stated above, inverse_memory_index holds field indices by increasing offset.
271     // This makes it an already-sorted view of the offsets vec.
272     // To invert it, consider:
273     // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0.
274     // Field 5 would be the first element, so memory_index is i:
275     // Note: if we didn't optimize, it's already right.
276
277     let memory_index =
278         if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index };
279
280     let size = min_size.align_to(align.abi);
281     let mut abi = Abi::Aggregate { sized };
282
283     // Unpack newtype ABIs and find scalar pairs.
284     if sized && size.bytes() > 0 {
285         // All other fields must be ZSTs.
286         let mut non_zst_fields = fields.iter().enumerate().filter(|&(_, f)| !f.is_zst());
287
288         match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
289             // We have exactly one non-ZST field.
290             (Some((i, field)), None, None) => {
291                 // Field fills the struct and it has a scalar or scalar pair ABI.
292                 if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size {
293                     match field.abi {
294                         // For plain scalars, or vectors of them, we can't unpack
295                         // newtypes for `#[repr(C)]`, as that affects C ABIs.
296                         Abi::Scalar(_) | Abi::Vector { .. } if optimize => {
297                             abi = field.abi;
298                         }
299                         // But scalar pairs are Rust-specific and get
300                         // treated as aggregates by C ABIs anyway.
301                         Abi::ScalarPair(..) => {
302                             abi = field.abi;
303                         }
304                         _ => {}
305                     }
306                 }
307             }
308
309             // Two non-ZST fields, and they're both scalars.
310             (Some((i, a)), Some((j, b)), None) => {
311                 match (a.abi, b.abi) {
312                     (Abi::Scalar(a), Abi::Scalar(b)) => {
313                         // Order by the memory placement, not source order.
314                         let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
315                             ((i, a), (j, b))
316                         } else {
317                             ((j, b), (i, a))
318                         };
319                         let pair = scalar_pair(cx, a, b);
320                         let pair_offsets = match pair.fields {
321                             FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
322                                 assert_eq!(memory_index, &[0, 1]);
323                                 offsets
324                             }
325                             _ => bug!(),
326                         };
327                         if offsets[i] == pair_offsets[0]
328                             && offsets[j] == pair_offsets[1]
329                             && align == pair.align
330                             && size == pair.size
331                         {
332                             // We can use `ScalarPair` only when it matches our
333                             // already computed layout (including `#[repr(C)]`).
334                             abi = pair.abi;
335                         }
336                     }
337                     _ => {}
338                 }
339             }
340
341             _ => {}
342         }
343     }
344
345     if fields.iter().any(|f| f.abi.is_uninhabited()) {
346         abi = Abi::Uninhabited;
347     }
348
349     Ok(LayoutS {
350         variants: Variants::Single { index: VariantIdx::new(0) },
351         fields: FieldsShape::Arbitrary { offsets, memory_index },
352         abi,
353         largest_niche,
354         align,
355         size,
356     })
357 }
358
359 fn layout_of_uncached<'tcx>(
360     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
361     ty: Ty<'tcx>,
362 ) -> Result<Layout<'tcx>, LayoutError<'tcx>> {
363     let tcx = cx.tcx;
364     let param_env = cx.param_env;
365     let dl = cx.data_layout();
366     let scalar_unit = |value: Primitive| {
367         let size = value.size(dl);
368         assert!(size.bits() <= 128);
369         Scalar::Initialized { value, valid_range: WrappingRange::full(size) }
370     };
371     let scalar = |value: Primitive| tcx.intern_layout(LayoutS::scalar(cx, scalar_unit(value)));
372
373     let univariant = |fields: &[TyAndLayout<'_>], repr: &ReprOptions, kind| {
374         Ok(tcx.intern_layout(univariant_uninterned(cx, ty, fields, repr, kind)?))
375     };
376     debug_assert!(!ty.has_non_region_infer());
377
378     Ok(match *ty.kind() {
379         // Basic scalars.
380         ty::Bool => tcx.intern_layout(LayoutS::scalar(
381             cx,
382             Scalar::Initialized {
383                 value: Int(I8, false),
384                 valid_range: WrappingRange { start: 0, end: 1 },
385             },
386         )),
387         ty::Char => tcx.intern_layout(LayoutS::scalar(
388             cx,
389             Scalar::Initialized {
390                 value: Int(I32, false),
391                 valid_range: WrappingRange { start: 0, end: 0x10FFFF },
392             },
393         )),
394         ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)),
395         ty::Uint(ity) => scalar(Int(Integer::from_uint_ty(dl, ity), false)),
396         ty::Float(fty) => scalar(match fty {
397             ty::FloatTy::F32 => F32,
398             ty::FloatTy::F64 => F64,
399         }),
400         ty::FnPtr(_) => {
401             let mut ptr = scalar_unit(Pointer);
402             ptr.valid_range_mut().start = 1;
403             tcx.intern_layout(LayoutS::scalar(cx, ptr))
404         }
405
406         // The never type.
407         ty::Never => tcx.intern_layout(LayoutS {
408             variants: Variants::Single { index: VariantIdx::new(0) },
409             fields: FieldsShape::Primitive,
410             abi: Abi::Uninhabited,
411             largest_niche: None,
412             align: dl.i8_align,
413             size: Size::ZERO,
414         }),
415
416         // Potentially-wide pointers.
417         ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
418             let mut data_ptr = scalar_unit(Pointer);
419             if !ty.is_unsafe_ptr() {
420                 data_ptr.valid_range_mut().start = 1;
421             }
422
423             let pointee = tcx.normalize_erasing_regions(param_env, pointee);
424             if pointee.is_sized(tcx, param_env) {
425                 return Ok(tcx.intern_layout(LayoutS::scalar(cx, data_ptr)));
426             }
427
428             let unsized_part = tcx.struct_tail_erasing_lifetimes(pointee, param_env);
429             let metadata = match unsized_part.kind() {
430                 ty::Foreign(..) => {
431                     return Ok(tcx.intern_layout(LayoutS::scalar(cx, data_ptr)));
432                 }
433                 ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)),
434                 ty::Dynamic(..) => {
435                     let mut vtable = scalar_unit(Pointer);
436                     vtable.valid_range_mut().start = 1;
437                     vtable
438                 }
439                 _ => return Err(LayoutError::Unknown(unsized_part)),
440             };
441
442             // Effectively a (ptr, meta) tuple.
443             tcx.intern_layout(scalar_pair(cx, data_ptr, metadata))
444         }
445
446         ty::Dynamic(_, _, ty::DynStar) => {
447             let mut data = scalar_unit(Int(dl.ptr_sized_integer(), false));
448             data.valid_range_mut().start = 0;
449             let mut vtable = scalar_unit(Pointer);
450             vtable.valid_range_mut().start = 1;
451             tcx.intern_layout(scalar_pair(cx, data, vtable))
452         }
453
454         // Arrays and slices.
455         ty::Array(element, mut count) => {
456             if count.has_projections() {
457                 count = tcx.normalize_erasing_regions(param_env, count);
458                 if count.has_projections() {
459                     return Err(LayoutError::Unknown(ty));
460                 }
461             }
462
463             let count = count.try_eval_usize(tcx, param_env).ok_or(LayoutError::Unknown(ty))?;
464             let element = cx.layout_of(element)?;
465             let size = element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow(ty))?;
466
467             let abi = if count != 0 && ty.is_privately_uninhabited(tcx, param_env) {
468                 Abi::Uninhabited
469             } else {
470                 Abi::Aggregate { sized: true }
471             };
472
473             let largest_niche = if count != 0 { element.largest_niche } else { None };
474
475             tcx.intern_layout(LayoutS {
476                 variants: Variants::Single { index: VariantIdx::new(0) },
477                 fields: FieldsShape::Array { stride: element.size, count },
478                 abi,
479                 largest_niche,
480                 align: element.align,
481                 size,
482             })
483         }
484         ty::Slice(element) => {
485             let element = cx.layout_of(element)?;
486             tcx.intern_layout(LayoutS {
487                 variants: Variants::Single { index: VariantIdx::new(0) },
488                 fields: FieldsShape::Array { stride: element.size, count: 0 },
489                 abi: Abi::Aggregate { sized: false },
490                 largest_niche: None,
491                 align: element.align,
492                 size: Size::ZERO,
493             })
494         }
495         ty::Str => tcx.intern_layout(LayoutS {
496             variants: Variants::Single { index: VariantIdx::new(0) },
497             fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 },
498             abi: Abi::Aggregate { sized: false },
499             largest_niche: None,
500             align: dl.i8_align,
501             size: Size::ZERO,
502         }),
503
504         // Odd unit types.
505         ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?,
506         ty::Dynamic(_, _, ty::Dyn) | ty::Foreign(..) => {
507             let mut unit = univariant_uninterned(
508                 cx,
509                 ty,
510                 &[],
511                 &ReprOptions::default(),
512                 StructKind::AlwaysSized,
513             )?;
514             match unit.abi {
515                 Abi::Aggregate { ref mut sized } => *sized = false,
516                 _ => bug!(),
517             }
518             tcx.intern_layout(unit)
519         }
520
521         ty::Generator(def_id, substs, _) => generator_layout(cx, ty, def_id, substs)?,
522
523         ty::Closure(_, ref substs) => {
524             let tys = substs.as_closure().upvar_tys();
525             univariant(
526                 &tys.map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
527                 &ReprOptions::default(),
528                 StructKind::AlwaysSized,
529             )?
530         }
531
532         ty::Tuple(tys) => {
533             let kind =
534                 if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized };
535
536             univariant(
537                 &tys.iter().map(|k| cx.layout_of(k)).collect::<Result<Vec<_>, _>>()?,
538                 &ReprOptions::default(),
539                 kind,
540             )?
541         }
542
543         // SIMD vector types.
544         ty::Adt(def, substs) if def.repr().simd() => {
545             if !def.is_struct() {
546                 // Should have yielded E0517 by now.
547                 tcx.sess.delay_span_bug(
548                     DUMMY_SP,
549                     "#[repr(simd)] was applied to an ADT that is not a struct",
550                 );
551                 return Err(LayoutError::Unknown(ty));
552             }
553
554             // Supported SIMD vectors are homogeneous ADTs with at least one field:
555             //
556             // * #[repr(simd)] struct S(T, T, T, T);
557             // * #[repr(simd)] struct S { x: T, y: T, z: T, w: T }
558             // * #[repr(simd)] struct S([T; 4])
559             //
560             // where T is a primitive scalar (integer/float/pointer).
561
562             // SIMD vectors with zero fields are not supported.
563             // (should be caught by typeck)
564             if def.non_enum_variant().fields.is_empty() {
565                 tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty));
566             }
567
568             // Type of the first ADT field:
569             let f0_ty = def.non_enum_variant().fields[0].ty(tcx, substs);
570
571             // Heterogeneous SIMD vectors are not supported:
572             // (should be caught by typeck)
573             for fi in &def.non_enum_variant().fields {
574                 if fi.ty(tcx, substs) != f0_ty {
575                     tcx.sess.fatal(&format!("monomorphising heterogeneous SIMD type `{}`", ty));
576                 }
577             }
578
579             // The element type and number of elements of the SIMD vector
580             // are obtained from:
581             //
582             // * the element type and length of the single array field, if
583             // the first field is of array type, or
584             //
585             // * the homogeneous field type and the number of fields.
586             let (e_ty, e_len, is_array) = if let ty::Array(e_ty, _) = f0_ty.kind() {
587                 // First ADT field is an array:
588
589                 // SIMD vectors with multiple array fields are not supported:
590                 // (should be caught by typeck)
591                 if def.non_enum_variant().fields.len() != 1 {
592                     tcx.sess.fatal(&format!(
593                         "monomorphising SIMD type `{}` with more than one array field",
594                         ty
595                     ));
596                 }
597
598                 // Extract the number of elements from the layout of the array field:
599                 let FieldsShape::Array { count, .. } = cx.layout_of(f0_ty)?.layout.fields() else {
600                         return Err(LayoutError::Unknown(ty));
601                     };
602
603                 (*e_ty, *count, true)
604             } else {
605                 // First ADT field is not an array:
606                 (f0_ty, def.non_enum_variant().fields.len() as _, false)
607             };
608
609             // SIMD vectors of zero length are not supported.
610             // Additionally, lengths are capped at 2^16 as a fixed maximum backends must
611             // support.
612             //
613             // Can't be caught in typeck if the array length is generic.
614             if e_len == 0 {
615                 tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty));
616             } else if e_len > MAX_SIMD_LANES {
617                 tcx.sess.fatal(&format!(
618                     "monomorphising SIMD type `{}` of length greater than {}",
619                     ty, MAX_SIMD_LANES,
620                 ));
621             }
622
623             // Compute the ABI of the element type:
624             let e_ly = cx.layout_of(e_ty)?;
625             let Abi::Scalar(e_abi) = e_ly.abi else {
626                     // This error isn't caught in typeck, e.g., if
627                     // the element type of the vector is generic.
628                     tcx.sess.fatal(&format!(
629                         "monomorphising SIMD type `{}` with a non-primitive-scalar \
630                         (integer/float/pointer) element type `{}`",
631                         ty, e_ty
632                     ))
633                 };
634
635             // Compute the size and alignment of the vector:
636             let size = e_ly.size.checked_mul(e_len, dl).ok_or(LayoutError::SizeOverflow(ty))?;
637             let align = dl.vector_align(size);
638             let size = size.align_to(align.abi);
639
640             // Compute the placement of the vector fields:
641             let fields = if is_array {
642                 FieldsShape::Arbitrary { offsets: vec![Size::ZERO], memory_index: vec![0] }
643             } else {
644                 FieldsShape::Array { stride: e_ly.size, count: e_len }
645             };
646
647             tcx.intern_layout(LayoutS {
648                 variants: Variants::Single { index: VariantIdx::new(0) },
649                 fields,
650                 abi: Abi::Vector { element: e_abi, count: e_len },
651                 largest_niche: e_ly.largest_niche,
652                 size,
653                 align,
654             })
655         }
656
657         // ADTs.
658         ty::Adt(def, substs) => {
659             // Cache the field layouts.
660             let variants = def
661                 .variants()
662                 .iter()
663                 .map(|v| {
664                     v.fields
665                         .iter()
666                         .map(|field| cx.layout_of(field.ty(tcx, substs)))
667                         .collect::<Result<Vec<_>, _>>()
668                 })
669                 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
670
671             if def.is_union() {
672                 if def.repr().pack.is_some() && def.repr().align.is_some() {
673                     cx.tcx.sess.delay_span_bug(
674                         tcx.def_span(def.did()),
675                         "union cannot be packed and aligned",
676                     );
677                     return Err(LayoutError::Unknown(ty));
678                 }
679
680                 let mut align =
681                     if def.repr().pack.is_some() { dl.i8_align } else { dl.aggregate_align };
682
683                 if let Some(repr_align) = def.repr().align {
684                     align = align.max(AbiAndPrefAlign::new(repr_align));
685                 }
686
687                 let optimize = !def.repr().inhibit_union_abi_opt();
688                 let mut size = Size::ZERO;
689                 let mut abi = Abi::Aggregate { sized: true };
690                 let index = VariantIdx::new(0);
691                 for field in &variants[index] {
692                     assert!(field.is_sized());
693                     align = align.max(field.align);
694
695                     // If all non-ZST fields have the same ABI, forward this ABI
696                     if optimize && !field.is_zst() {
697                         // Discard valid range information and allow undef
698                         let field_abi = match field.abi {
699                             Abi::Scalar(x) => Abi::Scalar(x.to_union()),
700                             Abi::ScalarPair(x, y) => Abi::ScalarPair(x.to_union(), y.to_union()),
701                             Abi::Vector { element: x, count } => {
702                                 Abi::Vector { element: x.to_union(), count }
703                             }
704                             Abi::Uninhabited | Abi::Aggregate { .. } => {
705                                 Abi::Aggregate { sized: true }
706                             }
707                         };
708
709                         if size == Size::ZERO {
710                             // first non ZST: initialize 'abi'
711                             abi = field_abi;
712                         } else if abi != field_abi {
713                             // different fields have different ABI: reset to Aggregate
714                             abi = Abi::Aggregate { sized: true };
715                         }
716                     }
717
718                     size = cmp::max(size, field.size);
719                 }
720
721                 if let Some(pack) = def.repr().pack {
722                     align = align.min(AbiAndPrefAlign::new(pack));
723                 }
724
725                 return Ok(tcx.intern_layout(LayoutS {
726                     variants: Variants::Single { index },
727                     fields: FieldsShape::Union(
728                         NonZeroUsize::new(variants[index].len()).ok_or(LayoutError::Unknown(ty))?,
729                     ),
730                     abi,
731                     largest_niche: None,
732                     align,
733                     size: size.align_to(align.abi),
734                 }));
735             }
736
737             // A variant is absent if it's uninhabited and only has ZST fields.
738             // Present uninhabited variants only require space for their fields,
739             // but *not* an encoding of the discriminant (e.g., a tag value).
740             // See issue #49298 for more details on the need to leave space
741             // for non-ZST uninhabited data (mostly partial initialization).
742             let absent = |fields: &[TyAndLayout<'_>]| {
743                 let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited());
744                 let is_zst = fields.iter().all(|f| f.is_zst());
745                 uninhabited && is_zst
746             };
747             let (present_first, present_second) = {
748                 let mut present_variants = variants
749                     .iter_enumerated()
750                     .filter_map(|(i, v)| if absent(v) { None } else { Some(i) });
751                 (present_variants.next(), present_variants.next())
752             };
753             let present_first = match present_first {
754                 Some(present_first) => present_first,
755                 // Uninhabited because it has no variants, or only absent ones.
756                 None if def.is_enum() => {
757                     return Ok(tcx.layout_of(param_env.and(tcx.types.never))?.layout);
758                 }
759                 // If it's a struct, still compute a layout so that we can still compute the
760                 // field offsets.
761                 None => VariantIdx::new(0),
762             };
763
764             let is_struct = !def.is_enum() ||
765                     // Only one variant is present.
766                     (present_second.is_none() &&
767                         // Representation optimizations are allowed.
768                         !def.repr().inhibit_enum_layout_opt());
769             if is_struct {
770                 // Struct, or univariant enum equivalent to a struct.
771                 // (Typechecking will reject discriminant-sizing attrs.)
772
773                 let v = present_first;
774                 let kind = if def.is_enum() || variants[v].is_empty() {
775                     StructKind::AlwaysSized
776                 } else {
777                     let param_env = tcx.param_env(def.did());
778                     let last_field = def.variant(v).fields.last().unwrap();
779                     let always_sized = tcx.type_of(last_field.did).is_sized(tcx, param_env);
780                     if !always_sized { StructKind::MaybeUnsized } else { StructKind::AlwaysSized }
781                 };
782
783                 let mut st = univariant_uninterned(cx, ty, &variants[v], &def.repr(), kind)?;
784                 st.variants = Variants::Single { index: v };
785
786                 if def.is_unsafe_cell() {
787                     let hide_niches = |scalar: &mut _| match scalar {
788                         Scalar::Initialized { value, valid_range } => {
789                             *valid_range = WrappingRange::full(value.size(dl))
790                         }
791                         // Already doesn't have any niches
792                         Scalar::Union { .. } => {}
793                     };
794                     match &mut st.abi {
795                         Abi::Uninhabited => {}
796                         Abi::Scalar(scalar) => hide_niches(scalar),
797                         Abi::ScalarPair(a, b) => {
798                             hide_niches(a);
799                             hide_niches(b);
800                         }
801                         Abi::Vector { element, count: _ } => hide_niches(element),
802                         Abi::Aggregate { sized: _ } => {}
803                     }
804                     st.largest_niche = None;
805                     return Ok(tcx.intern_layout(st));
806                 }
807
808                 let (start, end) = cx.tcx.layout_scalar_valid_range(def.did());
809                 match st.abi {
810                     Abi::Scalar(ref mut scalar) | Abi::ScalarPair(ref mut scalar, _) => {
811                         // the asserts ensure that we are not using the
812                         // `#[rustc_layout_scalar_valid_range(n)]`
813                         // attribute to widen the range of anything as that would probably
814                         // result in UB somewhere
815                         // FIXME(eddyb) the asserts are probably not needed,
816                         // as larger validity ranges would result in missed
817                         // optimizations, *not* wrongly assuming the inner
818                         // value is valid. e.g. unions enlarge validity ranges,
819                         // because the values may be uninitialized.
820                         if let Bound::Included(start) = start {
821                             // FIXME(eddyb) this might be incorrect - it doesn't
822                             // account for wrap-around (end < start) ranges.
823                             let valid_range = scalar.valid_range_mut();
824                             assert!(valid_range.start <= start);
825                             valid_range.start = start;
826                         }
827                         if let Bound::Included(end) = end {
828                             // FIXME(eddyb) this might be incorrect - it doesn't
829                             // account for wrap-around (end < start) ranges.
830                             let valid_range = scalar.valid_range_mut();
831                             assert!(valid_range.end >= end);
832                             valid_range.end = end;
833                         }
834
835                         // Update `largest_niche` if we have introduced a larger niche.
836                         let niche = Niche::from_scalar(dl, Size::ZERO, *scalar);
837                         if let Some(niche) = niche {
838                             match st.largest_niche {
839                                 Some(largest_niche) => {
840                                     // Replace the existing niche even if they're equal,
841                                     // because this one is at a lower offset.
842                                     if largest_niche.available(dl) <= niche.available(dl) {
843                                         st.largest_niche = Some(niche);
844                                     }
845                                 }
846                                 None => st.largest_niche = Some(niche),
847                             }
848                         }
849                     }
850                     _ => assert!(
851                         start == Bound::Unbounded && end == Bound::Unbounded,
852                         "nonscalar layout for layout_scalar_valid_range type {:?}: {:#?}",
853                         def,
854                         st,
855                     ),
856                 }
857
858                 return Ok(tcx.intern_layout(st));
859             }
860
861             // At this point, we have handled all unions and
862             // structs. (We have also handled univariant enums
863             // that allow representation optimization.)
864             assert!(def.is_enum());
865
866             // Until we've decided whether to use the tagged or
867             // niche filling LayoutS, we don't want to intern the
868             // variant layouts, so we can't store them in the
869             // overall LayoutS. Store the overall LayoutS
870             // and the variant LayoutSs here until then.
871             struct TmpLayout {
872                 layout: LayoutS<VariantIdx>,
873                 variants: IndexVec<VariantIdx, LayoutS<VariantIdx>>,
874             }
875
876             let calculate_niche_filling_layout =
877                 || -> Result<Option<TmpLayout>, LayoutError<'tcx>> {
878                     // The current code for niche-filling relies on variant indices
879                     // instead of actual discriminants, so enums with
880                     // explicit discriminants (RFC #2363) would misbehave.
881                     if def.repr().inhibit_enum_layout_opt()
882                         || def
883                             .variants()
884                             .iter_enumerated()
885                             .any(|(i, v)| v.discr != ty::VariantDiscr::Relative(i.as_u32()))
886                     {
887                         return Ok(None);
888                     }
889
890                     if variants.len() < 2 {
891                         return Ok(None);
892                     }
893
894                     let mut align = dl.aggregate_align;
895                     let mut variant_layouts = variants
896                         .iter_enumerated()
897                         .map(|(j, v)| {
898                             let mut st = univariant_uninterned(
899                                 cx,
900                                 ty,
901                                 v,
902                                 &def.repr(),
903                                 StructKind::AlwaysSized,
904                             )?;
905                             st.variants = Variants::Single { index: j };
906
907                             align = align.max(st.align);
908
909                             Ok(st)
910                         })
911                         .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
912
913                     let largest_variant_index = match variant_layouts
914                         .iter_enumerated()
915                         .max_by_key(|(_i, layout)| layout.size.bytes())
916                         .map(|(i, _layout)| i)
917                     {
918                         None => return Ok(None),
919                         Some(i) => i,
920                     };
921
922                     let all_indices = VariantIdx::new(0)..=VariantIdx::new(variants.len() - 1);
923                     let needs_disc = |index: VariantIdx| {
924                         index != largest_variant_index && !absent(&variants[index])
925                     };
926                     let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap()
927                         ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap();
928
929                     let count = niche_variants.size_hint().1.unwrap() as u128;
930
931                     // Find the field with the largest niche
932                     let (field_index, niche, (niche_start, niche_scalar)) = match variants
933                         [largest_variant_index]
934                         .iter()
935                         .enumerate()
936                         .filter_map(|(j, field)| Some((j, field.largest_niche?)))
937                         .max_by_key(|(_, niche)| niche.available(dl))
938                         .and_then(|(j, niche)| Some((j, niche, niche.reserve(cx, count)?)))
939                     {
940                         None => return Ok(None),
941                         Some(x) => x,
942                     };
943
944                     let niche_offset = niche.offset
945                         + variant_layouts[largest_variant_index].fields.offset(field_index);
946                     let niche_size = niche.value.size(dl);
947                     let size = variant_layouts[largest_variant_index].size.align_to(align.abi);
948
949                     let all_variants_fit =
950                         variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
951                             if i == largest_variant_index {
952                                 return true;
953                             }
954
955                             layout.largest_niche = None;
956
957                             if layout.size <= niche_offset {
958                                 // This variant will fit before the niche.
959                                 return true;
960                             }
961
962                             // Determine if it'll fit after the niche.
963                             let this_align = layout.align.abi;
964                             let this_offset = (niche_offset + niche_size).align_to(this_align);
965
966                             if this_offset + layout.size > size {
967                                 return false;
968                             }
969
970                             // It'll fit, but we need to make some adjustments.
971                             match layout.fields {
972                                 FieldsShape::Arbitrary { ref mut offsets, .. } => {
973                                     for (j, offset) in offsets.iter_mut().enumerate() {
974                                         if !variants[i][j].is_zst() {
975                                             *offset += this_offset;
976                                         }
977                                     }
978                                 }
979                                 _ => {
980                                     panic!("Layout of fields should be Arbitrary for variants")
981                                 }
982                             }
983
984                             // It can't be a Scalar or ScalarPair because the offset isn't 0.
985                             if !layout.abi.is_uninhabited() {
986                                 layout.abi = Abi::Aggregate { sized: true };
987                             }
988                             layout.size += this_offset;
989
990                             true
991                         });
992
993                     if !all_variants_fit {
994                         return Ok(None);
995                     }
996
997                     let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
998
999                     let others_zst = variant_layouts
1000                         .iter_enumerated()
1001                         .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
1002                     let same_size = size == variant_layouts[largest_variant_index].size;
1003                     let same_align = align == variant_layouts[largest_variant_index].align;
1004
1005                     let abi = if variant_layouts.iter().all(|v| v.abi.is_uninhabited()) {
1006                         Abi::Uninhabited
1007                     } else if same_size && same_align && others_zst {
1008                         match variant_layouts[largest_variant_index].abi {
1009                             // When the total alignment and size match, we can use the
1010                             // same ABI as the scalar variant with the reserved niche.
1011                             Abi::Scalar(_) => Abi::Scalar(niche_scalar),
1012                             Abi::ScalarPair(first, second) => {
1013                                 // Only the niche is guaranteed to be initialised,
1014                                 // so use union layouts for the other primitive.
1015                                 if niche_offset == Size::ZERO {
1016                                     Abi::ScalarPair(niche_scalar, second.to_union())
1017                                 } else {
1018                                     Abi::ScalarPair(first.to_union(), niche_scalar)
1019                                 }
1020                             }
1021                             _ => Abi::Aggregate { sized: true },
1022                         }
1023                     } else {
1024                         Abi::Aggregate { sized: true }
1025                     };
1026
1027                     let layout = LayoutS {
1028                         variants: Variants::Multiple {
1029                             tag: niche_scalar,
1030                             tag_encoding: TagEncoding::Niche {
1031                                 untagged_variant: largest_variant_index,
1032                                 niche_variants,
1033                                 niche_start,
1034                             },
1035                             tag_field: 0,
1036                             variants: IndexVec::new(),
1037                         },
1038                         fields: FieldsShape::Arbitrary {
1039                             offsets: vec![niche_offset],
1040                             memory_index: vec![0],
1041                         },
1042                         abi,
1043                         largest_niche,
1044                         size,
1045                         align,
1046                     };
1047
1048                     Ok(Some(TmpLayout { layout, variants: variant_layouts }))
1049                 };
1050
1051             let niche_filling_layout = calculate_niche_filling_layout()?;
1052
1053             let (mut min, mut max) = (i128::MAX, i128::MIN);
1054             let discr_type = def.repr().discr_type();
1055             let bits = Integer::from_attr(cx, discr_type).size().bits();
1056             for (i, discr) in def.discriminants(tcx) {
1057                 if variants[i].iter().any(|f| f.abi.is_uninhabited()) {
1058                     continue;
1059                 }
1060                 let mut x = discr.val as i128;
1061                 if discr_type.is_signed() {
1062                     // sign extend the raw representation to be an i128
1063                     x = (x << (128 - bits)) >> (128 - bits);
1064                 }
1065                 if x < min {
1066                     min = x;
1067                 }
1068                 if x > max {
1069                     max = x;
1070                 }
1071             }
1072             // We might have no inhabited variants, so pretend there's at least one.
1073             if (min, max) == (i128::MAX, i128::MIN) {
1074                 min = 0;
1075                 max = 0;
1076             }
1077             assert!(min <= max, "discriminant range is {}...{}", min, max);
1078             let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr(), min, max);
1079
1080             let mut align = dl.aggregate_align;
1081             let mut size = Size::ZERO;
1082
1083             // We're interested in the smallest alignment, so start large.
1084             let mut start_align = Align::from_bytes(256).unwrap();
1085             assert_eq!(Integer::for_align(dl, start_align), None);
1086
1087             // repr(C) on an enum tells us to make a (tag, union) layout,
1088             // so we need to grow the prefix alignment to be at least
1089             // the alignment of the union. (This value is used both for
1090             // determining the alignment of the overall enum, and the
1091             // determining the alignment of the payload after the tag.)
1092             let mut prefix_align = min_ity.align(dl).abi;
1093             if def.repr().c() {
1094                 for fields in &variants {
1095                     for field in fields {
1096                         prefix_align = prefix_align.max(field.align.abi);
1097                     }
1098                 }
1099             }
1100
1101             // Create the set of structs that represent each variant.
1102             let mut layout_variants = variants
1103                 .iter_enumerated()
1104                 .map(|(i, field_layouts)| {
1105                     let mut st = univariant_uninterned(
1106                         cx,
1107                         ty,
1108                         &field_layouts,
1109                         &def.repr(),
1110                         StructKind::Prefixed(min_ity.size(), prefix_align),
1111                     )?;
1112                     st.variants = Variants::Single { index: i };
1113                     // Find the first field we can't move later
1114                     // to make room for a larger discriminant.
1115                     for field in st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) {
1116                         if !field.is_zst() || field.align.abi.bytes() != 1 {
1117                             start_align = start_align.min(field.align.abi);
1118                             break;
1119                         }
1120                     }
1121                     size = cmp::max(size, st.size);
1122                     align = align.max(st.align);
1123                     Ok(st)
1124                 })
1125                 .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
1126
1127             // Align the maximum variant size to the largest alignment.
1128             size = size.align_to(align.abi);
1129
1130             if size.bytes() >= dl.obj_size_bound() {
1131                 return Err(LayoutError::SizeOverflow(ty));
1132             }
1133
1134             let typeck_ity = Integer::from_attr(dl, def.repr().discr_type());
1135             if typeck_ity < min_ity {
1136                 // It is a bug if Layout decided on a greater discriminant size than typeck for
1137                 // some reason at this point (based on values discriminant can take on). Mostly
1138                 // because this discriminant will be loaded, and then stored into variable of
1139                 // type calculated by typeck. Consider such case (a bug): typeck decided on
1140                 // byte-sized discriminant, but layout thinks we need a 16-bit to store all
1141                 // discriminant values. That would be a bug, because then, in codegen, in order
1142                 // to store this 16-bit discriminant into 8-bit sized temporary some of the
1143                 // space necessary to represent would have to be discarded (or layout is wrong
1144                 // on thinking it needs 16 bits)
1145                 bug!(
1146                     "layout decided on a larger discriminant type ({:?}) than typeck ({:?})",
1147                     min_ity,
1148                     typeck_ity
1149                 );
1150                 // However, it is fine to make discr type however large (as an optimisation)
1151                 // after this point â€“ we’ll just truncate the value we load in codegen.
1152             }
1153
1154             // Check to see if we should use a different type for the
1155             // discriminant. We can safely use a type with the same size
1156             // as the alignment of the first field of each variant.
1157             // We increase the size of the discriminant to avoid LLVM copying
1158             // padding when it doesn't need to. This normally causes unaligned
1159             // load/stores and excessive memcpy/memset operations. By using a
1160             // bigger integer size, LLVM can be sure about its contents and
1161             // won't be so conservative.
1162
1163             // Use the initial field alignment
1164             let mut ity = if def.repr().c() || def.repr().int.is_some() {
1165                 min_ity
1166             } else {
1167                 Integer::for_align(dl, start_align).unwrap_or(min_ity)
1168             };
1169
1170             // If the alignment is not larger than the chosen discriminant size,
1171             // don't use the alignment as the final size.
1172             if ity <= min_ity {
1173                 ity = min_ity;
1174             } else {
1175                 // Patch up the variants' first few fields.
1176                 let old_ity_size = min_ity.size();
1177                 let new_ity_size = ity.size();
1178                 for variant in &mut layout_variants {
1179                     match variant.fields {
1180                         FieldsShape::Arbitrary { ref mut offsets, .. } => {
1181                             for i in offsets {
1182                                 if *i <= old_ity_size {
1183                                     assert_eq!(*i, old_ity_size);
1184                                     *i = new_ity_size;
1185                                 }
1186                             }
1187                             // We might be making the struct larger.
1188                             if variant.size <= old_ity_size {
1189                                 variant.size = new_ity_size;
1190                             }
1191                         }
1192                         _ => bug!(),
1193                     }
1194                 }
1195             }
1196
1197             let tag_mask = ity.size().unsigned_int_max();
1198             let tag = Scalar::Initialized {
1199                 value: Int(ity, signed),
1200                 valid_range: WrappingRange {
1201                     start: (min as u128 & tag_mask),
1202                     end: (max as u128 & tag_mask),
1203                 },
1204             };
1205             let mut abi = Abi::Aggregate { sized: true };
1206
1207             if layout_variants.iter().all(|v| v.abi.is_uninhabited()) {
1208                 abi = Abi::Uninhabited;
1209             } else if tag.size(dl) == size {
1210                 // Make sure we only use scalar layout when the enum is entirely its
1211                 // own tag (i.e. it has no padding nor any non-ZST variant fields).
1212                 abi = Abi::Scalar(tag);
1213             } else {
1214                 // Try to use a ScalarPair for all tagged enums.
1215                 let mut common_prim = None;
1216                 let mut common_prim_initialized_in_all_variants = true;
1217                 for (field_layouts, layout_variant) in iter::zip(&variants, &layout_variants) {
1218                     let FieldsShape::Arbitrary { ref offsets, .. } = layout_variant.fields else {
1219                             bug!();
1220                         };
1221                     let mut fields = iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst());
1222                     let (field, offset) = match (fields.next(), fields.next()) {
1223                         (None, None) => {
1224                             common_prim_initialized_in_all_variants = false;
1225                             continue;
1226                         }
1227                         (Some(pair), None) => pair,
1228                         _ => {
1229                             common_prim = None;
1230                             break;
1231                         }
1232                     };
1233                     let prim = match field.abi {
1234                         Abi::Scalar(scalar) => {
1235                             common_prim_initialized_in_all_variants &=
1236                                 matches!(scalar, Scalar::Initialized { .. });
1237                             scalar.primitive()
1238                         }
1239                         _ => {
1240                             common_prim = None;
1241                             break;
1242                         }
1243                     };
1244                     if let Some(pair) = common_prim {
1245                         // This is pretty conservative. We could go fancier
1246                         // by conflating things like i32 and u32, or even
1247                         // realising that (u8, u8) could just cohabit with
1248                         // u16 or even u32.
1249                         if pair != (prim, offset) {
1250                             common_prim = None;
1251                             break;
1252                         }
1253                     } else {
1254                         common_prim = Some((prim, offset));
1255                     }
1256                 }
1257                 if let Some((prim, offset)) = common_prim {
1258                     let prim_scalar = if common_prim_initialized_in_all_variants {
1259                         scalar_unit(prim)
1260                     } else {
1261                         // Common prim might be uninit.
1262                         Scalar::Union { value: prim }
1263                     };
1264                     let pair = scalar_pair(cx, tag, prim_scalar);
1265                     let pair_offsets = match pair.fields {
1266                         FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
1267                             assert_eq!(memory_index, &[0, 1]);
1268                             offsets
1269                         }
1270                         _ => bug!(),
1271                     };
1272                     if pair_offsets[0] == Size::ZERO
1273                         && pair_offsets[1] == *offset
1274                         && align == pair.align
1275                         && size == pair.size
1276                     {
1277                         // We can use `ScalarPair` only when it matches our
1278                         // already computed layout (including `#[repr(C)]`).
1279                         abi = pair.abi;
1280                     }
1281                 }
1282             }
1283
1284             // If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
1285             // variants to ensure they are consistent. This is because a downcast is
1286             // semantically a NOP, and thus should not affect layout.
1287             if matches!(abi, Abi::Scalar(..) | Abi::ScalarPair(..)) {
1288                 for variant in &mut layout_variants {
1289                     // We only do this for variants with fields; the others are not accessed anyway.
1290                     // Also do not overwrite any already existing "clever" ABIs.
1291                     if variant.fields.count() > 0 && matches!(variant.abi, Abi::Aggregate { .. }) {
1292                         variant.abi = abi;
1293                         // Also need to bump up the size and alignment, so that the entire value fits in here.
1294                         variant.size = cmp::max(variant.size, size);
1295                         variant.align.abi = cmp::max(variant.align.abi, align.abi);
1296                     }
1297                 }
1298             }
1299
1300             let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
1301
1302             let tagged_layout = LayoutS {
1303                 variants: Variants::Multiple {
1304                     tag,
1305                     tag_encoding: TagEncoding::Direct,
1306                     tag_field: 0,
1307                     variants: IndexVec::new(),
1308                 },
1309                 fields: FieldsShape::Arbitrary { offsets: vec![Size::ZERO], memory_index: vec![0] },
1310                 largest_niche,
1311                 abi,
1312                 align,
1313                 size,
1314             };
1315
1316             let tagged_layout = TmpLayout { layout: tagged_layout, variants: layout_variants };
1317
1318             let mut best_layout = match (tagged_layout, niche_filling_layout) {
1319                 (tl, Some(nl)) => {
1320                     // Pick the smaller layout; otherwise,
1321                     // pick the layout with the larger niche; otherwise,
1322                     // pick tagged as it has simpler codegen.
1323                     use Ordering::*;
1324                     let niche_size = |tmp_l: &TmpLayout| {
1325                         tmp_l.layout.largest_niche.map_or(0, |n| n.available(dl))
1326                     };
1327                     match (
1328                         tl.layout.size.cmp(&nl.layout.size),
1329                         niche_size(&tl).cmp(&niche_size(&nl)),
1330                     ) {
1331                         (Greater, _) => nl,
1332                         (Equal, Less) => nl,
1333                         _ => tl,
1334                     }
1335                 }
1336                 (tl, None) => tl,
1337             };
1338
1339             // Now we can intern the variant layouts and store them in the enum layout.
1340             best_layout.layout.variants = match best_layout.layout.variants {
1341                 Variants::Multiple { tag, tag_encoding, tag_field, .. } => Variants::Multiple {
1342                     tag,
1343                     tag_encoding,
1344                     tag_field,
1345                     variants: best_layout.variants,
1346                 },
1347                 _ => bug!(),
1348             };
1349
1350             tcx.intern_layout(best_layout.layout)
1351         }
1352
1353         // Types with no meaningful known layout.
1354         ty::Projection(_) | ty::Opaque(..) => {
1355             // NOTE(eddyb) `layout_of` query should've normalized these away,
1356             // if that was possible, so there's no reason to try again here.
1357             return Err(LayoutError::Unknown(ty));
1358         }
1359
1360         ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Infer(_) => {
1361             bug!("Layout::compute: unexpected type `{}`", ty)
1362         }
1363
1364         ty::Bound(..) | ty::Param(_) | ty::Error(_) => {
1365             return Err(LayoutError::Unknown(ty));
1366         }
1367     })
1368 }
1369
1370 /// Overlap eligibility and variant assignment for each GeneratorSavedLocal.
1371 #[derive(Clone, Debug, PartialEq)]
1372 enum SavedLocalEligibility {
1373     Unassigned,
1374     Assigned(VariantIdx),
1375     // FIXME: Use newtype_index so we aren't wasting bytes
1376     Ineligible(Option<u32>),
1377 }
1378
1379 // When laying out generators, we divide our saved local fields into two
1380 // categories: overlap-eligible and overlap-ineligible.
1381 //
1382 // Those fields which are ineligible for overlap go in a "prefix" at the
1383 // beginning of the layout, and always have space reserved for them.
1384 //
1385 // Overlap-eligible fields are only assigned to one variant, so we lay
1386 // those fields out for each variant and put them right after the
1387 // prefix.
1388 //
1389 // Finally, in the layout details, we point to the fields from the
1390 // variants they are assigned to. It is possible for some fields to be
1391 // included in multiple variants. No field ever "moves around" in the
1392 // layout; its offset is always the same.
1393 //
1394 // Also included in the layout are the upvars and the discriminant.
1395 // These are included as fields on the "outer" layout; they are not part
1396 // of any variant.
1397
1398 /// Compute the eligibility and assignment of each local.
1399 fn generator_saved_local_eligibility<'tcx>(
1400     info: &GeneratorLayout<'tcx>,
1401 ) -> (BitSet<GeneratorSavedLocal>, IndexVec<GeneratorSavedLocal, SavedLocalEligibility>) {
1402     use SavedLocalEligibility::*;
1403
1404     let mut assignments: IndexVec<GeneratorSavedLocal, SavedLocalEligibility> =
1405         IndexVec::from_elem_n(Unassigned, info.field_tys.len());
1406
1407     // The saved locals not eligible for overlap. These will get
1408     // "promoted" to the prefix of our generator.
1409     let mut ineligible_locals = BitSet::new_empty(info.field_tys.len());
1410
1411     // Figure out which of our saved locals are fields in only
1412     // one variant. The rest are deemed ineligible for overlap.
1413     for (variant_index, fields) in info.variant_fields.iter_enumerated() {
1414         for local in fields {
1415             match assignments[*local] {
1416                 Unassigned => {
1417                     assignments[*local] = Assigned(variant_index);
1418                 }
1419                 Assigned(idx) => {
1420                     // We've already seen this local at another suspension
1421                     // point, so it is no longer a candidate.
1422                     trace!(
1423                         "removing local {:?} in >1 variant ({:?}, {:?})",
1424                         local,
1425                         variant_index,
1426                         idx
1427                     );
1428                     ineligible_locals.insert(*local);
1429                     assignments[*local] = Ineligible(None);
1430                 }
1431                 Ineligible(_) => {}
1432             }
1433         }
1434     }
1435
1436     // Next, check every pair of eligible locals to see if they
1437     // conflict.
1438     for local_a in info.storage_conflicts.rows() {
1439         let conflicts_a = info.storage_conflicts.count(local_a);
1440         if ineligible_locals.contains(local_a) {
1441             continue;
1442         }
1443
1444         for local_b in info.storage_conflicts.iter(local_a) {
1445             // local_a and local_b are storage live at the same time, therefore they
1446             // cannot overlap in the generator layout. The only way to guarantee
1447             // this is if they are in the same variant, or one is ineligible
1448             // (which means it is stored in every variant).
1449             if ineligible_locals.contains(local_b) || assignments[local_a] == assignments[local_b] {
1450                 continue;
1451             }
1452
1453             // If they conflict, we will choose one to make ineligible.
1454             // This is not always optimal; it's just a greedy heuristic that
1455             // seems to produce good results most of the time.
1456             let conflicts_b = info.storage_conflicts.count(local_b);
1457             let (remove, other) =
1458                 if conflicts_a > conflicts_b { (local_a, local_b) } else { (local_b, local_a) };
1459             ineligible_locals.insert(remove);
1460             assignments[remove] = Ineligible(None);
1461             trace!("removing local {:?} due to conflict with {:?}", remove, other);
1462         }
1463     }
1464
1465     // Count the number of variants in use. If only one of them, then it is
1466     // impossible to overlap any locals in our layout. In this case it's
1467     // always better to make the remaining locals ineligible, so we can
1468     // lay them out with the other locals in the prefix and eliminate
1469     // unnecessary padding bytes.
1470     {
1471         let mut used_variants = BitSet::new_empty(info.variant_fields.len());
1472         for assignment in &assignments {
1473             if let Assigned(idx) = assignment {
1474                 used_variants.insert(*idx);
1475             }
1476         }
1477         if used_variants.count() < 2 {
1478             for assignment in assignments.iter_mut() {
1479                 *assignment = Ineligible(None);
1480             }
1481             ineligible_locals.insert_all();
1482         }
1483     }
1484
1485     // Write down the order of our locals that will be promoted to the prefix.
1486     {
1487         for (idx, local) in ineligible_locals.iter().enumerate() {
1488             assignments[local] = Ineligible(Some(idx as u32));
1489         }
1490     }
1491     debug!("generator saved local assignments: {:?}", assignments);
1492
1493     (ineligible_locals, assignments)
1494 }
1495
1496 /// Compute the full generator layout.
1497 fn generator_layout<'tcx>(
1498     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
1499     ty: Ty<'tcx>,
1500     def_id: hir::def_id::DefId,
1501     substs: SubstsRef<'tcx>,
1502 ) -> Result<Layout<'tcx>, LayoutError<'tcx>> {
1503     use SavedLocalEligibility::*;
1504     let tcx = cx.tcx;
1505     let subst_field = |ty: Ty<'tcx>| EarlyBinder(ty).subst(tcx, substs);
1506
1507     let Some(info) = tcx.generator_layout(def_id) else {
1508             return Err(LayoutError::Unknown(ty));
1509         };
1510     let (ineligible_locals, assignments) = generator_saved_local_eligibility(&info);
1511
1512     // Build a prefix layout, including "promoting" all ineligible
1513     // locals as part of the prefix. We compute the layout of all of
1514     // these fields at once to get optimal packing.
1515     let tag_index = substs.as_generator().prefix_tys().count();
1516
1517     // `info.variant_fields` already accounts for the reserved variants, so no need to add them.
1518     let max_discr = (info.variant_fields.len() - 1) as u128;
1519     let discr_int = Integer::fit_unsigned(max_discr);
1520     let discr_int_ty = discr_int.to_ty(tcx, false);
1521     let tag = Scalar::Initialized {
1522         value: Primitive::Int(discr_int, false),
1523         valid_range: WrappingRange { start: 0, end: max_discr },
1524     };
1525     let tag_layout = cx.tcx.intern_layout(LayoutS::scalar(cx, tag));
1526     let tag_layout = TyAndLayout { ty: discr_int_ty, layout: tag_layout };
1527
1528     let promoted_layouts = ineligible_locals
1529         .iter()
1530         .map(|local| subst_field(info.field_tys[local]))
1531         .map(|ty| tcx.mk_maybe_uninit(ty))
1532         .map(|ty| cx.layout_of(ty));
1533     let prefix_layouts = substs
1534         .as_generator()
1535         .prefix_tys()
1536         .map(|ty| cx.layout_of(ty))
1537         .chain(iter::once(Ok(tag_layout)))
1538         .chain(promoted_layouts)
1539         .collect::<Result<Vec<_>, _>>()?;
1540     let prefix = univariant_uninterned(
1541         cx,
1542         ty,
1543         &prefix_layouts,
1544         &ReprOptions::default(),
1545         StructKind::AlwaysSized,
1546     )?;
1547
1548     let (prefix_size, prefix_align) = (prefix.size, prefix.align);
1549
1550     // Split the prefix layout into the "outer" fields (upvars and
1551     // discriminant) and the "promoted" fields. Promoted fields will
1552     // get included in each variant that requested them in
1553     // GeneratorLayout.
1554     debug!("prefix = {:#?}", prefix);
1555     let (outer_fields, promoted_offsets, promoted_memory_index) = match prefix.fields {
1556         FieldsShape::Arbitrary { mut offsets, memory_index } => {
1557             let mut inverse_memory_index = invert_mapping(&memory_index);
1558
1559             // "a" (`0..b_start`) and "b" (`b_start..`) correspond to
1560             // "outer" and "promoted" fields respectively.
1561             let b_start = (tag_index + 1) as u32;
1562             let offsets_b = offsets.split_off(b_start as usize);
1563             let offsets_a = offsets;
1564
1565             // Disentangle the "a" and "b" components of `inverse_memory_index`
1566             // by preserving the order but keeping only one disjoint "half" each.
1567             // FIXME(eddyb) build a better abstraction for permutations, if possible.
1568             let inverse_memory_index_b: Vec<_> =
1569                 inverse_memory_index.iter().filter_map(|&i| i.checked_sub(b_start)).collect();
1570             inverse_memory_index.retain(|&i| i < b_start);
1571             let inverse_memory_index_a = inverse_memory_index;
1572
1573             // Since `inverse_memory_index_{a,b}` each only refer to their
1574             // respective fields, they can be safely inverted
1575             let memory_index_a = invert_mapping(&inverse_memory_index_a);
1576             let memory_index_b = invert_mapping(&inverse_memory_index_b);
1577
1578             let outer_fields =
1579                 FieldsShape::Arbitrary { offsets: offsets_a, memory_index: memory_index_a };
1580             (outer_fields, offsets_b, memory_index_b)
1581         }
1582         _ => bug!(),
1583     };
1584
1585     let mut size = prefix.size;
1586     let mut align = prefix.align;
1587     let variants = info
1588         .variant_fields
1589         .iter_enumerated()
1590         .map(|(index, variant_fields)| {
1591             // Only include overlap-eligible fields when we compute our variant layout.
1592             let variant_only_tys = variant_fields
1593                 .iter()
1594                 .filter(|local| match assignments[**local] {
1595                     Unassigned => bug!(),
1596                     Assigned(v) if v == index => true,
1597                     Assigned(_) => bug!("assignment does not match variant"),
1598                     Ineligible(_) => false,
1599                 })
1600                 .map(|local| subst_field(info.field_tys[*local]));
1601
1602             let mut variant = univariant_uninterned(
1603                 cx,
1604                 ty,
1605                 &variant_only_tys.map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
1606                 &ReprOptions::default(),
1607                 StructKind::Prefixed(prefix_size, prefix_align.abi),
1608             )?;
1609             variant.variants = Variants::Single { index };
1610
1611             let FieldsShape::Arbitrary { offsets, memory_index } = variant.fields else {
1612                     bug!();
1613                 };
1614
1615             // Now, stitch the promoted and variant-only fields back together in
1616             // the order they are mentioned by our GeneratorLayout.
1617             // Because we only use some subset (that can differ between variants)
1618             // of the promoted fields, we can't just pick those elements of the
1619             // `promoted_memory_index` (as we'd end up with gaps).
1620             // So instead, we build an "inverse memory_index", as if all of the
1621             // promoted fields were being used, but leave the elements not in the
1622             // subset as `INVALID_FIELD_IDX`, which we can filter out later to
1623             // obtain a valid (bijective) mapping.
1624             const INVALID_FIELD_IDX: u32 = !0;
1625             let mut combined_inverse_memory_index =
1626                 vec![INVALID_FIELD_IDX; promoted_memory_index.len() + memory_index.len()];
1627             let mut offsets_and_memory_index = iter::zip(offsets, memory_index);
1628             let combined_offsets = variant_fields
1629                 .iter()
1630                 .enumerate()
1631                 .map(|(i, local)| {
1632                     let (offset, memory_index) = match assignments[*local] {
1633                         Unassigned => bug!(),
1634                         Assigned(_) => {
1635                             let (offset, memory_index) = offsets_and_memory_index.next().unwrap();
1636                             (offset, promoted_memory_index.len() as u32 + memory_index)
1637                         }
1638                         Ineligible(field_idx) => {
1639                             let field_idx = field_idx.unwrap() as usize;
1640                             (promoted_offsets[field_idx], promoted_memory_index[field_idx])
1641                         }
1642                     };
1643                     combined_inverse_memory_index[memory_index as usize] = i as u32;
1644                     offset
1645                 })
1646                 .collect();
1647
1648             // Remove the unused slots and invert the mapping to obtain the
1649             // combined `memory_index` (also see previous comment).
1650             combined_inverse_memory_index.retain(|&i| i != INVALID_FIELD_IDX);
1651             let combined_memory_index = invert_mapping(&combined_inverse_memory_index);
1652
1653             variant.fields = FieldsShape::Arbitrary {
1654                 offsets: combined_offsets,
1655                 memory_index: combined_memory_index,
1656             };
1657
1658             size = size.max(variant.size);
1659             align = align.max(variant.align);
1660             Ok(variant)
1661         })
1662         .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
1663
1664     size = size.align_to(align.abi);
1665
1666     let abi = if prefix.abi.is_uninhabited() || variants.iter().all(|v| v.abi().is_uninhabited()) {
1667         Abi::Uninhabited
1668     } else {
1669         Abi::Aggregate { sized: true }
1670     };
1671
1672     let layout = tcx.intern_layout(LayoutS {
1673         variants: Variants::Multiple {
1674             tag,
1675             tag_encoding: TagEncoding::Direct,
1676             tag_field: tag_index,
1677             variants,
1678         },
1679         fields: outer_fields,
1680         abi,
1681         largest_niche: prefix.largest_niche,
1682         size,
1683         align,
1684     });
1685     debug!("generator layout ({:?}): {:#?}", ty, layout);
1686     Ok(layout)
1687 }
1688
1689 /// This is invoked by the `layout_of` query to record the final
1690 /// layout of each type.
1691 #[inline(always)]
1692 fn record_layout_for_printing<'tcx>(cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, layout: TyAndLayout<'tcx>) {
1693     // If we are running with `-Zprint-type-sizes`, maybe record layouts
1694     // for dumping later.
1695     if cx.tcx.sess.opts.unstable_opts.print_type_sizes {
1696         record_layout_for_printing_outlined(cx, layout)
1697     }
1698 }
1699
1700 fn record_layout_for_printing_outlined<'tcx>(
1701     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
1702     layout: TyAndLayout<'tcx>,
1703 ) {
1704     // Ignore layouts that are done with non-empty environments or
1705     // non-monomorphic layouts, as the user only wants to see the stuff
1706     // resulting from the final codegen session.
1707     if layout.ty.has_non_region_param() || !cx.param_env.caller_bounds().is_empty() {
1708         return;
1709     }
1710
1711     // (delay format until we actually need it)
1712     let record = |kind, packed, opt_discr_size, variants| {
1713         let type_desc = format!("{:?}", layout.ty);
1714         cx.tcx.sess.code_stats.record_type_size(
1715             kind,
1716             type_desc,
1717             layout.align.abi,
1718             layout.size,
1719             packed,
1720             opt_discr_size,
1721             variants,
1722         );
1723     };
1724
1725     let adt_def = match *layout.ty.kind() {
1726         ty::Adt(ref adt_def, _) => {
1727             debug!("print-type-size t: `{:?}` process adt", layout.ty);
1728             adt_def
1729         }
1730
1731         ty::Closure(..) => {
1732             debug!("print-type-size t: `{:?}` record closure", layout.ty);
1733             record(DataTypeKind::Closure, false, None, vec![]);
1734             return;
1735         }
1736
1737         _ => {
1738             debug!("print-type-size t: `{:?}` skip non-nominal", layout.ty);
1739             return;
1740         }
1741     };
1742
1743     let adt_kind = adt_def.adt_kind();
1744     let adt_packed = adt_def.repr().pack.is_some();
1745
1746     let build_variant_info = |n: Option<Symbol>, flds: &[Symbol], layout: TyAndLayout<'tcx>| {
1747         let mut min_size = Size::ZERO;
1748         let field_info: Vec<_> = flds
1749             .iter()
1750             .enumerate()
1751             .map(|(i, &name)| {
1752                 let field_layout = layout.field(cx, i);
1753                 let offset = layout.fields.offset(i);
1754                 let field_end = offset + field_layout.size;
1755                 if min_size < field_end {
1756                     min_size = field_end;
1757                 }
1758                 FieldInfo {
1759                     name,
1760                     offset: offset.bytes(),
1761                     size: field_layout.size.bytes(),
1762                     align: field_layout.align.abi.bytes(),
1763                 }
1764             })
1765             .collect();
1766
1767         VariantInfo {
1768             name: n,
1769             kind: if layout.is_unsized() { SizeKind::Min } else { SizeKind::Exact },
1770             align: layout.align.abi.bytes(),
1771             size: if min_size.bytes() == 0 { layout.size.bytes() } else { min_size.bytes() },
1772             fields: field_info,
1773         }
1774     };
1775
1776     match layout.variants {
1777         Variants::Single { index } => {
1778             if !adt_def.variants().is_empty() && layout.fields != FieldsShape::Primitive {
1779                 debug!("print-type-size `{:#?}` variant {}", layout, adt_def.variant(index).name);
1780                 let variant_def = &adt_def.variant(index);
1781                 let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
1782                 record(
1783                     adt_kind.into(),
1784                     adt_packed,
1785                     None,
1786                     vec![build_variant_info(Some(variant_def.name), &fields, layout)],
1787                 );
1788             } else {
1789                 // (This case arises for *empty* enums; so give it
1790                 // zero variants.)
1791                 record(adt_kind.into(), adt_packed, None, vec![]);
1792             }
1793         }
1794
1795         Variants::Multiple { tag, ref tag_encoding, .. } => {
1796             debug!(
1797                 "print-type-size `{:#?}` adt general variants def {}",
1798                 layout.ty,
1799                 adt_def.variants().len()
1800             );
1801             let variant_infos: Vec<_> = adt_def
1802                 .variants()
1803                 .iter_enumerated()
1804                 .map(|(i, variant_def)| {
1805                     let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect();
1806                     build_variant_info(Some(variant_def.name), &fields, layout.for_variant(cx, i))
1807                 })
1808                 .collect();
1809             record(
1810                 adt_kind.into(),
1811                 adt_packed,
1812                 match tag_encoding {
1813                     TagEncoding::Direct => Some(tag.size(cx)),
1814                     _ => None,
1815                 },
1816                 variant_infos,
1817             );
1818         }
1819     }
1820 }