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