4 use crate::spec::Target;
6 use std::ops::{Add, AddAssign, Deref, Mul, Range, RangeInclusive, Sub};
8 use rustc_index::vec::{Idx, IndexVec};
9 use rustc_macros::HashStable_Generic;
14 /// Parsed [Data layout](http://llvm.org/docs/LangRef.html#data-layout)
15 /// for a target, which contains everything needed to compute layouts.
16 pub struct TargetDataLayout {
18 pub i1_align: AbiAndPrefAlign,
19 pub i8_align: AbiAndPrefAlign,
20 pub i16_align: AbiAndPrefAlign,
21 pub i32_align: AbiAndPrefAlign,
22 pub i64_align: AbiAndPrefAlign,
23 pub i128_align: AbiAndPrefAlign,
24 pub f32_align: AbiAndPrefAlign,
25 pub f64_align: AbiAndPrefAlign,
26 pub pointer_size: Size,
27 pub pointer_align: AbiAndPrefAlign,
28 pub aggregate_align: AbiAndPrefAlign,
30 /// Alignments for vector types.
31 pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
33 pub instruction_address_space: u32,
36 impl Default for TargetDataLayout {
37 /// Creates an instance of `TargetDataLayout`.
38 fn default() -> TargetDataLayout {
39 let align = |bits| Align::from_bits(bits).unwrap();
42 i1_align: AbiAndPrefAlign::new(align(8)),
43 i8_align: AbiAndPrefAlign::new(align(8)),
44 i16_align: AbiAndPrefAlign::new(align(16)),
45 i32_align: AbiAndPrefAlign::new(align(32)),
46 i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
47 i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
48 f32_align: AbiAndPrefAlign::new(align(32)),
49 f64_align: AbiAndPrefAlign::new(align(64)),
50 pointer_size: Size::from_bits(64),
51 pointer_align: AbiAndPrefAlign::new(align(64)),
52 aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
54 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
55 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
57 instruction_address_space: 0,
62 impl TargetDataLayout {
63 pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
64 // Parse an address space index from a string.
65 let parse_address_space = |s: &str, cause: &str| {
66 s.parse::<u32>().map_err(|err| {
67 format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err)
71 // Parse a bit count from a string.
72 let parse_bits = |s: &str, kind: &str, cause: &str| {
73 s.parse::<u64>().map_err(|err| {
74 format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err)
78 // Parse a size string.
79 let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits);
81 // Parse an alignment string.
82 let align = |s: &[&str], cause: &str| {
84 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
86 let align_from_bits = |bits| {
87 Align::from_bits(bits).map_err(|err| {
88 format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err)
91 let abi = parse_bits(s[0], "alignment", cause)?;
92 let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
93 Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? })
96 let mut dl = TargetDataLayout::default();
97 let mut i128_align_src = 64;
98 for spec in target.data_layout.split('-') {
99 let spec_parts = spec.split(':').collect::<Vec<_>>();
102 ["e"] => dl.endian = Endian::Little,
103 ["E"] => dl.endian = Endian::Big,
104 [p] if p.starts_with('P') => {
105 dl.instruction_address_space = parse_address_space(&p[1..], "P")?
107 ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?,
108 ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?,
109 ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?,
110 [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => {
111 dl.pointer_size = size(s, p)?;
112 dl.pointer_align = align(a, p)?;
114 [s, ref a @ ..] if s.starts_with('i') => {
115 let bits = match s[1..].parse::<u64>() {
118 size(&s[1..], "i")?; // For the user error.
122 let a = align(a, s)?;
124 1 => dl.i1_align = a,
125 8 => dl.i8_align = a,
126 16 => dl.i16_align = a,
127 32 => dl.i32_align = a,
128 64 => dl.i64_align = a,
131 if bits >= i128_align_src && bits <= 128 {
132 // Default alignment for i128 is decided by taking the alignment of
133 // largest-sized i{64..=128}.
134 i128_align_src = bits;
138 [s, ref a @ ..] if s.starts_with('v') => {
139 let v_size = size(&s[1..], "v")?;
140 let a = align(a, s)?;
141 if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
145 // No existing entry, add a new one.
146 dl.vector_align.push((v_size, a));
148 _ => {} // Ignore everything else.
152 // Perform consistency checks against the Target information.
153 let endian_str = match dl.endian {
154 Endian::Little => "little",
155 Endian::Big => "big",
157 if endian_str != target.target_endian {
159 "inconsistent target specification: \"data-layout\" claims \
160 architecture is {}-endian, while \"target-endian\" is `{}`",
161 endian_str, target.target_endian
165 if dl.pointer_size.bits().to_string() != target.target_pointer_width {
167 "inconsistent target specification: \"data-layout\" claims \
168 pointers are {}-bit, while \"target-pointer-width\" is `{}`",
169 dl.pointer_size.bits(),
170 target.target_pointer_width
177 /// Returns exclusive upper bound on object size.
179 /// The theoretical maximum object size is defined as the maximum positive `isize` value.
180 /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
181 /// index every address within an object along with one byte past the end, along with allowing
182 /// `isize` to store the difference between any two pointers into an object.
184 /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
185 /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
186 /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
187 /// address space on 64-bit ARMv8 and x86_64.
188 pub fn obj_size_bound(&self) -> u64 {
189 match self.pointer_size.bits() {
193 bits => panic!("obj_size_bound: unknown pointer bit size {}", bits),
197 pub fn ptr_sized_integer(&self) -> Integer {
198 match self.pointer_size.bits() {
202 bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits),
206 pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
207 for &(size, align) in &self.vector_align {
208 if size == vec_size {
212 // Default to natural alignment, which is what LLVM does.
213 // That is, use the size, rounded up to a power of 2.
214 AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
218 pub trait HasDataLayout {
219 fn data_layout(&self) -> &TargetDataLayout;
222 impl HasDataLayout for TargetDataLayout {
223 fn data_layout(&self) -> &TargetDataLayout {
228 /// Endianness of the target, which must match cfg(target-endian).
229 #[derive(Copy, Clone, PartialEq)]
235 /// Size of a type in bytes.
236 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
237 #[derive(HashStable_Generic)]
243 pub const ZERO: Size = Self::from_bytes(0);
246 pub fn from_bits(bits: u64) -> Size {
247 // Avoid potential overflow from `bits + 7`.
248 Size::from_bytes(bits / 8 + ((bits % 8) + 7) / 8)
252 pub const fn from_bytes(bytes: u64) -> Size {
257 pub fn bytes(self) -> u64 {
262 pub fn bits(self) -> u64 {
263 self.bytes().checked_mul(8).unwrap_or_else(|| {
264 panic!("Size::bits: {} bytes in bits doesn't fit in u64", self.bytes())
269 pub fn align_to(self, align: Align) -> Size {
270 let mask = align.bytes() - 1;
271 Size::from_bytes((self.bytes() + mask) & !mask)
275 pub fn is_aligned(self, align: Align) -> bool {
276 let mask = align.bytes() - 1;
277 self.bytes() & mask == 0
281 pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
282 let dl = cx.data_layout();
284 let bytes = self.bytes().checked_add(offset.bytes())?;
286 if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
290 pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
291 let dl = cx.data_layout();
293 let bytes = self.bytes().checked_mul(count)?;
294 if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
298 // Panicking addition, subtraction and multiplication for convenience.
299 // Avoid during layout computation, return `LayoutError` instead.
304 fn add(self, other: Size) -> Size {
305 Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
306 panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
314 fn sub(self, other: Size) -> Size {
315 Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
316 panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
321 impl Mul<Size> for u64 {
324 fn mul(self, size: Size) -> Size {
329 impl Mul<u64> for Size {
332 fn mul(self, count: u64) -> Size {
333 match self.bytes().checked_mul(count) {
334 Some(bytes) => Size::from_bytes(bytes),
335 None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count),
340 impl AddAssign for Size {
342 fn add_assign(&mut self, other: Size) {
343 *self = *self + other;
347 /// Alignment of a type in bytes (always a power of two).
348 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
349 #[derive(HashStable_Generic)]
355 pub fn from_bits(bits: u64) -> Result<Align, String> {
356 Align::from_bytes(Size::from_bits(bits).bytes())
359 pub fn from_bytes(align: u64) -> Result<Align, String> {
360 // Treat an alignment of 0 bytes like 1-byte alignment.
362 return Ok(Align { pow2: 0 });
365 let mut bytes = align;
366 let mut pow2: u8 = 0;
367 while (bytes & 1) == 0 {
372 return Err(format!("`{}` is not a power of 2", align));
375 return Err(format!("`{}` is too large", align));
381 pub fn bytes(self) -> u64 {
385 pub fn bits(self) -> u64 {
389 /// Computes the best alignment possible for the given offset
390 /// (the largest power of two that the offset is a multiple of).
392 /// N.B., for an offset of `0`, this happens to return `2^64`.
393 pub fn max_for_offset(offset: Size) -> Align {
394 Align { pow2: offset.bytes().trailing_zeros() as u8 }
397 /// Lower the alignment, if necessary, such that the given offset
398 /// is aligned to it (the offset is a multiple of the alignment).
399 pub fn restrict_for_offset(self, offset: Size) -> Align {
400 self.min(Align::max_for_offset(offset))
404 /// A pair of alignments, ABI-mandated and preferred.
405 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
406 #[derive(HashStable_Generic)]
407 pub struct AbiAndPrefAlign {
412 impl AbiAndPrefAlign {
413 pub fn new(align: Align) -> AbiAndPrefAlign {
414 AbiAndPrefAlign { abi: align, pref: align }
417 pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
418 AbiAndPrefAlign { abi: self.abi.min(other.abi), pref: self.pref.min(other.pref) }
421 pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
422 AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) }
426 /// Integers, also used for enum discriminants.
427 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)]
437 pub fn size(self) -> Size {
439 I8 => Size::from_bytes(1),
440 I16 => Size::from_bytes(2),
441 I32 => Size::from_bytes(4),
442 I64 => Size::from_bytes(8),
443 I128 => Size::from_bytes(16),
447 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
448 let dl = cx.data_layout();
455 I128 => dl.i128_align,
459 /// Finds the smallest Integer type which can represent the signed value.
460 pub fn fit_signed(x: i128) -> Integer {
462 -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
463 -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
464 -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
465 -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
470 /// Finds the smallest Integer type which can represent the unsigned value.
471 pub fn fit_unsigned(x: u128) -> Integer {
473 0..=0x0000_0000_0000_00ff => I8,
474 0..=0x0000_0000_0000_ffff => I16,
475 0..=0x0000_0000_ffff_ffff => I32,
476 0..=0xffff_ffff_ffff_ffff => I64,
481 /// Finds the smallest integer with the given alignment.
482 pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
483 let dl = cx.data_layout();
485 for &candidate in &[I8, I16, I32, I64, I128] {
486 if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
487 return Some(candidate);
493 /// Find the largest integer with the given alignment or less.
494 pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
495 let dl = cx.data_layout();
497 // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
498 for &candidate in &[I64, I32, I16] {
499 if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
507 /// Fundamental unit of memory access and layout.
508 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
510 /// The `bool` is the signedness of the `Integer` type.
512 /// One would think we would not care about such details this low down,
513 /// but some ABIs are described in terms of C types and ISAs where the
514 /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
515 /// a negative integer passed by zero-extension will appear positive in
516 /// the callee, and most operations on it will produce the wrong values.
524 pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
525 let dl = cx.data_layout();
528 Int(i, _) => i.size(),
529 F32 => Size::from_bits(32),
530 F64 => Size::from_bits(64),
531 Pointer => dl.pointer_size,
535 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
536 let dl = cx.data_layout();
539 Int(i, _) => i.align(dl),
542 Pointer => dl.pointer_align,
546 pub fn is_float(self) -> bool {
553 pub fn is_int(self) -> bool {
561 /// Information about one scalar component of a Rust type.
562 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
563 #[derive(HashStable_Generic)]
565 pub value: Primitive,
567 /// Inclusive wrap-around range of valid values, that is, if
568 /// start > end, it represents `start..=max_value()`,
569 /// followed by `0..=end`.
571 /// That is, for an i8 primitive, a range of `254..=2` means following
574 /// 254 (-2), 255 (-1), 0, 1, 2
576 /// This is intended specifically to mirror LLVM’s `!range` metadata,
578 // FIXME(eddyb) always use the shortest range, e.g., by finding
579 // the largest space between two consecutive valid values and
580 // taking everything else as the (shortest) valid range.
581 pub valid_range: RangeInclusive<u128>,
585 pub fn is_bool(&self) -> bool {
586 if let Int(I8, _) = self.value { self.valid_range == (0..=1) } else { false }
589 /// Returns the valid range as a `x..y` range.
591 /// If `x` and `y` are equal, the range is full, not empty.
592 pub fn valid_range_exclusive<C: HasDataLayout>(&self, cx: &C) -> Range<u128> {
593 // For a (max) value of -1, max will be `-1 as usize`, which overflows.
594 // However, that is fine here (it would still represent the full range),
595 // i.e., if the range is everything.
596 let bits = self.value.size(cx).bits();
597 assert!(bits <= 128);
598 let mask = !0u128 >> (128 - bits);
599 let start = *self.valid_range.start();
600 let end = *self.valid_range.end();
601 assert_eq!(start, start & mask);
602 assert_eq!(end, end & mask);
603 start..(end.wrapping_add(1) & mask)
607 /// Describes how the fields of a type are located in memory.
608 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
609 pub enum FieldPlacement {
610 /// All fields start at no offset. The `usize` is the field count.
612 /// In the case of primitives the number of fields is `0`.
615 /// Array/vector-like placement, with all fields of identical types.
616 Array { stride: Size, count: u64 },
618 /// Struct-like placement, with precomputed offsets.
620 /// Fields are guaranteed to not overlap, but note that gaps
621 /// before, between and after all the fields are NOT always
622 /// padding, and as such their contents may not be discarded.
623 /// For example, enum variants leave a gap at the start,
624 /// where the discriminant field in the enum layout goes.
626 /// Offsets for the first byte of each field,
627 /// ordered to match the source definition order.
628 /// This vector does not go in increasing order.
629 // FIXME(eddyb) use small vector optimization for the common case.
632 /// Maps source order field indices to memory order indices,
633 /// depending on how the fields were reordered (if at all).
634 /// This is a permutation, with both the source order and the
635 /// memory order using the same (0..n) index ranges.
637 /// Note that during computation of `memory_index`, sometimes
638 /// it is easier to operate on the inverse mapping (that is,
639 /// from memory order to source order), and that is usually
640 /// named `inverse_memory_index`.
642 // FIXME(eddyb) build a better abstraction for permutations, if possible.
643 // FIXME(camlorn) also consider small vector optimization here.
644 memory_index: Vec<u32>,
648 impl FieldPlacement {
649 pub fn count(&self) -> usize {
651 FieldPlacement::Union(count) => count,
652 FieldPlacement::Array { count, .. } => {
653 let usize_count = count as usize;
654 assert_eq!(usize_count as u64, count);
657 FieldPlacement::Arbitrary { ref offsets, .. } => offsets.len(),
661 pub fn offset(&self, i: usize) -> Size {
663 FieldPlacement::Union(count) => {
664 assert!(i < count, "tried to access field {} of union with {} fields", i, count);
667 FieldPlacement::Array { stride, count } => {
672 FieldPlacement::Arbitrary { ref offsets, .. } => offsets[i],
676 pub fn memory_index(&self, i: usize) -> usize {
678 FieldPlacement::Union(_) | FieldPlacement::Array { .. } => i,
679 FieldPlacement::Arbitrary { ref memory_index, .. } => {
680 let r = memory_index[i];
681 assert_eq!(r as usize as u32, r);
687 /// Gets source indices of the fields by increasing offsets.
689 pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item = usize> + 'a {
690 let mut inverse_small = [0u8; 64];
691 let mut inverse_big = vec![];
692 let use_small = self.count() <= inverse_small.len();
694 // We have to write this logic twice in order to keep the array small.
695 if let FieldPlacement::Arbitrary { ref memory_index, .. } = *self {
697 for i in 0..self.count() {
698 inverse_small[memory_index[i] as usize] = i as u8;
701 inverse_big = vec![0; self.count()];
702 for i in 0..self.count() {
703 inverse_big[memory_index[i] as usize] = i as u32;
708 (0..self.count()).map(move |i| match *self {
709 FieldPlacement::Union(_) | FieldPlacement::Array { .. } => i,
710 FieldPlacement::Arbitrary { .. } => {
712 inverse_small[i] as usize
714 inverse_big[i] as usize
721 /// Describes how values of the type are passed by target ABIs,
722 /// in terms of categories of C types there are ABI rules for.
723 #[derive(Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
727 ScalarPair(Scalar, Scalar),
733 /// If true, the size is exact, otherwise it's only a lower bound.
739 /// Returns `true` if the layout corresponds to an unsized type.
740 pub fn is_unsized(&self) -> bool {
742 Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
743 Abi::Aggregate { sized } => !sized,
747 /// Returns `true` if this is a single signed integer scalar
748 pub fn is_signed(&self) -> bool {
750 Abi::Scalar(ref scal) => match scal.value {
751 Primitive::Int(_, signed) => signed,
758 /// Returns `true` if this is an uninhabited type
759 pub fn is_uninhabited(&self) -> bool {
761 Abi::Uninhabited => true,
766 /// Returns `true` is this is a scalar type
767 pub fn is_scalar(&self) -> bool {
769 Abi::Scalar(_) => true,
775 rustc_index::newtype_index! {
776 pub struct VariantIdx {
777 derive [HashStable_Generic]
781 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
783 /// Single enum variants, structs/tuples, unions, and all non-ADTs.
784 Single { index: VariantIdx },
786 /// Enum-likes with more than one inhabited variant: for each case there is
787 /// a struct, and they all have space reserved for the discriminant.
788 /// For enums this is the sole field of the layout.
791 discr_kind: DiscriminantKind,
793 variants: IndexVec<VariantIdx, LayoutDetails>,
797 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
798 pub enum DiscriminantKind {
799 /// Integer tag holding the discriminant value itself.
802 /// Niche (values invalid for a type) encoding the discriminant:
803 /// the variant `dataful_variant` contains a niche at an arbitrary
804 /// offset (field `discr_index` of the enum), which for a variant with
805 /// discriminant `d` is set to
806 /// `(d - niche_variants.start).wrapping_add(niche_start)`.
808 /// For example, `Option<(usize, &T)>` is represented such that
809 /// `None` has a null pointer for the second tuple field, and
810 /// `Some` is the identity function (with a non-null reference).
812 dataful_variant: VariantIdx,
813 niche_variants: RangeInclusive<VariantIdx>,
818 #[derive(Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
825 pub fn from_scalar<C: HasDataLayout>(cx: &C, offset: Size, scalar: Scalar) -> Option<Self> {
826 let niche = Niche { offset, scalar };
827 if niche.available(cx) > 0 { Some(niche) } else { None }
830 pub fn available<C: HasDataLayout>(&self, cx: &C) -> u128 {
831 let Scalar { value, valid_range: ref v } = self.scalar;
832 let bits = value.size(cx).bits();
833 assert!(bits <= 128);
834 let max_value = !0u128 >> (128 - bits);
836 // Find out how many values are outside the valid range.
837 let niche = v.end().wrapping_add(1)..*v.start();
838 niche.end.wrapping_sub(niche.start) & max_value
841 pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> {
844 let Scalar { value, valid_range: ref v } = self.scalar;
845 let bits = value.size(cx).bits();
846 assert!(bits <= 128);
847 let max_value = !0u128 >> (128 - bits);
849 if count > max_value {
853 // Compute the range of invalid values being reserved.
854 let start = v.end().wrapping_add(1) & max_value;
855 let end = v.end().wrapping_add(count) & max_value;
857 // If the `end` of our range is inside the valid range,
858 // then we ran out of invalid values.
859 // FIXME(eddyb) abstract this with a wraparound range type.
860 let valid_range_contains = |x| {
861 if v.start() <= v.end() {
862 *v.start() <= x && x <= *v.end()
864 *v.start() <= x || x <= *v.end()
867 if valid_range_contains(end) {
871 Some((start, Scalar { value, valid_range: *v.start()..=end }))
875 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
876 pub struct LayoutDetails {
877 /// Says where the fields are located within the layout.
878 /// Primitives and uninhabited enums appear as unions without fields.
879 pub fields: FieldPlacement,
881 /// Encodes information about multi-variant layouts.
882 /// Even with `Multiple` variants, a layout still has its own fields! Those are then
883 /// shared between all variants. One of them will be the discriminant,
884 /// but e.g. generators can have more.
886 /// To access all fields of this layout, both `fields` and the fields of the active variant
887 /// must be taken into account.
888 pub variants: Variants,
890 /// The `abi` defines how this data is passed between functions, and it defines
891 /// value restrictions via `valid_range`.
893 /// Note that this is entirely orthogonal to the recursive structure defined by
894 /// `variants` and `fields`; for example, `ManuallyDrop<Result<isize, isize>>` has
895 /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants`
896 /// have to be taken into account to find all fields of this layout.
899 /// The leaf scalar with the largest number of invalid values
900 /// (i.e. outside of its `valid_range`), if it exists.
901 pub largest_niche: Option<Niche>,
903 pub align: AbiAndPrefAlign,
908 pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
909 let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar.clone());
910 let size = scalar.value.size(cx);
911 let align = scalar.value.align(cx);
913 variants: Variants::Single { index: VariantIdx::new(0) },
914 fields: FieldPlacement::Union(0),
915 abi: Abi::Scalar(scalar),
923 /// The details of the layout of a type, alongside the type itself.
924 /// Provides various type traversal APIs (e.g., recursing into fields).
926 /// Note that the details are NOT guaranteed to always be identical
927 /// to those obtained from `layout_of(ty)`, as we need to produce
928 /// layouts for which Rust types do not exist, such as enum variants
929 /// or synthetic fields of enums (i.e., discriminants) and fat pointers.
930 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
931 pub struct TyLayout<'a, Ty> {
933 pub details: &'a LayoutDetails,
936 impl<'a, Ty> Deref for TyLayout<'a, Ty> {
937 type Target = &'a LayoutDetails;
938 fn deref(&self) -> &&'a LayoutDetails {
943 /// Trait for context types that can compute layouts of things.
948 fn layout_of(&self, ty: Self::Ty) -> Self::TyLayout;
949 fn spanned_layout_of(&self, ty: Self::Ty, _span: Span) -> Self::TyLayout {
954 /// The `TyLayout` above will always be a `MaybeResult<TyLayout<'_, Self>>`.
955 /// We can't add the bound due to the lifetime, but this trait is still useful when
956 /// writing code that's generic over the `LayoutOf` impl.
957 pub trait MaybeResult<T> {
960 fn from(x: Result<T, Self::Error>) -> Self;
961 fn to_result(self) -> Result<T, Self::Error>;
964 impl<T> MaybeResult<T> for T {
967 fn from(Ok(x): Result<T, Self::Error>) -> Self {
970 fn to_result(self) -> Result<T, Self::Error> {
975 impl<T, E> MaybeResult<T> for Result<T, E> {
978 fn from(x: Result<T, Self::Error>) -> Self {
981 fn to_result(self) -> Result<T, Self::Error> {
986 #[derive(Copy, Clone, PartialEq, Eq)]
987 pub enum PointerKind {
988 /// Most general case, we know no restrictions to tell LLVM.
991 /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
994 /// `&mut T`, when we know `noalias` is safe for LLVM.
997 /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
1001 #[derive(Copy, Clone)]
1002 pub struct PointeeInfo {
1005 pub safe: Option<PointerKind>,
1008 pub trait TyLayoutMethods<'a, C: LayoutOf<Ty = Self>>: Sized {
1010 this: TyLayout<'a, Self>,
1012 variant_index: VariantIdx,
1013 ) -> TyLayout<'a, Self>;
1014 fn field(this: TyLayout<'a, Self>, cx: &C, i: usize) -> C::TyLayout;
1015 fn pointee_info_at(this: TyLayout<'a, Self>, cx: &C, offset: Size) -> Option<PointeeInfo>;
1018 impl<'a, Ty> TyLayout<'a, Ty> {
1019 pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
1021 Ty: TyLayoutMethods<'a, C>,
1022 C: LayoutOf<Ty = Ty>,
1024 Ty::for_variant(self, cx, variant_index)
1027 /// Callers might want to use `C: LayoutOf<Ty=Ty, TyLayout: MaybeResult<Self>>`
1028 /// to allow recursion (see `might_permit_zero_init` below for an example).
1029 pub fn field<C>(self, cx: &C, i: usize) -> C::TyLayout
1031 Ty: TyLayoutMethods<'a, C>,
1032 C: LayoutOf<Ty = Ty>,
1034 Ty::field(self, cx, i)
1037 pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
1039 Ty: TyLayoutMethods<'a, C>,
1040 C: LayoutOf<Ty = Ty>,
1042 Ty::pointee_info_at(self, cx, offset)
1046 impl<'a, Ty> TyLayout<'a, Ty> {
1047 /// Returns `true` if the layout corresponds to an unsized type.
1048 pub fn is_unsized(&self) -> bool {
1049 self.abi.is_unsized()
1052 /// Returns `true` if the type is a ZST and not unsized.
1053 pub fn is_zst(&self) -> bool {
1055 Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
1056 Abi::Uninhabited => self.size.bytes() == 0,
1057 Abi::Aggregate { sized } => sized && self.size.bytes() == 0,
1061 /// Determines if this type permits "raw" initialization by just transmuting some
1062 /// memory into an instance of `T`.
1063 /// `zero` indicates if the memory is zero-initialized, or alternatively
1064 /// left entirely uninitialized.
1065 /// This is conservative: in doubt, it will answer `true`.
1067 /// FIXME: Once we removed all the conservatism, we could alternatively
1068 /// create an all-0/all-undef constant and run the const value validator to see if
1069 /// this is a valid value for the given type.
1070 pub fn might_permit_raw_init<C, E>(self, cx: &C, zero: bool) -> Result<bool, E>
1073 Ty: TyLayoutMethods<'a, C>,
1074 C: LayoutOf<Ty = Ty, TyLayout: MaybeResult<Self, Error = E>> + HasDataLayout,
1076 let scalar_allows_raw_init = move |s: &Scalar| -> bool {
1078 let range = &s.valid_range;
1079 // The range must contain 0.
1080 range.contains(&0) || (*range.start() > *range.end()) // wrap-around allows 0
1082 // The range must include all values. `valid_range_exclusive` handles
1083 // the wrap-around using target arithmetic; with wrap-around then the full
1084 // range is one where `start == end`.
1085 let range = s.valid_range_exclusive(cx);
1086 range.start == range.end
1091 let valid = match &self.abi {
1092 Abi::Uninhabited => false, // definitely UB
1093 Abi::Scalar(s) => scalar_allows_raw_init(s),
1094 Abi::ScalarPair(s1, s2) => scalar_allows_raw_init(s1) && scalar_allows_raw_init(s2),
1095 Abi::Vector { element: s, count } => *count == 0 || scalar_allows_raw_init(s),
1096 Abi::Aggregate { .. } => true, // Cannot be excluded *right now*.
1099 // This is definitely not okay.
1100 trace!("might_permit_raw_init({:?}, zero={}): not valid", self.details, zero);
1104 // If we have not found an error yet, we need to recursively descend.
1105 // FIXME(#66151): For now, we are conservative and do not do this.