]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_abi/src/layout.rs
Rollup merge of #106712 - Ezrashaw:impl-ref-trait, r=estebank
[rust.git] / compiler / rustc_abi / src / layout.rs
1 use super::*;
2 use std::{
3     borrow::Borrow,
4     cmp,
5     fmt::Debug,
6     iter,
7     ops::{Bound, Deref},
8 };
9
10 #[cfg(feature = "randomize")]
11 use rand::{seq::SliceRandom, SeedableRng};
12 #[cfg(feature = "randomize")]
13 use rand_xoshiro::Xoshiro128StarStar;
14
15 use tracing::debug;
16
17 // Invert a bijective mapping, i.e. `invert(map)[y] = x` if `map[x] = y`.
18 // This is used to go between `memory_index` (source field order to memory order)
19 // and `inverse_memory_index` (memory order to source field order).
20 // See also `FieldsShape::Arbitrary::memory_index` for more details.
21 // FIXME(eddyb) build a better abstraction for permutations, if possible.
22 fn invert_mapping(map: &[u32]) -> Vec<u32> {
23     let mut inverse = vec![0; map.len()];
24     for i in 0..map.len() {
25         inverse[map[i] as usize] = i as u32;
26     }
27     inverse
28 }
29
30 pub trait LayoutCalculator {
31     type TargetDataLayoutRef: Borrow<TargetDataLayout>;
32
33     fn delay_bug(&self, txt: &str);
34     fn current_data_layout(&self) -> Self::TargetDataLayoutRef;
35
36     fn scalar_pair<V: Idx>(&self, a: Scalar, b: Scalar) -> LayoutS<V> {
37         let dl = self.current_data_layout();
38         let dl = dl.borrow();
39         let b_align = b.align(dl);
40         let align = a.align(dl).max(b_align).max(dl.aggregate_align);
41         let b_offset = a.size(dl).align_to(b_align.abi);
42         let size = (b_offset + b.size(dl)).align_to(align.abi);
43
44         // HACK(nox): We iter on `b` and then `a` because `max_by_key`
45         // returns the last maximum.
46         let largest_niche = Niche::from_scalar(dl, b_offset, b)
47             .into_iter()
48             .chain(Niche::from_scalar(dl, Size::ZERO, a))
49             .max_by_key(|niche| niche.available(dl));
50
51         LayoutS {
52             variants: Variants::Single { index: V::new(0) },
53             fields: FieldsShape::Arbitrary {
54                 offsets: vec![Size::ZERO, b_offset],
55                 memory_index: vec![0, 1],
56             },
57             abi: Abi::ScalarPair(a, b),
58             largest_niche,
59             align,
60             size,
61         }
62     }
63
64     fn univariant<'a, V: Idx, F: Deref<Target = &'a LayoutS<V>> + Debug>(
65         &self,
66         dl: &TargetDataLayout,
67         fields: &[F],
68         repr: &ReprOptions,
69         kind: StructKind,
70     ) -> Option<LayoutS<V>> {
71         let pack = repr.pack;
72         let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };
73         let mut inverse_memory_index: Vec<u32> = (0..fields.len() as u32).collect();
74         let optimize = !repr.inhibit_struct_field_reordering_opt();
75         if optimize {
76             let end =
77                 if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() };
78             let optimizing = &mut inverse_memory_index[..end];
79             let effective_field_align = |f: &F| {
80                 if let Some(pack) = pack {
81                     // return the packed alignment in bytes
82                     f.align.abi.min(pack).bytes()
83                 } else {
84                     // returns log2(effective-align).
85                     // This is ok since `pack` applies to all fields equally.
86                     // The calculation assumes that size is an integer multiple of align, except for ZSTs.
87                     //
88                     // group [u8; 4] with align-4 or [u8; 6] with align-2 fields
89                     f.align.abi.bytes().max(f.size.bytes()).trailing_zeros() as u64
90                 }
91             };
92
93             // If `-Z randomize-layout` was enabled for the type definition we can shuffle
94             // the field ordering to try and catch some code making assumptions about layouts
95             // we don't guarantee
96             if repr.can_randomize_type_layout() && cfg!(feature = "randomize") {
97                 #[cfg(feature = "randomize")]
98                 {
99                     // `ReprOptions.layout_seed` is a deterministic seed that we can use to
100                     // randomize field ordering with
101                     let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed);
102
103                     // Shuffle the ordering of the fields
104                     optimizing.shuffle(&mut rng);
105                 }
106                 // Otherwise we just leave things alone and actually optimize the type's fields
107             } else {
108                 match kind {
109                     StructKind::AlwaysSized | StructKind::MaybeUnsized => {
110                         optimizing.sort_by_key(|&x| {
111                             // Place ZSTs first to avoid "interesting offsets",
112                             // especially with only one or two non-ZST fields.
113                             // Then place largest alignments first, largest niches within an alignment group last
114                             let f = &fields[x as usize];
115                             let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
116                             (!f.is_zst(), cmp::Reverse(effective_field_align(f)), niche_size)
117                         });
118                     }
119
120                     StructKind::Prefixed(..) => {
121                         // Sort in ascending alignment so that the layout stays optimal
122                         // regardless of the prefix.
123                         // And put the largest niche in an alignment group at the end
124                         // so it can be used as discriminant in jagged enums
125                         optimizing.sort_by_key(|&x| {
126                             let f = &fields[x as usize];
127                             let niche_size = f.largest_niche.map_or(0, |n| n.available(dl));
128                             (effective_field_align(f), niche_size)
129                         });
130                     }
131                 }
132
133                 // FIXME(Kixiron): We can always shuffle fields within a given alignment class
134                 //                 regardless of the status of `-Z randomize-layout`
135             }
136         }
137         // inverse_memory_index holds field indices by increasing memory offset.
138         // That is, if field 5 has offset 0, the first element of inverse_memory_index is 5.
139         // We now write field offsets to the corresponding offset slot;
140         // field 5 with offset 0 puts 0 in offsets[5].
141         // At the bottom of this function, we invert `inverse_memory_index` to
142         // produce `memory_index` (see `invert_mapping`).
143         let mut sized = true;
144         let mut offsets = vec![Size::ZERO; fields.len()];
145         let mut offset = Size::ZERO;
146         let mut largest_niche = None;
147         let mut largest_niche_available = 0;
148         if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
149             let prefix_align =
150                 if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align };
151             align = align.max(AbiAndPrefAlign::new(prefix_align));
152             offset = prefix_size.align_to(prefix_align);
153         }
154         for &i in &inverse_memory_index {
155             let field = &fields[i as usize];
156             if !sized {
157                 self.delay_bug(&format!(
158                     "univariant: field #{} comes after unsized field",
159                     offsets.len(),
160                 ));
161             }
162
163             if field.is_unsized() {
164                 sized = false;
165             }
166
167             // Invariant: offset < dl.obj_size_bound() <= 1<<61
168             let field_align = if let Some(pack) = pack {
169                 field.align.min(AbiAndPrefAlign::new(pack))
170             } else {
171                 field.align
172             };
173             offset = offset.align_to(field_align.abi);
174             align = align.max(field_align);
175
176             debug!("univariant offset: {:?} field: {:#?}", offset, field);
177             offsets[i as usize] = offset;
178
179             if let Some(mut niche) = field.largest_niche {
180                 let available = niche.available(dl);
181                 if available > largest_niche_available {
182                     largest_niche_available = available;
183                     niche.offset += offset;
184                     largest_niche = Some(niche);
185                 }
186             }
187
188             offset = offset.checked_add(field.size, dl)?;
189         }
190         if let Some(repr_align) = repr.align {
191             align = align.max(AbiAndPrefAlign::new(repr_align));
192         }
193         debug!("univariant min_size: {:?}", offset);
194         let min_size = offset;
195         // As stated above, inverse_memory_index holds field indices by increasing offset.
196         // This makes it an already-sorted view of the offsets vec.
197         // To invert it, consider:
198         // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0.
199         // Field 5 would be the first element, so memory_index is i:
200         // Note: if we didn't optimize, it's already right.
201         let memory_index =
202             if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index };
203         let size = min_size.align_to(align.abi);
204         let mut abi = Abi::Aggregate { sized };
205         // Unpack newtype ABIs and find scalar pairs.
206         if sized && size.bytes() > 0 {
207             // All other fields must be ZSTs.
208             let mut non_zst_fields = fields.iter().enumerate().filter(|&(_, f)| !f.is_zst());
209
210             match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
211                 // We have exactly one non-ZST field.
212                 (Some((i, field)), None, None) => {
213                     // Field fills the struct and it has a scalar or scalar pair ABI.
214                     if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size
215                     {
216                         match field.abi {
217                             // For plain scalars, or vectors of them, we can't unpack
218                             // newtypes for `#[repr(C)]`, as that affects C ABIs.
219                             Abi::Scalar(_) | Abi::Vector { .. } if optimize => {
220                                 abi = field.abi;
221                             }
222                             // But scalar pairs are Rust-specific and get
223                             // treated as aggregates by C ABIs anyway.
224                             Abi::ScalarPair(..) => {
225                                 abi = field.abi;
226                             }
227                             _ => {}
228                         }
229                     }
230                 }
231
232                 // Two non-ZST fields, and they're both scalars.
233                 (Some((i, a)), Some((j, b)), None) => {
234                     match (a.abi, b.abi) {
235                         (Abi::Scalar(a), Abi::Scalar(b)) => {
236                             // Order by the memory placement, not source order.
237                             let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
238                                 ((i, a), (j, b))
239                             } else {
240                                 ((j, b), (i, a))
241                             };
242                             let pair = self.scalar_pair::<V>(a, b);
243                             let pair_offsets = match pair.fields {
244                                 FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
245                                     assert_eq!(memory_index, &[0, 1]);
246                                     offsets
247                                 }
248                                 _ => panic!(),
249                             };
250                             if offsets[i] == pair_offsets[0]
251                                 && offsets[j] == pair_offsets[1]
252                                 && align == pair.align
253                                 && size == pair.size
254                             {
255                                 // We can use `ScalarPair` only when it matches our
256                                 // already computed layout (including `#[repr(C)]`).
257                                 abi = pair.abi;
258                             }
259                         }
260                         _ => {}
261                     }
262                 }
263
264                 _ => {}
265             }
266         }
267         if fields.iter().any(|f| f.abi.is_uninhabited()) {
268             abi = Abi::Uninhabited;
269         }
270         Some(LayoutS {
271             variants: Variants::Single { index: V::new(0) },
272             fields: FieldsShape::Arbitrary { offsets, memory_index },
273             abi,
274             largest_niche,
275             align,
276             size,
277         })
278     }
279
280     fn layout_of_never_type<V: Idx>(&self) -> LayoutS<V> {
281         let dl = self.current_data_layout();
282         let dl = dl.borrow();
283         LayoutS {
284             variants: Variants::Single { index: V::new(0) },
285             fields: FieldsShape::Primitive,
286             abi: Abi::Uninhabited,
287             largest_niche: None,
288             align: dl.i8_align,
289             size: Size::ZERO,
290         }
291     }
292
293     fn layout_of_struct_or_enum<'a, V: Idx, F: Deref<Target = &'a LayoutS<V>> + Debug>(
294         &self,
295         repr: &ReprOptions,
296         variants: &IndexVec<V, Vec<F>>,
297         is_enum: bool,
298         is_unsafe_cell: bool,
299         scalar_valid_range: (Bound<u128>, Bound<u128>),
300         discr_range_of_repr: impl Fn(i128, i128) -> (Integer, bool),
301         discriminants: impl Iterator<Item = (V, i128)>,
302         niche_optimize_enum: bool,
303         always_sized: bool,
304     ) -> Option<LayoutS<V>> {
305         let dl = self.current_data_layout();
306         let dl = dl.borrow();
307
308         let scalar_unit = |value: Primitive| {
309             let size = value.size(dl);
310             assert!(size.bits() <= 128);
311             Scalar::Initialized { value, valid_range: WrappingRange::full(size) }
312         };
313
314         // A variant is absent if it's uninhabited and only has ZST fields.
315         // Present uninhabited variants only require space for their fields,
316         // but *not* an encoding of the discriminant (e.g., a tag value).
317         // See issue #49298 for more details on the need to leave space
318         // for non-ZST uninhabited data (mostly partial initialization).
319         let absent = |fields: &[F]| {
320             let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited());
321             let is_zst = fields.iter().all(|f| f.is_zst());
322             uninhabited && is_zst
323         };
324         let (present_first, present_second) = {
325             let mut present_variants = variants
326                 .iter_enumerated()
327                 .filter_map(|(i, v)| if absent(v) { None } else { Some(i) });
328             (present_variants.next(), present_variants.next())
329         };
330         let present_first = match present_first {
331             Some(present_first) => present_first,
332             // Uninhabited because it has no variants, or only absent ones.
333             None if is_enum => {
334                 return Some(self.layout_of_never_type());
335             }
336             // If it's a struct, still compute a layout so that we can still compute the
337             // field offsets.
338             None => V::new(0),
339         };
340
341         let is_struct = !is_enum ||
342                     // Only one variant is present.
343                     (present_second.is_none() &&
344                         // Representation optimizations are allowed.
345                         !repr.inhibit_enum_layout_opt());
346         if is_struct {
347             // Struct, or univariant enum equivalent to a struct.
348             // (Typechecking will reject discriminant-sizing attrs.)
349
350             let v = present_first;
351             let kind = if is_enum || variants[v].is_empty() {
352                 StructKind::AlwaysSized
353             } else {
354                 if !always_sized { StructKind::MaybeUnsized } else { StructKind::AlwaysSized }
355             };
356
357             let mut st = self.univariant(dl, &variants[v], repr, kind)?;
358             st.variants = Variants::Single { index: v };
359
360             if is_unsafe_cell {
361                 let hide_niches = |scalar: &mut _| match scalar {
362                     Scalar::Initialized { value, valid_range } => {
363                         *valid_range = WrappingRange::full(value.size(dl))
364                     }
365                     // Already doesn't have any niches
366                     Scalar::Union { .. } => {}
367                 };
368                 match &mut st.abi {
369                     Abi::Uninhabited => {}
370                     Abi::Scalar(scalar) => hide_niches(scalar),
371                     Abi::ScalarPair(a, b) => {
372                         hide_niches(a);
373                         hide_niches(b);
374                     }
375                     Abi::Vector { element, count: _ } => hide_niches(element),
376                     Abi::Aggregate { sized: _ } => {}
377                 }
378                 st.largest_niche = None;
379                 return Some(st);
380             }
381
382             let (start, end) = scalar_valid_range;
383             match st.abi {
384                 Abi::Scalar(ref mut scalar) | Abi::ScalarPair(ref mut scalar, _) => {
385                     // Enlarging validity ranges would result in missed
386                     // optimizations, *not* wrongly assuming the inner
387                     // value is valid. e.g. unions already enlarge validity ranges,
388                     // because the values may be uninitialized.
389                     //
390                     // Because of that we only check that the start and end
391                     // of the range is representable with this scalar type.
392
393                     let max_value = scalar.size(dl).unsigned_int_max();
394                     if let Bound::Included(start) = start {
395                         // FIXME(eddyb) this might be incorrect - it doesn't
396                         // account for wrap-around (end < start) ranges.
397                         assert!(start <= max_value, "{start} > {max_value}");
398                         scalar.valid_range_mut().start = start;
399                     }
400                     if let Bound::Included(end) = end {
401                         // FIXME(eddyb) this might be incorrect - it doesn't
402                         // account for wrap-around (end < start) ranges.
403                         assert!(end <= max_value, "{end} > {max_value}");
404                         scalar.valid_range_mut().end = end;
405                     }
406
407                     // Update `largest_niche` if we have introduced a larger niche.
408                     let niche = Niche::from_scalar(dl, Size::ZERO, *scalar);
409                     if let Some(niche) = niche {
410                         match st.largest_niche {
411                             Some(largest_niche) => {
412                                 // Replace the existing niche even if they're equal,
413                                 // because this one is at a lower offset.
414                                 if largest_niche.available(dl) <= niche.available(dl) {
415                                     st.largest_niche = Some(niche);
416                                 }
417                             }
418                             None => st.largest_niche = Some(niche),
419                         }
420                     }
421                 }
422                 _ => assert!(
423                     start == Bound::Unbounded && end == Bound::Unbounded,
424                     "nonscalar layout for layout_scalar_valid_range type: {:#?}",
425                     st,
426                 ),
427             }
428
429             return Some(st);
430         }
431
432         // At this point, we have handled all unions and
433         // structs. (We have also handled univariant enums
434         // that allow representation optimization.)
435         assert!(is_enum);
436
437         // Until we've decided whether to use the tagged or
438         // niche filling LayoutS, we don't want to intern the
439         // variant layouts, so we can't store them in the
440         // overall LayoutS. Store the overall LayoutS
441         // and the variant LayoutSs here until then.
442         struct TmpLayout<V: Idx> {
443             layout: LayoutS<V>,
444             variants: IndexVec<V, LayoutS<V>>,
445         }
446
447         let calculate_niche_filling_layout = || -> Option<TmpLayout<V>> {
448             if niche_optimize_enum {
449                 return None;
450             }
451
452             if variants.len() < 2 {
453                 return None;
454             }
455
456             let mut align = dl.aggregate_align;
457             let mut variant_layouts = variants
458                 .iter_enumerated()
459                 .map(|(j, v)| {
460                     let mut st = self.univariant(dl, v, repr, StructKind::AlwaysSized)?;
461                     st.variants = Variants::Single { index: j };
462
463                     align = align.max(st.align);
464
465                     Some(st)
466                 })
467                 .collect::<Option<IndexVec<V, _>>>()?;
468
469             let largest_variant_index = variant_layouts
470                 .iter_enumerated()
471                 .max_by_key(|(_i, layout)| layout.size.bytes())
472                 .map(|(i, _layout)| i)?;
473
474             let all_indices = (0..=variants.len() - 1).map(V::new);
475             let needs_disc = |index: V| index != largest_variant_index && !absent(&variants[index]);
476             let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap().index()
477                 ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap().index();
478
479             let count = niche_variants.size_hint().1.unwrap() as u128;
480
481             // Find the field with the largest niche
482             let (field_index, niche, (niche_start, niche_scalar)) = variants[largest_variant_index]
483                 .iter()
484                 .enumerate()
485                 .filter_map(|(j, field)| Some((j, field.largest_niche?)))
486                 .max_by_key(|(_, niche)| niche.available(dl))
487                 .and_then(|(j, niche)| Some((j, niche, niche.reserve(dl, count)?)))?;
488             let niche_offset =
489                 niche.offset + variant_layouts[largest_variant_index].fields.offset(field_index);
490             let niche_size = niche.value.size(dl);
491             let size = variant_layouts[largest_variant_index].size.align_to(align.abi);
492
493             let all_variants_fit = variant_layouts.iter_enumerated_mut().all(|(i, layout)| {
494                 if i == largest_variant_index {
495                     return true;
496                 }
497
498                 layout.largest_niche = None;
499
500                 if layout.size <= niche_offset {
501                     // This variant will fit before the niche.
502                     return true;
503                 }
504
505                 // Determine if it'll fit after the niche.
506                 let this_align = layout.align.abi;
507                 let this_offset = (niche_offset + niche_size).align_to(this_align);
508
509                 if this_offset + layout.size > size {
510                     return false;
511                 }
512
513                 // It'll fit, but we need to make some adjustments.
514                 match layout.fields {
515                     FieldsShape::Arbitrary { ref mut offsets, .. } => {
516                         for (j, offset) in offsets.iter_mut().enumerate() {
517                             if !variants[i][j].is_zst() {
518                                 *offset += this_offset;
519                             }
520                         }
521                     }
522                     _ => {
523                         panic!("Layout of fields should be Arbitrary for variants")
524                     }
525                 }
526
527                 // It can't be a Scalar or ScalarPair because the offset isn't 0.
528                 if !layout.abi.is_uninhabited() {
529                     layout.abi = Abi::Aggregate { sized: true };
530                 }
531                 layout.size += this_offset;
532
533                 true
534             });
535
536             if !all_variants_fit {
537                 return None;
538             }
539
540             let largest_niche = Niche::from_scalar(dl, niche_offset, niche_scalar);
541
542             let others_zst = variant_layouts
543                 .iter_enumerated()
544                 .all(|(i, layout)| i == largest_variant_index || layout.size == Size::ZERO);
545             let same_size = size == variant_layouts[largest_variant_index].size;
546             let same_align = align == variant_layouts[largest_variant_index].align;
547
548             let abi = if variant_layouts.iter().all(|v| v.abi.is_uninhabited()) {
549                 Abi::Uninhabited
550             } else if same_size && same_align && others_zst {
551                 match variant_layouts[largest_variant_index].abi {
552                     // When the total alignment and size match, we can use the
553                     // same ABI as the scalar variant with the reserved niche.
554                     Abi::Scalar(_) => Abi::Scalar(niche_scalar),
555                     Abi::ScalarPair(first, second) => {
556                         // Only the niche is guaranteed to be initialised,
557                         // so use union layouts for the other primitive.
558                         if niche_offset == Size::ZERO {
559                             Abi::ScalarPair(niche_scalar, second.to_union())
560                         } else {
561                             Abi::ScalarPair(first.to_union(), niche_scalar)
562                         }
563                     }
564                     _ => Abi::Aggregate { sized: true },
565                 }
566             } else {
567                 Abi::Aggregate { sized: true }
568             };
569
570             let layout = LayoutS {
571                 variants: Variants::Multiple {
572                     tag: niche_scalar,
573                     tag_encoding: TagEncoding::Niche {
574                         untagged_variant: largest_variant_index,
575                         niche_variants: (V::new(*niche_variants.start())
576                             ..=V::new(*niche_variants.end())),
577                         niche_start,
578                     },
579                     tag_field: 0,
580                     variants: IndexVec::new(),
581                 },
582                 fields: FieldsShape::Arbitrary {
583                     offsets: vec![niche_offset],
584                     memory_index: vec![0],
585                 },
586                 abi,
587                 largest_niche,
588                 size,
589                 align,
590             };
591
592             Some(TmpLayout { layout, variants: variant_layouts })
593         };
594
595         let niche_filling_layout = calculate_niche_filling_layout();
596
597         let (mut min, mut max) = (i128::MAX, i128::MIN);
598         let discr_type = repr.discr_type();
599         let bits = Integer::from_attr(dl, discr_type).size().bits();
600         for (i, mut val) in discriminants {
601             if variants[i].iter().any(|f| f.abi.is_uninhabited()) {
602                 continue;
603             }
604             if discr_type.is_signed() {
605                 // sign extend the raw representation to be an i128
606                 val = (val << (128 - bits)) >> (128 - bits);
607             }
608             if val < min {
609                 min = val;
610             }
611             if val > max {
612                 max = val;
613             }
614         }
615         // We might have no inhabited variants, so pretend there's at least one.
616         if (min, max) == (i128::MAX, i128::MIN) {
617             min = 0;
618             max = 0;
619         }
620         assert!(min <= max, "discriminant range is {}...{}", min, max);
621         let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::repr_discr(tcx, ty, &repr, min, max);
622
623         let mut align = dl.aggregate_align;
624         let mut size = Size::ZERO;
625
626         // We're interested in the smallest alignment, so start large.
627         let mut start_align = Align::from_bytes(256).unwrap();
628         assert_eq!(Integer::for_align(dl, start_align), None);
629
630         // repr(C) on an enum tells us to make a (tag, union) layout,
631         // so we need to grow the prefix alignment to be at least
632         // the alignment of the union. (This value is used both for
633         // determining the alignment of the overall enum, and the
634         // determining the alignment of the payload after the tag.)
635         let mut prefix_align = min_ity.align(dl).abi;
636         if repr.c() {
637             for fields in variants {
638                 for field in fields {
639                     prefix_align = prefix_align.max(field.align.abi);
640                 }
641             }
642         }
643
644         // Create the set of structs that represent each variant.
645         let mut layout_variants = variants
646             .iter_enumerated()
647             .map(|(i, field_layouts)| {
648                 let mut st = self.univariant(
649                     dl,
650                     field_layouts,
651                     repr,
652                     StructKind::Prefixed(min_ity.size(), prefix_align),
653                 )?;
654                 st.variants = Variants::Single { index: i };
655                 // Find the first field we can't move later
656                 // to make room for a larger discriminant.
657                 for field in st.fields.index_by_increasing_offset().map(|j| &field_layouts[j]) {
658                     if !field.is_zst() || field.align.abi.bytes() != 1 {
659                         start_align = start_align.min(field.align.abi);
660                         break;
661                     }
662                 }
663                 size = cmp::max(size, st.size);
664                 align = align.max(st.align);
665                 Some(st)
666             })
667             .collect::<Option<IndexVec<V, _>>>()?;
668
669         // Align the maximum variant size to the largest alignment.
670         size = size.align_to(align.abi);
671
672         if size.bytes() >= dl.obj_size_bound() {
673             return None;
674         }
675
676         let typeck_ity = Integer::from_attr(dl, repr.discr_type());
677         if typeck_ity < min_ity {
678             // It is a bug if Layout decided on a greater discriminant size than typeck for
679             // some reason at this point (based on values discriminant can take on). Mostly
680             // because this discriminant will be loaded, and then stored into variable of
681             // type calculated by typeck. Consider such case (a bug): typeck decided on
682             // byte-sized discriminant, but layout thinks we need a 16-bit to store all
683             // discriminant values. That would be a bug, because then, in codegen, in order
684             // to store this 16-bit discriminant into 8-bit sized temporary some of the
685             // space necessary to represent would have to be discarded (or layout is wrong
686             // on thinking it needs 16 bits)
687             panic!(
688                 "layout decided on a larger discriminant type ({:?}) than typeck ({:?})",
689                 min_ity, typeck_ity
690             );
691             // However, it is fine to make discr type however large (as an optimisation)
692             // after this point â€“ we’ll just truncate the value we load in codegen.
693         }
694
695         // Check to see if we should use a different type for the
696         // discriminant. We can safely use a type with the same size
697         // as the alignment of the first field of each variant.
698         // We increase the size of the discriminant to avoid LLVM copying
699         // padding when it doesn't need to. This normally causes unaligned
700         // load/stores and excessive memcpy/memset operations. By using a
701         // bigger integer size, LLVM can be sure about its contents and
702         // won't be so conservative.
703
704         // Use the initial field alignment
705         let mut ity = if repr.c() || repr.int.is_some() {
706             min_ity
707         } else {
708             Integer::for_align(dl, start_align).unwrap_or(min_ity)
709         };
710
711         // If the alignment is not larger than the chosen discriminant size,
712         // don't use the alignment as the final size.
713         if ity <= min_ity {
714             ity = min_ity;
715         } else {
716             // Patch up the variants' first few fields.
717             let old_ity_size = min_ity.size();
718             let new_ity_size = ity.size();
719             for variant in &mut layout_variants {
720                 match variant.fields {
721                     FieldsShape::Arbitrary { ref mut offsets, .. } => {
722                         for i in offsets {
723                             if *i <= old_ity_size {
724                                 assert_eq!(*i, old_ity_size);
725                                 *i = new_ity_size;
726                             }
727                         }
728                         // We might be making the struct larger.
729                         if variant.size <= old_ity_size {
730                             variant.size = new_ity_size;
731                         }
732                     }
733                     _ => panic!(),
734                 }
735             }
736         }
737
738         let tag_mask = ity.size().unsigned_int_max();
739         let tag = Scalar::Initialized {
740             value: Int(ity, signed),
741             valid_range: WrappingRange {
742                 start: (min as u128 & tag_mask),
743                 end: (max as u128 & tag_mask),
744             },
745         };
746         let mut abi = Abi::Aggregate { sized: true };
747
748         if layout_variants.iter().all(|v| v.abi.is_uninhabited()) {
749             abi = Abi::Uninhabited;
750         } else if tag.size(dl) == size {
751             // Make sure we only use scalar layout when the enum is entirely its
752             // own tag (i.e. it has no padding nor any non-ZST variant fields).
753             abi = Abi::Scalar(tag);
754         } else {
755             // Try to use a ScalarPair for all tagged enums.
756             let mut common_prim = None;
757             let mut common_prim_initialized_in_all_variants = true;
758             for (field_layouts, layout_variant) in iter::zip(variants, &layout_variants) {
759                 let FieldsShape::Arbitrary { ref offsets, .. } = layout_variant.fields else {
760                     panic!();
761                 };
762                 let mut fields = iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst());
763                 let (field, offset) = match (fields.next(), fields.next()) {
764                     (None, None) => {
765                         common_prim_initialized_in_all_variants = false;
766                         continue;
767                     }
768                     (Some(pair), None) => pair,
769                     _ => {
770                         common_prim = None;
771                         break;
772                     }
773                 };
774                 let prim = match field.abi {
775                     Abi::Scalar(scalar) => {
776                         common_prim_initialized_in_all_variants &=
777                             matches!(scalar, Scalar::Initialized { .. });
778                         scalar.primitive()
779                     }
780                     _ => {
781                         common_prim = None;
782                         break;
783                     }
784                 };
785                 if let Some(pair) = common_prim {
786                     // This is pretty conservative. We could go fancier
787                     // by conflating things like i32 and u32, or even
788                     // realising that (u8, u8) could just cohabit with
789                     // u16 or even u32.
790                     if pair != (prim, offset) {
791                         common_prim = None;
792                         break;
793                     }
794                 } else {
795                     common_prim = Some((prim, offset));
796                 }
797             }
798             if let Some((prim, offset)) = common_prim {
799                 let prim_scalar = if common_prim_initialized_in_all_variants {
800                     scalar_unit(prim)
801                 } else {
802                     // Common prim might be uninit.
803                     Scalar::Union { value: prim }
804                 };
805                 let pair = self.scalar_pair::<V>(tag, prim_scalar);
806                 let pair_offsets = match pair.fields {
807                     FieldsShape::Arbitrary { ref offsets, ref memory_index } => {
808                         assert_eq!(memory_index, &[0, 1]);
809                         offsets
810                     }
811                     _ => panic!(),
812                 };
813                 if pair_offsets[0] == Size::ZERO
814                     && pair_offsets[1] == *offset
815                     && align == pair.align
816                     && size == pair.size
817                 {
818                     // We can use `ScalarPair` only when it matches our
819                     // already computed layout (including `#[repr(C)]`).
820                     abi = pair.abi;
821                 }
822             }
823         }
824
825         // If we pick a "clever" (by-value) ABI, we might have to adjust the ABI of the
826         // variants to ensure they are consistent. This is because a downcast is
827         // semantically a NOP, and thus should not affect layout.
828         if matches!(abi, Abi::Scalar(..) | Abi::ScalarPair(..)) {
829             for variant in &mut layout_variants {
830                 // We only do this for variants with fields; the others are not accessed anyway.
831                 // Also do not overwrite any already existing "clever" ABIs.
832                 if variant.fields.count() > 0 && matches!(variant.abi, Abi::Aggregate { .. }) {
833                     variant.abi = abi;
834                     // Also need to bump up the size and alignment, so that the entire value fits in here.
835                     variant.size = cmp::max(variant.size, size);
836                     variant.align.abi = cmp::max(variant.align.abi, align.abi);
837                 }
838             }
839         }
840
841         let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag);
842
843         let tagged_layout = LayoutS {
844             variants: Variants::Multiple {
845                 tag,
846                 tag_encoding: TagEncoding::Direct,
847                 tag_field: 0,
848                 variants: IndexVec::new(),
849             },
850             fields: FieldsShape::Arbitrary { offsets: vec![Size::ZERO], memory_index: vec![0] },
851             largest_niche,
852             abi,
853             align,
854             size,
855         };
856
857         let tagged_layout = TmpLayout { layout: tagged_layout, variants: layout_variants };
858
859         let mut best_layout = match (tagged_layout, niche_filling_layout) {
860             (tl, Some(nl)) => {
861                 // Pick the smaller layout; otherwise,
862                 // pick the layout with the larger niche; otherwise,
863                 // pick tagged as it has simpler codegen.
864                 use cmp::Ordering::*;
865                 let niche_size = |tmp_l: &TmpLayout<V>| {
866                     tmp_l.layout.largest_niche.map_or(0, |n| n.available(dl))
867                 };
868                 match (tl.layout.size.cmp(&nl.layout.size), niche_size(&tl).cmp(&niche_size(&nl))) {
869                     (Greater, _) => nl,
870                     (Equal, Less) => nl,
871                     _ => tl,
872                 }
873             }
874             (tl, None) => tl,
875         };
876
877         // Now we can intern the variant layouts and store them in the enum layout.
878         best_layout.layout.variants = match best_layout.layout.variants {
879             Variants::Multiple { tag, tag_encoding, tag_field, .. } => {
880                 Variants::Multiple { tag, tag_encoding, tag_field, variants: best_layout.variants }
881             }
882             _ => panic!(),
883         };
884         Some(best_layout.layout)
885     }
886
887     fn layout_of_union<'a, V: Idx, F: Deref<Target = &'a LayoutS<V>> + Debug>(
888         &self,
889         repr: &ReprOptions,
890         variants: &IndexVec<V, Vec<F>>,
891     ) -> Option<LayoutS<V>> {
892         let dl = self.current_data_layout();
893         let dl = dl.borrow();
894         let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align };
895
896         if let Some(repr_align) = repr.align {
897             align = align.max(AbiAndPrefAlign::new(repr_align));
898         }
899
900         let optimize = !repr.inhibit_union_abi_opt();
901         let mut size = Size::ZERO;
902         let mut abi = Abi::Aggregate { sized: true };
903         let index = V::new(0);
904         for field in &variants[index] {
905             assert!(field.is_sized());
906             align = align.max(field.align);
907
908             // If all non-ZST fields have the same ABI, forward this ABI
909             if optimize && !field.is_zst() {
910                 // Discard valid range information and allow undef
911                 let field_abi = match field.abi {
912                     Abi::Scalar(x) => Abi::Scalar(x.to_union()),
913                     Abi::ScalarPair(x, y) => Abi::ScalarPair(x.to_union(), y.to_union()),
914                     Abi::Vector { element: x, count } => {
915                         Abi::Vector { element: x.to_union(), count }
916                     }
917                     Abi::Uninhabited | Abi::Aggregate { .. } => Abi::Aggregate { sized: true },
918                 };
919
920                 if size == Size::ZERO {
921                     // first non ZST: initialize 'abi'
922                     abi = field_abi;
923                 } else if abi != field_abi {
924                     // different fields have different ABI: reset to Aggregate
925                     abi = Abi::Aggregate { sized: true };
926                 }
927             }
928
929             size = cmp::max(size, field.size);
930         }
931
932         if let Some(pack) = repr.pack {
933             align = align.min(AbiAndPrefAlign::new(pack));
934         }
935
936         Some(LayoutS {
937             variants: Variants::Single { index },
938             fields: FieldsShape::Union(NonZeroUsize::new(variants[index].len())?),
939             abi,
940             largest_niche: None,
941             align,
942             size: size.align_to(align.abi),
943         })
944     }
945 }