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