4 use crate::spec::Target;
6 use std::convert::{TryFrom, TryInto};
7 use std::num::NonZeroUsize;
8 use std::ops::{Add, AddAssign, Deref, Mul, Range, RangeInclusive, Sub};
10 use rustc_index::vec::{Idx, IndexVec};
11 use rustc_macros::HashStable_Generic;
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 {
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,
32 /// Alignments for vector types.
33 pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
35 pub instruction_address_space: AddressSpace,
38 impl Default for TargetDataLayout {
39 /// Creates an instance of `TargetDataLayout`.
40 fn default() -> TargetDataLayout {
41 let align = |bits| Align::from_bits(bits).unwrap();
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) },
56 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
57 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
59 instruction_address_space: AddressSpace::DATA,
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)
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)
80 // Parse a size string.
81 let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits);
83 // Parse an alignment string.
84 let align = |s: &[&str], cause: &str| {
86 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
88 let align_from_bits = |bits| {
89 Align::from_bits(bits).map_err(|err| {
90 format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err)
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)? })
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<_>>();
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")?
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)?;
116 [s, ref a @ ..] if s.starts_with('i') => {
117 let bits = match s[1..].parse::<u64>() {
120 size(&s[1..], "i")?; // For the user error.
124 let a = align(a, s)?;
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,
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;
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) {
147 // No existing entry, add a new one.
148 dl.vector_align.push((v_size, a));
150 _ => {} // Ignore everything else.
154 // Perform consistency checks against the Target information.
155 let endian_str = match dl.endian {
156 Endian::Little => "little",
157 Endian::Big => "big",
159 if endian_str != target.target_endian {
161 "inconsistent target specification: \"data-layout\" claims \
162 architecture is {}-endian, while \"target-endian\" is `{}`",
163 endian_str, target.target_endian
167 if dl.pointer_size.bits().to_string() != target.target_pointer_width {
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
179 /// Returns exclusive upper bound on object size.
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.
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() {
195 bits => panic!("obj_size_bound: unknown pointer bit size {}", bits),
199 pub fn ptr_sized_integer(&self) -> Integer {
200 match self.pointer_size.bits() {
204 bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits),
208 pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
209 for &(size, align) in &self.vector_align {
210 if size == vec_size {
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())
220 pub trait HasDataLayout {
221 fn data_layout(&self) -> &TargetDataLayout;
224 impl HasDataLayout for TargetDataLayout {
225 fn data_layout(&self) -> &TargetDataLayout {
230 /// Endianness of the target, which must match cfg(target-endian).
231 #[derive(Copy, Clone, PartialEq)]
237 /// Size of a type in bytes.
238 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
239 #[derive(HashStable_Generic)]
245 pub const ZERO: Size = Size { raw: 0 };
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)
255 pub fn from_bytes(bytes: impl TryInto<u64>) -> Size {
256 Size { raw: bytes.try_into().ok().unwrap() }
260 pub fn bytes(self) -> u64 {
265 pub fn bytes_usize(self) -> usize {
266 self.bytes().try_into().unwrap()
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())
277 pub fn bits_usize(self) -> usize {
278 self.bits().try_into().unwrap()
282 pub fn align_to(self, align: Align) -> Size {
283 let mask = align.bytes() - 1;
284 Size::from_bytes((self.bytes() + mask) & !mask)
288 pub fn is_aligned(self, align: Align) -> bool {
289 let mask = align.bytes() - 1;
290 self.bytes() & mask == 0
294 pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
295 let dl = cx.data_layout();
297 let bytes = self.bytes().checked_add(offset.bytes())?;
299 if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
303 pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
304 let dl = cx.data_layout();
306 let bytes = self.bytes().checked_mul(count)?;
307 if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
311 // Panicking addition, subtraction and multiplication for convenience.
312 // Avoid during layout computation, return `LayoutError` instead.
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())
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())
334 impl Mul<Size> for u64 {
337 fn mul(self, size: Size) -> Size {
342 impl Mul<u64> for Size {
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),
353 impl AddAssign for Size {
355 fn add_assign(&mut self, other: Size) {
356 *self = *self + other;
360 /// Alignment of a type in bytes (always a power of two).
361 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
362 #[derive(HashStable_Generic)]
368 pub fn from_bits(bits: u64) -> Result<Align, String> {
369 Align::from_bytes(Size::from_bits(bits).bytes())
372 pub fn from_bytes(align: u64) -> Result<Align, String> {
373 // Treat an alignment of 0 bytes like 1-byte alignment.
375 return Ok(Align { pow2: 0 });
378 let mut bytes = align;
379 let mut pow2: u8 = 0;
380 while (bytes & 1) == 0 {
385 return Err(format!("`{}` is not a power of 2", align));
388 return Err(format!("`{}` is too large", align));
394 pub fn bytes(self) -> u64 {
398 pub fn bits(self) -> u64 {
402 /// Computes the best alignment possible for the given offset
403 /// (the largest power of two that the offset is a multiple of).
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 }
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))
417 /// A pair of alignments, ABI-mandated and preferred.
418 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
419 #[derive(HashStable_Generic)]
420 pub struct AbiAndPrefAlign {
425 impl AbiAndPrefAlign {
426 pub fn new(align: Align) -> AbiAndPrefAlign {
427 AbiAndPrefAlign { abi: align, pref: align }
430 pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
431 AbiAndPrefAlign { abi: self.abi.min(other.abi), pref: self.pref.min(other.pref) }
434 pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
435 AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) }
439 /// Integers, also used for enum discriminants.
440 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)]
450 pub fn size(self) -> Size {
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),
460 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
461 let dl = cx.data_layout();
468 I128 => dl.i128_align,
472 /// Finds the smallest Integer type which can represent the signed value.
473 pub fn fit_signed(x: i128) -> Integer {
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,
483 /// Finds the smallest Integer type which can represent the unsigned value.
484 pub fn fit_unsigned(x: u128) -> Integer {
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,
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();
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);
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();
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() {
520 /// Fundamental unit of memory access and layout.
521 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
523 /// The `bool` is the signedness of the `Integer` type.
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.
537 pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
538 let dl = cx.data_layout();
541 Int(i, _) => i.size(),
542 F32 => Size::from_bits(32),
543 F64 => Size::from_bits(64),
544 Pointer => dl.pointer_size,
548 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
549 let dl = cx.data_layout();
552 Int(i, _) => i.align(dl),
555 Pointer => dl.pointer_align,
559 pub fn is_float(self) -> bool {
566 pub fn is_int(self) -> bool {
574 /// Information about one scalar component of a Rust type.
575 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
576 #[derive(HashStable_Generic)]
578 pub value: Primitive,
580 /// Inclusive wrap-around range of valid values, that is, if
581 /// start > end, it represents `start..=MAX`,
582 /// followed by `0..=end`.
584 /// That is, for an i8 primitive, a range of `254..=2` means following
587 /// 254 (-2), 255 (-1), 0, 1, 2
589 /// This is intended specifically to mirror LLVM’s `!range` metadata,
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>,
598 pub fn is_bool(&self) -> bool {
599 if let Int(I8, _) = self.value { self.valid_range == (0..=1) } else { false }
602 /// Returns the valid range as a `x..y` range.
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)
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.
626 /// All fields start at no offset. The `usize` is the field count.
629 /// Array/vector-like placement, with all fields of identical types.
630 Array { stride: Size, count: u64 },
632 /// Struct-like placement, with precomputed offsets.
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.
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.
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.
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`.
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>,
663 pub fn count(&self) -> usize {
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);
672 FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(),
676 pub fn offset(&self, i: usize) -> Size {
678 FieldsShape::Primitive => {
679 unreachable!("FieldsShape::offset: `Primitive`s have no fields")
681 FieldsShape::Union(count) => {
684 "tried to access field {} of union with {} fields",
690 FieldsShape::Array { stride, count } => {
691 let i = u64::try_from(i).unwrap();
695 FieldsShape::Arbitrary { ref offsets, .. } => offsets[i],
699 pub fn memory_index(&self, i: usize) -> usize {
701 FieldsShape::Primitive => {
702 unreachable!("FieldsShape::memory_index: `Primitive`s have no fields")
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);
713 /// Gets source indices of the fields by increasing offsets.
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();
720 // We have to write this logic twice in order to keep the array small.
721 if let FieldsShape::Arbitrary { ref memory_index, .. } = *self {
723 for i in 0..self.count() {
724 inverse_small[memory_index[i] as usize] = i as u8;
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;
734 (0..self.count()).map(move |i| match *self {
735 FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
736 FieldsShape::Arbitrary { .. } => {
738 inverse_small[i] as usize
740 inverse_big[i] as usize
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);
754 /// The default address space, corresponding to data space.
755 pub const DATA: Self = AddressSpace(0);
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)]
764 ScalarPair(Scalar, Scalar),
770 /// If true, the size is exact, otherwise it's only a lower bound.
776 /// Returns `true` if the layout corresponds to an unsized type.
777 pub fn is_unsized(&self) -> bool {
779 Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
780 Abi::Aggregate { sized } => !sized,
784 /// Returns `true` if this is a single signed integer scalar
785 pub fn is_signed(&self) -> bool {
787 Abi::Scalar(ref scal) => match scal.value {
788 Primitive::Int(_, signed) => signed,
791 _ => panic!("`is_signed` on non-scalar ABI {:?}", self),
795 /// Returns `true` if this is an uninhabited type
796 pub fn is_uninhabited(&self) -> bool {
798 Abi::Uninhabited => true,
803 /// Returns `true` is this is a scalar type
804 pub fn is_scalar(&self) -> bool {
806 Abi::Scalar(_) => true,
812 rustc_index::newtype_index! {
813 pub struct VariantIdx {
814 derive [HashStable_Generic]
818 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
820 /// Single enum variants, structs/tuples, unions, and all non-ADTs.
821 Single { index: VariantIdx },
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.
831 tag_encoding: TagEncoding,
833 variants: IndexVec<VariantIdx, Layout>,
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).
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)`.
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).
854 dataful_variant: VariantIdx,
855 niche_variants: RangeInclusive<VariantIdx>,
860 #[derive(Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
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 }
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);
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
883 pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> {
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);
891 if count > max_value {
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;
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()
906 *v.start() <= x || x <= *v.end()
909 if valid_range_contains(end) {
913 Some((start, Scalar { value, valid_range: *v.start()..=end }))
917 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
919 /// Says where the fields are located within the layout.
920 pub fields: FieldsShape,
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.
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,
931 /// The `abi` defines how this data is passed between functions, and it defines
932 /// value restrictions via `valid_range`.
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.
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>,
944 pub align: AbiAndPrefAlign,
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);
954 variants: Variants::Single { index: VariantIdx::new(0) },
955 fields: FieldsShape::Primitive,
956 abi: Abi::Scalar(scalar),
964 /// The layout of a type, alongside the type itself.
965 /// Provides various type traversal APIs (e.g., recursing into fields).
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> {
974 pub layout: &'a Layout,
977 impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
978 type Target = &'a Layout;
979 fn deref(&self) -> &&'a Layout {
984 /// Trait for context types that can compute layouts of things.
989 fn layout_of(&self, ty: Self::Ty) -> Self::TyAndLayout;
990 fn spanned_layout_of(&self, ty: Self::Ty, _span: Span) -> Self::TyAndLayout {
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> {
1001 fn from(x: Result<T, Self::Error>) -> Self;
1002 fn to_result(self) -> Result<T, Self::Error>;
1005 impl<T> MaybeResult<T> for T {
1008 fn from(Ok(x): Result<T, Self::Error>) -> Self {
1011 fn to_result(self) -> Result<T, Self::Error> {
1016 impl<T, E> MaybeResult<T> for Result<T, E> {
1019 fn from(x: Result<T, Self::Error>) -> Self {
1022 fn to_result(self) -> Result<T, Self::Error> {
1027 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1028 pub enum PointerKind {
1029 /// Most general case, we know no restrictions to tell LLVM.
1032 /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
1035 /// `&mut T`, when we know `noalias` is safe for LLVM.
1038 /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
1042 #[derive(Copy, Clone, Debug)]
1043 pub struct PointeeInfo {
1046 pub safe: Option<PointerKind>,
1047 pub address_space: AddressSpace,
1050 pub trait TyAndLayoutMethods<'a, C: LayoutOf<Ty = Self>>: Sized {
1052 this: TyAndLayout<'a, Self>,
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>;
1060 impl<'a, Ty> TyAndLayout<'a, Ty> {
1061 pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
1063 Ty: TyAndLayoutMethods<'a, C>,
1064 C: LayoutOf<Ty = Ty>,
1066 Ty::for_variant(self, cx, variant_index)
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
1073 Ty: TyAndLayoutMethods<'a, C>,
1074 C: LayoutOf<Ty = Ty>,
1076 Ty::field(self, cx, i)
1079 pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
1081 Ty: TyAndLayoutMethods<'a, C>,
1082 C: LayoutOf<Ty = Ty>,
1084 Ty::pointee_info_at(self, cx, offset)
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()
1094 /// Returns `true` if the type is a ZST and not unsized.
1095 pub fn is_zst(&self) -> bool {
1097 Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
1098 Abi::Uninhabited => self.size.bytes() == 0,
1099 Abi::Aggregate { sized } => sized && self.size.bytes() == 0,
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`.
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>
1115 Ty: TyAndLayoutMethods<'a, C>,
1116 C: LayoutOf<Ty = Ty, TyAndLayout: MaybeResult<Self, Error = E>> + HasDataLayout,
1118 let scalar_allows_raw_init = move |s: &Scalar| -> bool {
1120 let range = &s.valid_range;
1121 // The range must contain 0.
1122 range.contains(&0) || (*range.start() > *range.end()) // wrap-around allows 0
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
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*.
1141 // This is definitely not okay.
1142 trace!("might_permit_raw_init({:?}, zero={}): not valid", self.layout, zero);
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.