]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/abi/mod.rs
Tweak move error
[rust.git] / compiler / rustc_target / src / abi / mod.rs
1 pub use Integer::*;
2 pub use Primitive::*;
3
4 use crate::spec::Target;
5
6 use std::convert::{TryFrom, TryInto};
7 use std::fmt;
8 use std::iter::Step;
9 use std::num::NonZeroUsize;
10 use std::ops::{Add, AddAssign, Deref, Mul, RangeInclusive, Sub};
11 use std::str::FromStr;
12
13 use rustc_index::vec::{Idx, IndexVec};
14 use rustc_macros::HashStable_Generic;
15 use rustc_serialize::json::{Json, ToJson};
16
17 pub mod call;
18
19 /// Parsed [Data layout](https://llvm.org/docs/LangRef.html#data-layout)
20 /// for a target, which contains everything needed to compute layouts.
21 pub struct TargetDataLayout {
22     pub endian: Endian,
23     pub i1_align: AbiAndPrefAlign,
24     pub i8_align: AbiAndPrefAlign,
25     pub i16_align: AbiAndPrefAlign,
26     pub i32_align: AbiAndPrefAlign,
27     pub i64_align: AbiAndPrefAlign,
28     pub i128_align: AbiAndPrefAlign,
29     pub f32_align: AbiAndPrefAlign,
30     pub f64_align: AbiAndPrefAlign,
31     pub pointer_size: Size,
32     pub pointer_align: AbiAndPrefAlign,
33     pub aggregate_align: AbiAndPrefAlign,
34
35     /// Alignments for vector types.
36     pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
37
38     pub instruction_address_space: AddressSpace,
39
40     /// Minimum size of #[repr(C)] enums (default I32 bits)
41     pub c_enum_min_size: Integer,
42 }
43
44 impl Default for TargetDataLayout {
45     /// Creates an instance of `TargetDataLayout`.
46     fn default() -> TargetDataLayout {
47         let align = |bits| Align::from_bits(bits).unwrap();
48         TargetDataLayout {
49             endian: Endian::Big,
50             i1_align: AbiAndPrefAlign::new(align(8)),
51             i8_align: AbiAndPrefAlign::new(align(8)),
52             i16_align: AbiAndPrefAlign::new(align(16)),
53             i32_align: AbiAndPrefAlign::new(align(32)),
54             i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
55             i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
56             f32_align: AbiAndPrefAlign::new(align(32)),
57             f64_align: AbiAndPrefAlign::new(align(64)),
58             pointer_size: Size::from_bits(64),
59             pointer_align: AbiAndPrefAlign::new(align(64)),
60             aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
61             vector_align: vec![
62                 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
63                 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
64             ],
65             instruction_address_space: AddressSpace::DATA,
66             c_enum_min_size: Integer::I32,
67         }
68     }
69 }
70
71 impl TargetDataLayout {
72     pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
73         // Parse an address space index from a string.
74         let parse_address_space = |s: &str, cause: &str| {
75             s.parse::<u32>().map(AddressSpace).map_err(|err| {
76                 format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err)
77             })
78         };
79
80         // Parse a bit count from a string.
81         let parse_bits = |s: &str, kind: &str, cause: &str| {
82             s.parse::<u64>().map_err(|err| {
83                 format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err)
84             })
85         };
86
87         // Parse a size string.
88         let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits);
89
90         // Parse an alignment string.
91         let align = |s: &[&str], cause: &str| {
92             if s.is_empty() {
93                 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
94             }
95             let align_from_bits = |bits| {
96                 Align::from_bits(bits).map_err(|err| {
97                     format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err)
98                 })
99             };
100             let abi = parse_bits(s[0], "alignment", cause)?;
101             let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
102             Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? })
103         };
104
105         let mut dl = TargetDataLayout::default();
106         let mut i128_align_src = 64;
107         for spec in target.data_layout.split('-') {
108             let spec_parts = spec.split(':').collect::<Vec<_>>();
109
110             match &*spec_parts {
111                 ["e"] => dl.endian = Endian::Little,
112                 ["E"] => dl.endian = Endian::Big,
113                 [p] if p.starts_with('P') => {
114                     dl.instruction_address_space = parse_address_space(&p[1..], "P")?
115                 }
116                 ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?,
117                 ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?,
118                 ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?,
119                 [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => {
120                     dl.pointer_size = size(s, p)?;
121                     dl.pointer_align = align(a, p)?;
122                 }
123                 [s, ref a @ ..] if s.starts_with('i') => {
124                     let Ok(bits) = s[1..].parse::<u64>() else {
125                         size(&s[1..], "i")?; // For the user error.
126                         continue;
127                     };
128                     let a = align(a, s)?;
129                     match bits {
130                         1 => dl.i1_align = a,
131                         8 => dl.i8_align = a,
132                         16 => dl.i16_align = a,
133                         32 => dl.i32_align = a,
134                         64 => dl.i64_align = a,
135                         _ => {}
136                     }
137                     if bits >= i128_align_src && bits <= 128 {
138                         // Default alignment for i128 is decided by taking the alignment of
139                         // largest-sized i{64..=128}.
140                         i128_align_src = bits;
141                         dl.i128_align = a;
142                     }
143                 }
144                 [s, ref a @ ..] if s.starts_with('v') => {
145                     let v_size = size(&s[1..], "v")?;
146                     let a = align(a, s)?;
147                     if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
148                         v.1 = a;
149                         continue;
150                     }
151                     // No existing entry, add a new one.
152                     dl.vector_align.push((v_size, a));
153                 }
154                 _ => {} // Ignore everything else.
155             }
156         }
157
158         // Perform consistency checks against the Target information.
159         if dl.endian != target.endian {
160             return Err(format!(
161                 "inconsistent target specification: \"data-layout\" claims \
162                  architecture is {}-endian, while \"target-endian\" is `{}`",
163                 dl.endian.as_str(),
164                 target.endian.as_str(),
165             ));
166         }
167
168         if dl.pointer_size.bits() != target.pointer_width.into() {
169             return Err(format!(
170                 "inconsistent target specification: \"data-layout\" claims \
171                  pointers are {}-bit, while \"target-pointer-width\" is `{}`",
172                 dl.pointer_size.bits(),
173                 target.pointer_width
174             ));
175         }
176
177         dl.c_enum_min_size = Integer::from_size(Size::from_bits(target.c_enum_min_bits))?;
178
179         Ok(dl)
180     }
181
182     /// Returns exclusive upper bound on object size.
183     ///
184     /// The theoretical maximum object size is defined as the maximum positive `isize` value.
185     /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
186     /// index every address within an object along with one byte past the end, along with allowing
187     /// `isize` to store the difference between any two pointers into an object.
188     ///
189     /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
190     /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
191     /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
192     /// address space on 64-bit ARMv8 and x86_64.
193     #[inline]
194     pub fn obj_size_bound(&self) -> u64 {
195         match self.pointer_size.bits() {
196             16 => 1 << 15,
197             32 => 1 << 31,
198             64 => 1 << 47,
199             bits => panic!("obj_size_bound: unknown pointer bit size {}", bits),
200         }
201     }
202
203     #[inline]
204     pub fn ptr_sized_integer(&self) -> Integer {
205         match self.pointer_size.bits() {
206             16 => I16,
207             32 => I32,
208             64 => I64,
209             bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits),
210         }
211     }
212
213     #[inline]
214     pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
215         for &(size, align) in &self.vector_align {
216             if size == vec_size {
217                 return align;
218             }
219         }
220         // Default to natural alignment, which is what LLVM does.
221         // That is, use the size, rounded up to a power of 2.
222         AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
223     }
224 }
225
226 pub trait HasDataLayout {
227     fn data_layout(&self) -> &TargetDataLayout;
228 }
229
230 impl HasDataLayout for TargetDataLayout {
231     #[inline]
232     fn data_layout(&self) -> &TargetDataLayout {
233         self
234     }
235 }
236
237 /// Endianness of the target, which must match cfg(target-endian).
238 #[derive(Copy, Clone, PartialEq)]
239 pub enum Endian {
240     Little,
241     Big,
242 }
243
244 impl Endian {
245     pub fn as_str(&self) -> &'static str {
246         match self {
247             Self::Little => "little",
248             Self::Big => "big",
249         }
250     }
251 }
252
253 impl fmt::Debug for Endian {
254     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255         f.write_str(self.as_str())
256     }
257 }
258
259 impl FromStr for Endian {
260     type Err = String;
261
262     fn from_str(s: &str) -> Result<Self, Self::Err> {
263         match s {
264             "little" => Ok(Self::Little),
265             "big" => Ok(Self::Big),
266             _ => Err(format!(r#"unknown endian: "{}""#, s)),
267         }
268     }
269 }
270
271 impl ToJson for Endian {
272     fn to_json(&self) -> Json {
273         self.as_str().to_json()
274     }
275 }
276
277 /// Size of a type in bytes.
278 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
279 #[derive(HashStable_Generic)]
280 pub struct Size {
281     // The top 3 bits are ALWAYS zero.
282     raw: u64,
283 }
284
285 impl Size {
286     pub const ZERO: Size = Size { raw: 0 };
287
288     /// Rounds `bits` up to the next-higher byte boundary, if `bits` is
289     /// is not aligned.
290     pub fn from_bits(bits: impl TryInto<u64>) -> Size {
291         let bits = bits.try_into().ok().unwrap();
292
293         #[cold]
294         fn overflow(bits: u64) -> ! {
295             panic!("Size::from_bits({}) has overflowed", bits);
296         }
297
298         // This is the largest value of `bits` that does not cause overflow
299         // during rounding, and guarantees that the resulting number of bytes
300         // cannot cause overflow when multiplied by 8.
301         if bits > 0xffff_ffff_ffff_fff8 {
302             overflow(bits);
303         }
304
305         // Avoid potential overflow from `bits + 7`.
306         Size { raw: bits / 8 + ((bits % 8) + 7) / 8 }
307     }
308
309     #[inline]
310     pub fn from_bytes(bytes: impl TryInto<u64>) -> Size {
311         let bytes: u64 = bytes.try_into().ok().unwrap();
312         Size { raw: bytes }
313     }
314
315     #[inline]
316     pub fn bytes(self) -> u64 {
317         self.raw
318     }
319
320     #[inline]
321     pub fn bytes_usize(self) -> usize {
322         self.bytes().try_into().unwrap()
323     }
324
325     #[inline]
326     pub fn bits(self) -> u64 {
327         self.raw << 3
328     }
329
330     #[inline]
331     pub fn bits_usize(self) -> usize {
332         self.bits().try_into().unwrap()
333     }
334
335     #[inline]
336     pub fn align_to(self, align: Align) -> Size {
337         let mask = align.bytes() - 1;
338         Size::from_bytes((self.bytes() + mask) & !mask)
339     }
340
341     #[inline]
342     pub fn is_aligned(self, align: Align) -> bool {
343         let mask = align.bytes() - 1;
344         self.bytes() & mask == 0
345     }
346
347     #[inline]
348     pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
349         let dl = cx.data_layout();
350
351         let bytes = self.bytes().checked_add(offset.bytes())?;
352
353         if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
354     }
355
356     #[inline]
357     pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
358         let dl = cx.data_layout();
359
360         let bytes = self.bytes().checked_mul(count)?;
361         if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
362     }
363
364     /// Truncates `value` to `self` bits and then sign-extends it to 128 bits
365     /// (i.e., if it is negative, fill with 1's on the left).
366     #[inline]
367     pub fn sign_extend(self, value: u128) -> u128 {
368         let size = self.bits();
369         if size == 0 {
370             // Truncated until nothing is left.
371             return 0;
372         }
373         // Sign-extend it.
374         let shift = 128 - size;
375         // Shift the unsigned value to the left, then shift back to the right as signed
376         // (essentially fills with sign bit on the left).
377         (((value << shift) as i128) >> shift) as u128
378     }
379
380     /// Truncates `value` to `self` bits.
381     #[inline]
382     pub fn truncate(self, value: u128) -> u128 {
383         let size = self.bits();
384         if size == 0 {
385             // Truncated until nothing is left.
386             return 0;
387         }
388         let shift = 128 - size;
389         // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
390         (value << shift) >> shift
391     }
392
393     #[inline]
394     pub fn signed_int_min(&self) -> i128 {
395         self.sign_extend(1_u128 << (self.bits() - 1)) as i128
396     }
397
398     #[inline]
399     pub fn signed_int_max(&self) -> i128 {
400         i128::MAX >> (128 - self.bits())
401     }
402
403     #[inline]
404     pub fn unsigned_int_max(&self) -> u128 {
405         u128::MAX >> (128 - self.bits())
406     }
407 }
408
409 // Panicking addition, subtraction and multiplication for convenience.
410 // Avoid during layout computation, return `LayoutError` instead.
411
412 impl Add for Size {
413     type Output = Size;
414     #[inline]
415     fn add(self, other: Size) -> Size {
416         Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
417             panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
418         }))
419     }
420 }
421
422 impl Sub for Size {
423     type Output = Size;
424     #[inline]
425     fn sub(self, other: Size) -> Size {
426         Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
427             panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
428         }))
429     }
430 }
431
432 impl Mul<Size> for u64 {
433     type Output = Size;
434     #[inline]
435     fn mul(self, size: Size) -> Size {
436         size * self
437     }
438 }
439
440 impl Mul<u64> for Size {
441     type Output = Size;
442     #[inline]
443     fn mul(self, count: u64) -> Size {
444         match self.bytes().checked_mul(count) {
445             Some(bytes) => Size::from_bytes(bytes),
446             None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count),
447         }
448     }
449 }
450
451 impl AddAssign for Size {
452     #[inline]
453     fn add_assign(&mut self, other: Size) {
454         *self = *self + other;
455     }
456 }
457
458 impl Step for Size {
459     #[inline]
460     fn steps_between(start: &Self, end: &Self) -> Option<usize> {
461         u64::steps_between(&start.bytes(), &end.bytes())
462     }
463
464     #[inline]
465     fn forward_checked(start: Self, count: usize) -> Option<Self> {
466         u64::forward_checked(start.bytes(), count).map(Self::from_bytes)
467     }
468
469     #[inline]
470     fn forward(start: Self, count: usize) -> Self {
471         Self::from_bytes(u64::forward(start.bytes(), count))
472     }
473
474     #[inline]
475     unsafe fn forward_unchecked(start: Self, count: usize) -> Self {
476         Self::from_bytes(u64::forward_unchecked(start.bytes(), count))
477     }
478
479     #[inline]
480     fn backward_checked(start: Self, count: usize) -> Option<Self> {
481         u64::backward_checked(start.bytes(), count).map(Self::from_bytes)
482     }
483
484     #[inline]
485     fn backward(start: Self, count: usize) -> Self {
486         Self::from_bytes(u64::backward(start.bytes(), count))
487     }
488
489     #[inline]
490     unsafe fn backward_unchecked(start: Self, count: usize) -> Self {
491         Self::from_bytes(u64::backward_unchecked(start.bytes(), count))
492     }
493 }
494
495 /// Alignment of a type in bytes (always a power of two).
496 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
497 #[derive(HashStable_Generic)]
498 pub struct Align {
499     pow2: u8,
500 }
501
502 impl Align {
503     pub const ONE: Align = Align { pow2: 0 };
504
505     #[inline]
506     pub fn from_bits(bits: u64) -> Result<Align, String> {
507         Align::from_bytes(Size::from_bits(bits).bytes())
508     }
509
510     #[inline]
511     pub fn from_bytes(align: u64) -> Result<Align, String> {
512         // Treat an alignment of 0 bytes like 1-byte alignment.
513         if align == 0 {
514             return Ok(Align::ONE);
515         }
516
517         #[cold]
518         fn not_power_of_2(align: u64) -> String {
519             format!("`{}` is not a power of 2", align)
520         }
521
522         #[cold]
523         fn too_large(align: u64) -> String {
524             format!("`{}` is too large", align)
525         }
526
527         let mut bytes = align;
528         let mut pow2: u8 = 0;
529         while (bytes & 1) == 0 {
530             pow2 += 1;
531             bytes >>= 1;
532         }
533         if bytes != 1 {
534             return Err(not_power_of_2(align));
535         }
536         if pow2 > 29 {
537             return Err(too_large(align));
538         }
539
540         Ok(Align { pow2 })
541     }
542
543     #[inline]
544     pub fn bytes(self) -> u64 {
545         1 << self.pow2
546     }
547
548     #[inline]
549     pub fn bits(self) -> u64 {
550         self.bytes() * 8
551     }
552
553     /// Computes the best alignment possible for the given offset
554     /// (the largest power of two that the offset is a multiple of).
555     ///
556     /// N.B., for an offset of `0`, this happens to return `2^64`.
557     #[inline]
558     pub fn max_for_offset(offset: Size) -> Align {
559         Align { pow2: offset.bytes().trailing_zeros() as u8 }
560     }
561
562     /// Lower the alignment, if necessary, such that the given offset
563     /// is aligned to it (the offset is a multiple of the alignment).
564     #[inline]
565     pub fn restrict_for_offset(self, offset: Size) -> Align {
566         self.min(Align::max_for_offset(offset))
567     }
568 }
569
570 /// A pair of alignments, ABI-mandated and preferred.
571 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
572 #[derive(HashStable_Generic)]
573 pub struct AbiAndPrefAlign {
574     pub abi: Align,
575     pub pref: Align,
576 }
577
578 impl AbiAndPrefAlign {
579     #[inline]
580     pub fn new(align: Align) -> AbiAndPrefAlign {
581         AbiAndPrefAlign { abi: align, pref: align }
582     }
583
584     #[inline]
585     pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
586         AbiAndPrefAlign { abi: self.abi.min(other.abi), pref: self.pref.min(other.pref) }
587     }
588
589     #[inline]
590     pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
591         AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) }
592     }
593 }
594
595 /// Integers, also used for enum discriminants.
596 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)]
597 pub enum Integer {
598     I8,
599     I16,
600     I32,
601     I64,
602     I128,
603 }
604
605 impl Integer {
606     #[inline]
607     pub fn size(self) -> Size {
608         match self {
609             I8 => Size::from_bytes(1),
610             I16 => Size::from_bytes(2),
611             I32 => Size::from_bytes(4),
612             I64 => Size::from_bytes(8),
613             I128 => Size::from_bytes(16),
614         }
615     }
616
617     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
618         let dl = cx.data_layout();
619
620         match self {
621             I8 => dl.i8_align,
622             I16 => dl.i16_align,
623             I32 => dl.i32_align,
624             I64 => dl.i64_align,
625             I128 => dl.i128_align,
626         }
627     }
628
629     /// Finds the smallest Integer type which can represent the signed value.
630     #[inline]
631     pub fn fit_signed(x: i128) -> Integer {
632         match x {
633             -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
634             -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
635             -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
636             -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
637             _ => I128,
638         }
639     }
640
641     /// Finds the smallest Integer type which can represent the unsigned value.
642     #[inline]
643     pub fn fit_unsigned(x: u128) -> Integer {
644         match x {
645             0..=0x0000_0000_0000_00ff => I8,
646             0..=0x0000_0000_0000_ffff => I16,
647             0..=0x0000_0000_ffff_ffff => I32,
648             0..=0xffff_ffff_ffff_ffff => I64,
649             _ => I128,
650         }
651     }
652
653     /// Finds the smallest integer with the given alignment.
654     pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
655         let dl = cx.data_layout();
656
657         for candidate in [I8, I16, I32, I64, I128] {
658             if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
659                 return Some(candidate);
660             }
661         }
662         None
663     }
664
665     /// Find the largest integer with the given alignment or less.
666     pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
667         let dl = cx.data_layout();
668
669         // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
670         for candidate in [I64, I32, I16] {
671             if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
672                 return candidate;
673             }
674         }
675         I8
676     }
677
678     // FIXME(eddyb) consolidate this and other methods that find the appropriate
679     // `Integer` given some requirements.
680     #[inline]
681     fn from_size(size: Size) -> Result<Self, String> {
682         match size.bits() {
683             8 => Ok(Integer::I8),
684             16 => Ok(Integer::I16),
685             32 => Ok(Integer::I32),
686             64 => Ok(Integer::I64),
687             128 => Ok(Integer::I128),
688             _ => Err(format!("rust does not support integers with {} bits", size.bits())),
689         }
690     }
691 }
692
693 /// Fundamental unit of memory access and layout.
694 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
695 pub enum Primitive {
696     /// The `bool` is the signedness of the `Integer` type.
697     ///
698     /// One would think we would not care about such details this low down,
699     /// but some ABIs are described in terms of C types and ISAs where the
700     /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
701     /// a negative integer passed by zero-extension will appear positive in
702     /// the callee, and most operations on it will produce the wrong values.
703     Int(Integer, bool),
704     F32,
705     F64,
706     Pointer,
707 }
708
709 impl Primitive {
710     pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
711         let dl = cx.data_layout();
712
713         match self {
714             Int(i, _) => i.size(),
715             F32 => Size::from_bits(32),
716             F64 => Size::from_bits(64),
717             Pointer => dl.pointer_size,
718         }
719     }
720
721     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
722         let dl = cx.data_layout();
723
724         match self {
725             Int(i, _) => i.align(dl),
726             F32 => dl.f32_align,
727             F64 => dl.f64_align,
728             Pointer => dl.pointer_align,
729         }
730     }
731
732     // FIXME(eddyb) remove, it's trivial thanks to `matches!`.
733     #[inline]
734     pub fn is_float(self) -> bool {
735         matches!(self, F32 | F64)
736     }
737
738     // FIXME(eddyb) remove, it's completely unused.
739     #[inline]
740     pub fn is_int(self) -> bool {
741         matches!(self, Int(..))
742     }
743 }
744
745 /// Inclusive wrap-around range of valid values, that is, if
746 /// start > end, it represents `start..=MAX`,
747 /// followed by `0..=end`.
748 ///
749 /// That is, for an i8 primitive, a range of `254..=2` means following
750 /// sequence:
751 ///
752 ///    254 (-2), 255 (-1), 0, 1, 2
753 ///
754 /// This is intended specifically to mirror LLVM’s `!range` metadata semantics.
755 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
756 #[derive(HashStable_Generic)]
757 pub struct WrappingRange {
758     pub start: u128,
759     pub end: u128,
760 }
761
762 impl WrappingRange {
763     /// Returns `true` if `v` is contained in the range.
764     #[inline(always)]
765     pub fn contains(&self, v: u128) -> bool {
766         if self.start <= self.end {
767             self.start <= v && v <= self.end
768         } else {
769             self.start <= v || v <= self.end
770         }
771     }
772
773     /// Returns `self` with replaced `start`
774     #[inline(always)]
775     pub fn with_start(mut self, start: u128) -> Self {
776         self.start = start;
777         self
778     }
779
780     /// Returns `self` with replaced `end`
781     #[inline(always)]
782     pub fn with_end(mut self, end: u128) -> Self {
783         self.end = end;
784         self
785     }
786
787     /// Returns `true` if `size` completely fills the range.
788     #[inline]
789     pub fn is_full_for(&self, size: Size) -> bool {
790         let max_value = size.unsigned_int_max();
791         debug_assert!(self.start <= max_value && self.end <= max_value);
792         self.start == (self.end.wrapping_add(1) & max_value)
793     }
794 }
795
796 impl fmt::Debug for WrappingRange {
797     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
798         if self.start > self.end {
799             write!(fmt, "(..={}) | ({}..)", self.end, self.start)?;
800         } else {
801             write!(fmt, "{}..={}", self.start, self.end)?;
802         }
803         Ok(())
804     }
805 }
806
807 /// Information about one scalar component of a Rust type.
808 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
809 #[derive(HashStable_Generic)]
810 pub struct Scalar {
811     pub value: Primitive,
812
813     // FIXME(eddyb) always use the shortest range, e.g., by finding
814     // the largest space between two consecutive valid values and
815     // taking everything else as the (shortest) valid range.
816     pub valid_range: WrappingRange,
817 }
818
819 impl Scalar {
820     #[inline]
821     pub fn is_bool(&self) -> bool {
822         matches!(
823             self,
824             Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } }
825         )
826     }
827
828     /// Returns `true` if all possible numbers are valid, i.e `valid_range` covers the whole layout
829     #[inline]
830     pub fn is_always_valid<C: HasDataLayout>(&self, cx: &C) -> bool {
831         self.valid_range.is_full_for(self.value.size(cx))
832     }
833 }
834
835 /// Describes how the fields of a type are located in memory.
836 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
837 pub enum FieldsShape {
838     /// Scalar primitives and `!`, which never have fields.
839     Primitive,
840
841     /// All fields start at no offset. The `usize` is the field count.
842     Union(NonZeroUsize),
843
844     /// Array/vector-like placement, with all fields of identical types.
845     Array { stride: Size, count: u64 },
846
847     /// Struct-like placement, with precomputed offsets.
848     ///
849     /// Fields are guaranteed to not overlap, but note that gaps
850     /// before, between and after all the fields are NOT always
851     /// padding, and as such their contents may not be discarded.
852     /// For example, enum variants leave a gap at the start,
853     /// where the discriminant field in the enum layout goes.
854     Arbitrary {
855         /// Offsets for the first byte of each field,
856         /// ordered to match the source definition order.
857         /// This vector does not go in increasing order.
858         // FIXME(eddyb) use small vector optimization for the common case.
859         offsets: Vec<Size>,
860
861         /// Maps source order field indices to memory order indices,
862         /// depending on how the fields were reordered (if at all).
863         /// This is a permutation, with both the source order and the
864         /// memory order using the same (0..n) index ranges.
865         ///
866         /// Note that during computation of `memory_index`, sometimes
867         /// it is easier to operate on the inverse mapping (that is,
868         /// from memory order to source order), and that is usually
869         /// named `inverse_memory_index`.
870         ///
871         // FIXME(eddyb) build a better abstraction for permutations, if possible.
872         // FIXME(camlorn) also consider small vector  optimization here.
873         memory_index: Vec<u32>,
874     },
875 }
876
877 impl FieldsShape {
878     #[inline]
879     pub fn count(&self) -> usize {
880         match *self {
881             FieldsShape::Primitive => 0,
882             FieldsShape::Union(count) => count.get(),
883             FieldsShape::Array { count, .. } => count.try_into().unwrap(),
884             FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(),
885         }
886     }
887
888     #[inline]
889     pub fn offset(&self, i: usize) -> Size {
890         match *self {
891             FieldsShape::Primitive => {
892                 unreachable!("FieldsShape::offset: `Primitive`s have no fields")
893             }
894             FieldsShape::Union(count) => {
895                 assert!(
896                     i < count.get(),
897                     "tried to access field {} of union with {} fields",
898                     i,
899                     count
900                 );
901                 Size::ZERO
902             }
903             FieldsShape::Array { stride, count } => {
904                 let i = u64::try_from(i).unwrap();
905                 assert!(i < count);
906                 stride * i
907             }
908             FieldsShape::Arbitrary { ref offsets, .. } => offsets[i],
909         }
910     }
911
912     #[inline]
913     pub fn memory_index(&self, i: usize) -> usize {
914         match *self {
915             FieldsShape::Primitive => {
916                 unreachable!("FieldsShape::memory_index: `Primitive`s have no fields")
917             }
918             FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
919             FieldsShape::Arbitrary { ref memory_index, .. } => memory_index[i].try_into().unwrap(),
920         }
921     }
922
923     /// Gets source indices of the fields by increasing offsets.
924     #[inline]
925     pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item = usize> + 'a {
926         let mut inverse_small = [0u8; 64];
927         let mut inverse_big = vec![];
928         let use_small = self.count() <= inverse_small.len();
929
930         // We have to write this logic twice in order to keep the array small.
931         if let FieldsShape::Arbitrary { ref memory_index, .. } = *self {
932             if use_small {
933                 for i in 0..self.count() {
934                     inverse_small[memory_index[i] as usize] = i as u8;
935                 }
936             } else {
937                 inverse_big = vec![0; self.count()];
938                 for i in 0..self.count() {
939                     inverse_big[memory_index[i] as usize] = i as u32;
940                 }
941             }
942         }
943
944         (0..self.count()).map(move |i| match *self {
945             FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
946             FieldsShape::Arbitrary { .. } => {
947                 if use_small {
948                     inverse_small[i] as usize
949                 } else {
950                     inverse_big[i] as usize
951                 }
952             }
953         })
954     }
955 }
956
957 /// An identifier that specifies the address space that some operation
958 /// should operate on. Special address spaces have an effect on code generation,
959 /// depending on the target and the address spaces it implements.
960 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
961 pub struct AddressSpace(pub u32);
962
963 impl AddressSpace {
964     /// The default address space, corresponding to data space.
965     pub const DATA: Self = AddressSpace(0);
966 }
967
968 /// Describes how values of the type are passed by target ABIs,
969 /// in terms of categories of C types there are ABI rules for.
970 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
971 pub enum Abi {
972     Uninhabited,
973     Scalar(Scalar),
974     ScalarPair(Scalar, Scalar),
975     Vector {
976         element: Scalar,
977         count: u64,
978     },
979     Aggregate {
980         /// If true, the size is exact, otherwise it's only a lower bound.
981         sized: bool,
982     },
983 }
984
985 impl Abi {
986     /// Returns `true` if the layout corresponds to an unsized type.
987     #[inline]
988     pub fn is_unsized(&self) -> bool {
989         match *self {
990             Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
991             Abi::Aggregate { sized } => !sized,
992         }
993     }
994
995     /// Returns `true` if this is a single signed integer scalar
996     #[inline]
997     pub fn is_signed(&self) -> bool {
998         match self {
999             Abi::Scalar(scal) => match scal.value {
1000                 Primitive::Int(_, signed) => signed,
1001                 _ => false,
1002             },
1003             _ => panic!("`is_signed` on non-scalar ABI {:?}", self),
1004         }
1005     }
1006
1007     /// Returns `true` if this is an uninhabited type
1008     #[inline]
1009     pub fn is_uninhabited(&self) -> bool {
1010         matches!(*self, Abi::Uninhabited)
1011     }
1012
1013     /// Returns `true` is this is a scalar type
1014     #[inline]
1015     pub fn is_scalar(&self) -> bool {
1016         matches!(*self, Abi::Scalar(_))
1017     }
1018 }
1019
1020 rustc_index::newtype_index! {
1021     pub struct VariantIdx {
1022         derive [HashStable_Generic]
1023     }
1024 }
1025
1026 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1027 pub enum Variants {
1028     /// Single enum variants, structs/tuples, unions, and all non-ADTs.
1029     Single { index: VariantIdx },
1030
1031     /// Enum-likes with more than one inhabited variant: each variant comes with
1032     /// a *discriminant* (usually the same as the variant index but the user can
1033     /// assign explicit discriminant values).  That discriminant is encoded
1034     /// as a *tag* on the machine.  The layout of each variant is
1035     /// a struct, and they all have space reserved for the tag.
1036     /// For enums, the tag is the sole field of the layout.
1037     Multiple {
1038         tag: Scalar,
1039         tag_encoding: TagEncoding,
1040         tag_field: usize,
1041         variants: IndexVec<VariantIdx, Layout>,
1042     },
1043 }
1044
1045 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1046 pub enum TagEncoding {
1047     /// The tag directly stores the discriminant, but possibly with a smaller layout
1048     /// (so converting the tag to the discriminant can require sign extension).
1049     Direct,
1050
1051     /// Niche (values invalid for a type) encoding the discriminant:
1052     /// Discriminant and variant index coincide.
1053     /// The variant `dataful_variant` contains a niche at an arbitrary
1054     /// offset (field `tag_field` of the enum), which for a variant with
1055     /// discriminant `d` is set to
1056     /// `(d - niche_variants.start).wrapping_add(niche_start)`.
1057     ///
1058     /// For example, `Option<(usize, &T)>`  is represented such that
1059     /// `None` has a null pointer for the second tuple field, and
1060     /// `Some` is the identity function (with a non-null reference).
1061     Niche {
1062         dataful_variant: VariantIdx,
1063         niche_variants: RangeInclusive<VariantIdx>,
1064         niche_start: u128,
1065     },
1066 }
1067
1068 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1069 pub struct Niche {
1070     pub offset: Size,
1071     pub scalar: Scalar,
1072 }
1073
1074 impl Niche {
1075     pub fn from_scalar<C: HasDataLayout>(cx: &C, offset: Size, scalar: Scalar) -> Option<Self> {
1076         let niche = Niche { offset, scalar };
1077         if niche.available(cx) > 0 { Some(niche) } else { None }
1078     }
1079
1080     pub fn available<C: HasDataLayout>(&self, cx: &C) -> u128 {
1081         let Scalar { value, valid_range: v } = self.scalar;
1082         let size = value.size(cx);
1083         assert!(size.bits() <= 128);
1084         let max_value = size.unsigned_int_max();
1085
1086         // Find out how many values are outside the valid range.
1087         let niche = v.end.wrapping_add(1)..v.start;
1088         niche.end.wrapping_sub(niche.start) & max_value
1089     }
1090
1091     pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> {
1092         assert!(count > 0);
1093
1094         let Scalar { value, valid_range: v } = self.scalar;
1095         let size = value.size(cx);
1096         assert!(size.bits() <= 128);
1097         let max_value = size.unsigned_int_max();
1098
1099         let niche = v.end.wrapping_add(1)..v.start;
1100         let available = niche.end.wrapping_sub(niche.start) & max_value;
1101         if count > available {
1102             return None;
1103         }
1104
1105         // Extend the range of valid values being reserved by moving either `v.start` or `v.end` bound.
1106         // Given an eventual `Option<T>`, we try to maximize the chance for `None` to occupy the niche of zero.
1107         // This is accomplished by prefering enums with 2 variants(`count==1`) and always taking the shortest path to niche zero.
1108         // Having `None` in niche zero can enable some special optimizations.
1109         //
1110         // Bound selection criteria:
1111         // 1. Select closest to zero given wrapping semantics.
1112         // 2. Avoid moving past zero if possible.
1113         //
1114         // In practice this means that enums with `count > 1` are unlikely to claim niche zero, since they have to fit perfectly.
1115         // If niche zero is already reserved, the selection of bounds are of little interest.
1116         let move_start = |v: WrappingRange| {
1117             let start = v.start.wrapping_sub(count) & max_value;
1118             Some((start, Scalar { value, valid_range: v.with_start(start) }))
1119         };
1120         let move_end = |v: WrappingRange| {
1121             let start = v.end.wrapping_add(1) & max_value;
1122             let end = v.end.wrapping_add(count) & max_value;
1123             Some((start, Scalar { value, valid_range: v.with_end(end) }))
1124         };
1125         let distance_end_zero = max_value - v.end;
1126         if v.start > v.end {
1127             // zero is unavailable because wrapping occurs
1128             move_end(v)
1129         } else if v.start <= distance_end_zero {
1130             if count <= v.start {
1131                 move_start(v)
1132             } else {
1133                 // moved past zero, use other bound
1134                 move_end(v)
1135             }
1136         } else {
1137             let end = v.end.wrapping_add(count) & max_value;
1138             let overshot_zero = (1..=v.end).contains(&end);
1139             if overshot_zero {
1140                 // moved past zero, use other bound
1141                 move_start(v)
1142             } else {
1143                 move_end(v)
1144             }
1145         }
1146     }
1147 }
1148
1149 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1150 pub struct Layout {
1151     /// Says where the fields are located within the layout.
1152     pub fields: FieldsShape,
1153
1154     /// Encodes information about multi-variant layouts.
1155     /// Even with `Multiple` variants, a layout still has its own fields! Those are then
1156     /// shared between all variants. One of them will be the discriminant,
1157     /// but e.g. generators can have more.
1158     ///
1159     /// To access all fields of this layout, both `fields` and the fields of the active variant
1160     /// must be taken into account.
1161     pub variants: Variants,
1162
1163     /// The `abi` defines how this data is passed between functions, and it defines
1164     /// value restrictions via `valid_range`.
1165     ///
1166     /// Note that this is entirely orthogonal to the recursive structure defined by
1167     /// `variants` and `fields`; for example, `ManuallyDrop<Result<isize, isize>>` has
1168     /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants`
1169     /// have to be taken into account to find all fields of this layout.
1170     pub abi: Abi,
1171
1172     /// The leaf scalar with the largest number of invalid values
1173     /// (i.e. outside of its `valid_range`), if it exists.
1174     pub largest_niche: Option<Niche>,
1175
1176     pub align: AbiAndPrefAlign,
1177     pub size: Size,
1178 }
1179
1180 impl Layout {
1181     pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
1182         let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar);
1183         let size = scalar.value.size(cx);
1184         let align = scalar.value.align(cx);
1185         Layout {
1186             variants: Variants::Single { index: VariantIdx::new(0) },
1187             fields: FieldsShape::Primitive,
1188             abi: Abi::Scalar(scalar),
1189             largest_niche,
1190             size,
1191             align,
1192         }
1193     }
1194 }
1195
1196 /// The layout of a type, alongside the type itself.
1197 /// Provides various type traversal APIs (e.g., recursing into fields).
1198 ///
1199 /// Note that the layout is NOT guaranteed to always be identical
1200 /// to that obtained from `layout_of(ty)`, as we need to produce
1201 /// layouts for which Rust types do not exist, such as enum variants
1202 /// or synthetic fields of enums (i.e., discriminants) and fat pointers.
1203 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)]
1204 pub struct TyAndLayout<'a, Ty> {
1205     pub ty: Ty,
1206     pub layout: &'a Layout,
1207 }
1208
1209 impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
1210     type Target = &'a Layout;
1211     fn deref(&self) -> &&'a Layout {
1212         &self.layout
1213     }
1214 }
1215
1216 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1217 pub enum PointerKind {
1218     /// Most general case, we know no restrictions to tell LLVM.
1219     Shared,
1220
1221     /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
1222     Frozen,
1223
1224     /// `&mut T` which is `noalias` but not `readonly`.
1225     UniqueBorrowed,
1226
1227     /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
1228     UniqueOwned,
1229 }
1230
1231 #[derive(Copy, Clone, Debug)]
1232 pub struct PointeeInfo {
1233     pub size: Size,
1234     pub align: Align,
1235     pub safe: Option<PointerKind>,
1236     pub address_space: AddressSpace,
1237 }
1238
1239 /// Trait that needs to be implemented by the higher-level type representation
1240 /// (e.g. `rustc_middle::ty::Ty`), to provide `rustc_target::abi` functionality.
1241 pub trait TyAbiInterface<'a, C>: Sized {
1242     fn ty_and_layout_for_variant(
1243         this: TyAndLayout<'a, Self>,
1244         cx: &C,
1245         variant_index: VariantIdx,
1246     ) -> TyAndLayout<'a, Self>;
1247     fn ty_and_layout_field(this: TyAndLayout<'a, Self>, cx: &C, i: usize) -> TyAndLayout<'a, Self>;
1248     fn ty_and_layout_pointee_info_at(
1249         this: TyAndLayout<'a, Self>,
1250         cx: &C,
1251         offset: Size,
1252     ) -> Option<PointeeInfo>;
1253 }
1254
1255 impl<'a, Ty> TyAndLayout<'a, Ty> {
1256     pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
1257     where
1258         Ty: TyAbiInterface<'a, C>,
1259     {
1260         Ty::ty_and_layout_for_variant(self, cx, variant_index)
1261     }
1262
1263     pub fn field<C>(self, cx: &C, i: usize) -> Self
1264     where
1265         Ty: TyAbiInterface<'a, C>,
1266     {
1267         Ty::ty_and_layout_field(self, cx, i)
1268     }
1269
1270     pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
1271     where
1272         Ty: TyAbiInterface<'a, C>,
1273     {
1274         Ty::ty_and_layout_pointee_info_at(self, cx, offset)
1275     }
1276
1277     pub fn is_single_fp_element<C>(self, cx: &C) -> bool
1278     where
1279         Ty: TyAbiInterface<'a, C>,
1280         C: HasDataLayout,
1281     {
1282         match self.abi {
1283             Abi::Scalar(scalar) => scalar.value.is_float(),
1284             Abi::Aggregate { .. } => {
1285                 if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
1286                     self.field(cx, 0).is_single_fp_element(cx)
1287                 } else {
1288                     false
1289                 }
1290             }
1291             _ => false,
1292         }
1293     }
1294 }
1295
1296 impl<'a, Ty> TyAndLayout<'a, Ty> {
1297     /// Returns `true` if the layout corresponds to an unsized type.
1298     pub fn is_unsized(&self) -> bool {
1299         self.abi.is_unsized()
1300     }
1301
1302     /// Returns `true` if the type is a ZST and not unsized.
1303     pub fn is_zst(&self) -> bool {
1304         match self.abi {
1305             Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
1306             Abi::Uninhabited => self.size.bytes() == 0,
1307             Abi::Aggregate { sized } => sized && self.size.bytes() == 0,
1308         }
1309     }
1310
1311     /// Determines if this type permits "raw" initialization by just transmuting some
1312     /// memory into an instance of `T`.
1313     /// `zero` indicates if the memory is zero-initialized, or alternatively
1314     /// left entirely uninitialized.
1315     /// This is conservative: in doubt, it will answer `true`.
1316     ///
1317     /// FIXME: Once we removed all the conservatism, we could alternatively
1318     /// create an all-0/all-undef constant and run the const value validator to see if
1319     /// this is a valid value for the given type.
1320     pub fn might_permit_raw_init<C>(self, cx: &C, zero: bool) -> bool
1321     where
1322         Self: Copy,
1323         Ty: TyAbiInterface<'a, C>,
1324         C: HasDataLayout,
1325     {
1326         let scalar_allows_raw_init = move |s: Scalar| -> bool {
1327             if zero {
1328                 // The range must contain 0.
1329                 s.valid_range.contains(0)
1330             } else {
1331                 // The range must include all values.
1332                 s.is_always_valid(cx)
1333             }
1334         };
1335
1336         // Check the ABI.
1337         let valid = match self.abi {
1338             Abi::Uninhabited => false, // definitely UB
1339             Abi::Scalar(s) => scalar_allows_raw_init(s),
1340             Abi::ScalarPair(s1, s2) => scalar_allows_raw_init(s1) && scalar_allows_raw_init(s2),
1341             Abi::Vector { element: s, count } => count == 0 || scalar_allows_raw_init(s),
1342             Abi::Aggregate { .. } => true, // Fields are checked below.
1343         };
1344         if !valid {
1345             // This is definitely not okay.
1346             return false;
1347         }
1348
1349         // If we have not found an error yet, we need to recursively descend into fields.
1350         match &self.fields {
1351             FieldsShape::Primitive | FieldsShape::Union { .. } => {}
1352             FieldsShape::Array { .. } => {
1353                 // FIXME(#66151): For now, we are conservative and do not check arrays.
1354             }
1355             FieldsShape::Arbitrary { offsets, .. } => {
1356                 for idx in 0..offsets.len() {
1357                     if !self.field(cx, idx).might_permit_raw_init(cx, zero) {
1358                         // We found a field that is unhappy with this kind of initialization.
1359                         return false;
1360                     }
1361                 }
1362             }
1363         }
1364
1365         // FIXME(#66151): For now, we are conservative and do not check `self.variants`.
1366         true
1367     }
1368 }