4 use crate::spec::Target;
6 use std::convert::{TryFrom, TryInto};
9 use std::num::NonZeroUsize;
10 use std::ops::{Add, AddAssign, Deref, Mul, RangeInclusive, Sub};
11 use std::str::FromStr;
13 use rustc_index::vec::{Idx, IndexVec};
14 use rustc_macros::HashStable_Generic;
15 use rustc_serialize::json::{Json, ToJson};
19 /// Parsed [Data layout](https://llvm.org/docs/LangRef.html#data-layout)
20 /// for a target, which contains everything needed to compute layouts.
21 pub struct TargetDataLayout {
23 pub i1_align: AbiAndPrefAlign,
24 pub i8_align: AbiAndPrefAlign,
25 pub i16_align: AbiAndPrefAlign,
26 pub i32_align: AbiAndPrefAlign,
27 pub i64_align: AbiAndPrefAlign,
28 pub i128_align: AbiAndPrefAlign,
29 pub f32_align: AbiAndPrefAlign,
30 pub f64_align: AbiAndPrefAlign,
31 pub pointer_size: Size,
32 pub pointer_align: AbiAndPrefAlign,
33 pub aggregate_align: AbiAndPrefAlign,
35 /// Alignments for vector types.
36 pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
38 pub instruction_address_space: AddressSpace,
40 /// Minimum size of #[repr(C)] enums (default I32 bits)
41 pub c_enum_min_size: Integer,
44 impl Default for TargetDataLayout {
45 /// Creates an instance of `TargetDataLayout`.
46 fn default() -> TargetDataLayout {
47 let align = |bits| Align::from_bits(bits).unwrap();
50 i1_align: AbiAndPrefAlign::new(align(8)),
51 i8_align: AbiAndPrefAlign::new(align(8)),
52 i16_align: AbiAndPrefAlign::new(align(16)),
53 i32_align: AbiAndPrefAlign::new(align(32)),
54 i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
55 i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
56 f32_align: AbiAndPrefAlign::new(align(32)),
57 f64_align: AbiAndPrefAlign::new(align(64)),
58 pointer_size: Size::from_bits(64),
59 pointer_align: AbiAndPrefAlign::new(align(64)),
60 aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
62 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
63 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
65 instruction_address_space: AddressSpace::DATA,
66 c_enum_min_size: Integer::I32,
71 impl TargetDataLayout {
72 pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
73 // Parse an address space index from a string.
74 let parse_address_space = |s: &str, cause: &str| {
75 s.parse::<u32>().map(AddressSpace).map_err(|err| {
76 format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err)
80 // Parse a bit count from a string.
81 let parse_bits = |s: &str, kind: &str, cause: &str| {
82 s.parse::<u64>().map_err(|err| {
83 format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err)
87 // Parse a size string.
88 let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits);
90 // Parse an alignment string.
91 let align = |s: &[&str], cause: &str| {
93 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
95 let align_from_bits = |bits| {
96 Align::from_bits(bits).map_err(|err| {
97 format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err)
100 let abi = parse_bits(s[0], "alignment", cause)?;
101 let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
102 Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? })
105 let mut dl = TargetDataLayout::default();
106 let mut i128_align_src = 64;
107 for spec in target.data_layout.split('-') {
108 let spec_parts = spec.split(':').collect::<Vec<_>>();
111 ["e"] => dl.endian = Endian::Little,
112 ["E"] => dl.endian = Endian::Big,
113 [p] if p.starts_with('P') => {
114 dl.instruction_address_space = parse_address_space(&p[1..], "P")?
116 ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?,
117 ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?,
118 ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?,
119 [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => {
120 dl.pointer_size = size(s, p)?;
121 dl.pointer_align = align(a, p)?;
123 [s, ref a @ ..] if s.starts_with('i') => {
124 let Ok(bits) = s[1..].parse::<u64>() else {
125 size(&s[1..], "i")?; // For the user error.
128 let a = align(a, s)?;
130 1 => dl.i1_align = a,
131 8 => dl.i8_align = a,
132 16 => dl.i16_align = a,
133 32 => dl.i32_align = a,
134 64 => dl.i64_align = a,
137 if bits >= i128_align_src && bits <= 128 {
138 // Default alignment for i128 is decided by taking the alignment of
139 // largest-sized i{64..=128}.
140 i128_align_src = bits;
144 [s, ref a @ ..] if s.starts_with('v') => {
145 let v_size = size(&s[1..], "v")?;
146 let a = align(a, s)?;
147 if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
151 // No existing entry, add a new one.
152 dl.vector_align.push((v_size, a));
154 _ => {} // Ignore everything else.
158 // Perform consistency checks against the Target information.
159 if dl.endian != target.endian {
161 "inconsistent target specification: \"data-layout\" claims \
162 architecture is {}-endian, while \"target-endian\" is `{}`",
164 target.endian.as_str(),
168 if dl.pointer_size.bits() != target.pointer_width.into() {
170 "inconsistent target specification: \"data-layout\" claims \
171 pointers are {}-bit, while \"target-pointer-width\" is `{}`",
172 dl.pointer_size.bits(),
177 dl.c_enum_min_size = Integer::from_size(Size::from_bits(target.c_enum_min_bits))?;
182 /// Returns exclusive upper bound on object size.
184 /// The theoretical maximum object size is defined as the maximum positive `isize` value.
185 /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
186 /// index every address within an object along with one byte past the end, along with allowing
187 /// `isize` to store the difference between any two pointers into an object.
189 /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
190 /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
191 /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
192 /// address space on 64-bit ARMv8 and x86_64.
194 pub fn obj_size_bound(&self) -> u64 {
195 match self.pointer_size.bits() {
199 bits => panic!("obj_size_bound: unknown pointer bit size {}", bits),
204 pub fn ptr_sized_integer(&self) -> Integer {
205 match self.pointer_size.bits() {
209 bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits),
214 pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
215 for &(size, align) in &self.vector_align {
216 if size == vec_size {
220 // Default to natural alignment, which is what LLVM does.
221 // That is, use the size, rounded up to a power of 2.
222 AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
226 pub trait HasDataLayout {
227 fn data_layout(&self) -> &TargetDataLayout;
230 impl HasDataLayout for TargetDataLayout {
232 fn data_layout(&self) -> &TargetDataLayout {
237 /// Endianness of the target, which must match cfg(target-endian).
238 #[derive(Copy, Clone, PartialEq)]
245 pub fn as_str(&self) -> &'static str {
247 Self::Little => "little",
253 impl fmt::Debug for Endian {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str(self.as_str())
259 impl FromStr for Endian {
262 fn from_str(s: &str) -> Result<Self, Self::Err> {
264 "little" => Ok(Self::Little),
265 "big" => Ok(Self::Big),
266 _ => Err(format!(r#"unknown endian: "{}""#, s)),
271 impl ToJson for Endian {
272 fn to_json(&self) -> Json {
273 self.as_str().to_json()
277 /// Size of a type in bytes.
278 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
279 #[derive(HashStable_Generic)]
281 // The top 3 bits are ALWAYS zero.
286 pub const ZERO: Size = Size { raw: 0 };
288 /// Rounds `bits` up to the next-higher byte boundary, if `bits` is
290 pub fn from_bits(bits: impl TryInto<u64>) -> Size {
291 let bits = bits.try_into().ok().unwrap();
294 fn overflow(bits: u64) -> ! {
295 panic!("Size::from_bits({}) has overflowed", bits);
298 // This is the largest value of `bits` that does not cause overflow
299 // during rounding, and guarantees that the resulting number of bytes
300 // cannot cause overflow when multiplied by 8.
301 if bits > 0xffff_ffff_ffff_fff8 {
305 // Avoid potential overflow from `bits + 7`.
306 Size { raw: bits / 8 + ((bits % 8) + 7) / 8 }
310 pub fn from_bytes(bytes: impl TryInto<u64>) -> Size {
311 let bytes: u64 = bytes.try_into().ok().unwrap();
316 pub fn bytes(self) -> u64 {
321 pub fn bytes_usize(self) -> usize {
322 self.bytes().try_into().unwrap()
326 pub fn bits(self) -> u64 {
331 pub fn bits_usize(self) -> usize {
332 self.bits().try_into().unwrap()
336 pub fn align_to(self, align: Align) -> Size {
337 let mask = align.bytes() - 1;
338 Size::from_bytes((self.bytes() + mask) & !mask)
342 pub fn is_aligned(self, align: Align) -> bool {
343 let mask = align.bytes() - 1;
344 self.bytes() & mask == 0
348 pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
349 let dl = cx.data_layout();
351 let bytes = self.bytes().checked_add(offset.bytes())?;
353 if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
357 pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
358 let dl = cx.data_layout();
360 let bytes = self.bytes().checked_mul(count)?;
361 if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
364 /// Truncates `value` to `self` bits and then sign-extends it to 128 bits
365 /// (i.e., if it is negative, fill with 1's on the left).
367 pub fn sign_extend(self, value: u128) -> u128 {
368 let size = self.bits();
370 // Truncated until nothing is left.
374 let shift = 128 - size;
375 // Shift the unsigned value to the left, then shift back to the right as signed
376 // (essentially fills with sign bit on the left).
377 (((value << shift) as i128) >> shift) as u128
380 /// Truncates `value` to `self` bits.
382 pub fn truncate(self, value: u128) -> u128 {
383 let size = self.bits();
385 // Truncated until nothing is left.
388 let shift = 128 - size;
389 // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
390 (value << shift) >> shift
394 pub fn signed_int_min(&self) -> i128 {
395 self.sign_extend(1_u128 << (self.bits() - 1)) as i128
399 pub fn signed_int_max(&self) -> i128 {
400 i128::MAX >> (128 - self.bits())
404 pub fn unsigned_int_max(&self) -> u128 {
405 u128::MAX >> (128 - self.bits())
409 // Panicking addition, subtraction and multiplication for convenience.
410 // Avoid during layout computation, return `LayoutError` instead.
415 fn add(self, other: Size) -> Size {
416 Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
417 panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
425 fn sub(self, other: Size) -> Size {
426 Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
427 panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
432 impl Mul<Size> for u64 {
435 fn mul(self, size: Size) -> Size {
440 impl Mul<u64> for Size {
443 fn mul(self, count: u64) -> Size {
444 match self.bytes().checked_mul(count) {
445 Some(bytes) => Size::from_bytes(bytes),
446 None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count),
451 impl AddAssign for Size {
453 fn add_assign(&mut self, other: Size) {
454 *self = *self + other;
460 fn steps_between(start: &Self, end: &Self) -> Option<usize> {
461 u64::steps_between(&start.bytes(), &end.bytes())
465 fn forward_checked(start: Self, count: usize) -> Option<Self> {
466 u64::forward_checked(start.bytes(), count).map(Self::from_bytes)
470 fn forward(start: Self, count: usize) -> Self {
471 Self::from_bytes(u64::forward(start.bytes(), count))
475 unsafe fn forward_unchecked(start: Self, count: usize) -> Self {
476 Self::from_bytes(u64::forward_unchecked(start.bytes(), count))
480 fn backward_checked(start: Self, count: usize) -> Option<Self> {
481 u64::backward_checked(start.bytes(), count).map(Self::from_bytes)
485 fn backward(start: Self, count: usize) -> Self {
486 Self::from_bytes(u64::backward(start.bytes(), count))
490 unsafe fn backward_unchecked(start: Self, count: usize) -> Self {
491 Self::from_bytes(u64::backward_unchecked(start.bytes(), count))
495 /// Alignment of a type in bytes (always a power of two).
496 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
497 #[derive(HashStable_Generic)]
503 pub const ONE: Align = Align { pow2: 0 };
506 pub fn from_bits(bits: u64) -> Result<Align, String> {
507 Align::from_bytes(Size::from_bits(bits).bytes())
511 pub fn from_bytes(align: u64) -> Result<Align, String> {
512 // Treat an alignment of 0 bytes like 1-byte alignment.
514 return Ok(Align::ONE);
518 fn not_power_of_2(align: u64) -> String {
519 format!("`{}` is not a power of 2", align)
523 fn too_large(align: u64) -> String {
524 format!("`{}` is too large", align)
527 let mut bytes = align;
528 let mut pow2: u8 = 0;
529 while (bytes & 1) == 0 {
534 return Err(not_power_of_2(align));
537 return Err(too_large(align));
544 pub fn bytes(self) -> u64 {
549 pub fn bits(self) -> u64 {
553 /// Computes the best alignment possible for the given offset
554 /// (the largest power of two that the offset is a multiple of).
556 /// N.B., for an offset of `0`, this happens to return `2^64`.
558 pub fn max_for_offset(offset: Size) -> Align {
559 Align { pow2: offset.bytes().trailing_zeros() as u8 }
562 /// Lower the alignment, if necessary, such that the given offset
563 /// is aligned to it (the offset is a multiple of the alignment).
565 pub fn restrict_for_offset(self, offset: Size) -> Align {
566 self.min(Align::max_for_offset(offset))
570 /// A pair of alignments, ABI-mandated and preferred.
571 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
572 #[derive(HashStable_Generic)]
573 pub struct AbiAndPrefAlign {
578 impl AbiAndPrefAlign {
580 pub fn new(align: Align) -> AbiAndPrefAlign {
581 AbiAndPrefAlign { abi: align, pref: align }
585 pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
586 AbiAndPrefAlign { abi: self.abi.min(other.abi), pref: self.pref.min(other.pref) }
590 pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
591 AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) }
595 /// Integers, also used for enum discriminants.
596 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)]
607 pub fn size(self) -> Size {
609 I8 => Size::from_bytes(1),
610 I16 => Size::from_bytes(2),
611 I32 => Size::from_bytes(4),
612 I64 => Size::from_bytes(8),
613 I128 => Size::from_bytes(16),
617 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
618 let dl = cx.data_layout();
625 I128 => dl.i128_align,
629 /// Finds the smallest Integer type which can represent the signed value.
631 pub fn fit_signed(x: i128) -> Integer {
633 -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
634 -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
635 -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
636 -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
641 /// Finds the smallest Integer type which can represent the unsigned value.
643 pub fn fit_unsigned(x: u128) -> Integer {
645 0..=0x0000_0000_0000_00ff => I8,
646 0..=0x0000_0000_0000_ffff => I16,
647 0..=0x0000_0000_ffff_ffff => I32,
648 0..=0xffff_ffff_ffff_ffff => I64,
653 /// Finds the smallest integer with the given alignment.
654 pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
655 let dl = cx.data_layout();
657 for candidate in [I8, I16, I32, I64, I128] {
658 if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
659 return Some(candidate);
665 /// Find the largest integer with the given alignment or less.
666 pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
667 let dl = cx.data_layout();
669 // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
670 for candidate in [I64, I32, I16] {
671 if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
678 // FIXME(eddyb) consolidate this and other methods that find the appropriate
679 // `Integer` given some requirements.
681 fn from_size(size: Size) -> Result<Self, String> {
683 8 => Ok(Integer::I8),
684 16 => Ok(Integer::I16),
685 32 => Ok(Integer::I32),
686 64 => Ok(Integer::I64),
687 128 => Ok(Integer::I128),
688 _ => Err(format!("rust does not support integers with {} bits", size.bits())),
693 /// Fundamental unit of memory access and layout.
694 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
696 /// The `bool` is the signedness of the `Integer` type.
698 /// One would think we would not care about such details this low down,
699 /// but some ABIs are described in terms of C types and ISAs where the
700 /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
701 /// a negative integer passed by zero-extension will appear positive in
702 /// the callee, and most operations on it will produce the wrong values.
710 pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
711 let dl = cx.data_layout();
714 Int(i, _) => i.size(),
715 F32 => Size::from_bits(32),
716 F64 => Size::from_bits(64),
717 Pointer => dl.pointer_size,
721 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
722 let dl = cx.data_layout();
725 Int(i, _) => i.align(dl),
728 Pointer => dl.pointer_align,
732 // FIXME(eddyb) remove, it's trivial thanks to `matches!`.
734 pub fn is_float(self) -> bool {
735 matches!(self, F32 | F64)
738 // FIXME(eddyb) remove, it's completely unused.
740 pub fn is_int(self) -> bool {
741 matches!(self, Int(..))
745 /// Inclusive wrap-around range of valid values, that is, if
746 /// start > end, it represents `start..=MAX`,
747 /// followed by `0..=end`.
749 /// That is, for an i8 primitive, a range of `254..=2` means following
752 /// 254 (-2), 255 (-1), 0, 1, 2
754 /// This is intended specifically to mirror LLVM’s `!range` metadata semantics.
755 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
756 #[derive(HashStable_Generic)]
757 pub struct WrappingRange {
763 /// Returns `true` if `v` is contained in the range.
765 pub fn contains(&self, v: u128) -> bool {
766 if self.start <= self.end {
767 self.start <= v && v <= self.end
769 self.start <= v || v <= self.end
773 /// Returns `self` with replaced `start`
775 pub fn with_start(mut self, start: u128) -> Self {
780 /// Returns `self` with replaced `end`
782 pub fn with_end(mut self, end: u128) -> Self {
787 /// Returns `true` if `size` completely fills the range.
789 pub fn is_full_for(&self, size: Size) -> bool {
790 let max_value = size.unsigned_int_max();
791 debug_assert!(self.start <= max_value && self.end <= max_value);
792 self.start == (self.end.wrapping_add(1) & max_value)
796 impl fmt::Debug for WrappingRange {
797 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
798 if self.start > self.end {
799 write!(fmt, "(..={}) | ({}..)", self.end, self.start)?;
801 write!(fmt, "{}..={}", self.start, self.end)?;
807 /// Information about one scalar component of a Rust type.
808 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
809 #[derive(HashStable_Generic)]
811 pub value: Primitive,
813 // FIXME(eddyb) always use the shortest range, e.g., by finding
814 // the largest space between two consecutive valid values and
815 // taking everything else as the (shortest) valid range.
816 pub valid_range: WrappingRange,
821 pub fn is_bool(&self) -> bool {
824 Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } }
828 /// Returns `true` if all possible numbers are valid, i.e `valid_range` covers the whole layout
830 pub fn is_always_valid<C: HasDataLayout>(&self, cx: &C) -> bool {
831 self.valid_range.is_full_for(self.value.size(cx))
835 /// Describes how the fields of a type are located in memory.
836 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
837 pub enum FieldsShape {
838 /// Scalar primitives and `!`, which never have fields.
841 /// All fields start at no offset. The `usize` is the field count.
844 /// Array/vector-like placement, with all fields of identical types.
845 Array { stride: Size, count: u64 },
847 /// Struct-like placement, with precomputed offsets.
849 /// Fields are guaranteed to not overlap, but note that gaps
850 /// before, between and after all the fields are NOT always
851 /// padding, and as such their contents may not be discarded.
852 /// For example, enum variants leave a gap at the start,
853 /// where the discriminant field in the enum layout goes.
855 /// Offsets for the first byte of each field,
856 /// ordered to match the source definition order.
857 /// This vector does not go in increasing order.
858 // FIXME(eddyb) use small vector optimization for the common case.
861 /// Maps source order field indices to memory order indices,
862 /// depending on how the fields were reordered (if at all).
863 /// This is a permutation, with both the source order and the
864 /// memory order using the same (0..n) index ranges.
866 /// Note that during computation of `memory_index`, sometimes
867 /// it is easier to operate on the inverse mapping (that is,
868 /// from memory order to source order), and that is usually
869 /// named `inverse_memory_index`.
871 // FIXME(eddyb) build a better abstraction for permutations, if possible.
872 // FIXME(camlorn) also consider small vector optimization here.
873 memory_index: Vec<u32>,
879 pub fn count(&self) -> usize {
881 FieldsShape::Primitive => 0,
882 FieldsShape::Union(count) => count.get(),
883 FieldsShape::Array { count, .. } => count.try_into().unwrap(),
884 FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(),
889 pub fn offset(&self, i: usize) -> Size {
891 FieldsShape::Primitive => {
892 unreachable!("FieldsShape::offset: `Primitive`s have no fields")
894 FieldsShape::Union(count) => {
897 "tried to access field {} of union with {} fields",
903 FieldsShape::Array { stride, count } => {
904 let i = u64::try_from(i).unwrap();
908 FieldsShape::Arbitrary { ref offsets, .. } => offsets[i],
913 pub fn memory_index(&self, i: usize) -> usize {
915 FieldsShape::Primitive => {
916 unreachable!("FieldsShape::memory_index: `Primitive`s have no fields")
918 FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
919 FieldsShape::Arbitrary { ref memory_index, .. } => memory_index[i].try_into().unwrap(),
923 /// Gets source indices of the fields by increasing offsets.
925 pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item = usize> + 'a {
926 let mut inverse_small = [0u8; 64];
927 let mut inverse_big = vec![];
928 let use_small = self.count() <= inverse_small.len();
930 // We have to write this logic twice in order to keep the array small.
931 if let FieldsShape::Arbitrary { ref memory_index, .. } = *self {
933 for i in 0..self.count() {
934 inverse_small[memory_index[i] as usize] = i as u8;
937 inverse_big = vec![0; self.count()];
938 for i in 0..self.count() {
939 inverse_big[memory_index[i] as usize] = i as u32;
944 (0..self.count()).map(move |i| match *self {
945 FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
946 FieldsShape::Arbitrary { .. } => {
948 inverse_small[i] as usize
950 inverse_big[i] as usize
957 /// An identifier that specifies the address space that some operation
958 /// should operate on. Special address spaces have an effect on code generation,
959 /// depending on the target and the address spaces it implements.
960 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
961 pub struct AddressSpace(pub u32);
964 /// The default address space, corresponding to data space.
965 pub const DATA: Self = AddressSpace(0);
968 /// Describes how values of the type are passed by target ABIs,
969 /// in terms of categories of C types there are ABI rules for.
970 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
974 ScalarPair(Scalar, Scalar),
980 /// If true, the size is exact, otherwise it's only a lower bound.
986 /// Returns `true` if the layout corresponds to an unsized type.
988 pub fn is_unsized(&self) -> bool {
990 Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
991 Abi::Aggregate { sized } => !sized,
995 /// Returns `true` if this is a single signed integer scalar
997 pub fn is_signed(&self) -> bool {
999 Abi::Scalar(scal) => match scal.value {
1000 Primitive::Int(_, signed) => signed,
1003 _ => panic!("`is_signed` on non-scalar ABI {:?}", self),
1007 /// Returns `true` if this is an uninhabited type
1009 pub fn is_uninhabited(&self) -> bool {
1010 matches!(*self, Abi::Uninhabited)
1013 /// Returns `true` is this is a scalar type
1015 pub fn is_scalar(&self) -> bool {
1016 matches!(*self, Abi::Scalar(_))
1020 rustc_index::newtype_index! {
1021 pub struct VariantIdx {
1022 derive [HashStable_Generic]
1026 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1028 /// Single enum variants, structs/tuples, unions, and all non-ADTs.
1029 Single { index: VariantIdx },
1031 /// Enum-likes with more than one inhabited variant: each variant comes with
1032 /// a *discriminant* (usually the same as the variant index but the user can
1033 /// assign explicit discriminant values). That discriminant is encoded
1034 /// as a *tag* on the machine. The layout of each variant is
1035 /// a struct, and they all have space reserved for the tag.
1036 /// For enums, the tag is the sole field of the layout.
1039 tag_encoding: TagEncoding,
1041 variants: IndexVec<VariantIdx, Layout>,
1045 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1046 pub enum TagEncoding {
1047 /// The tag directly stores the discriminant, but possibly with a smaller layout
1048 /// (so converting the tag to the discriminant can require sign extension).
1051 /// Niche (values invalid for a type) encoding the discriminant:
1052 /// Discriminant and variant index coincide.
1053 /// The variant `dataful_variant` contains a niche at an arbitrary
1054 /// offset (field `tag_field` of the enum), which for a variant with
1055 /// discriminant `d` is set to
1056 /// `(d - niche_variants.start).wrapping_add(niche_start)`.
1058 /// For example, `Option<(usize, &T)>` is represented such that
1059 /// `None` has a null pointer for the second tuple field, and
1060 /// `Some` is the identity function (with a non-null reference).
1062 dataful_variant: VariantIdx,
1063 niche_variants: RangeInclusive<VariantIdx>,
1068 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1075 pub fn from_scalar<C: HasDataLayout>(cx: &C, offset: Size, scalar: Scalar) -> Option<Self> {
1076 let niche = Niche { offset, scalar };
1077 if niche.available(cx) > 0 { Some(niche) } else { None }
1080 pub fn available<C: HasDataLayout>(&self, cx: &C) -> u128 {
1081 let Scalar { value, valid_range: v } = self.scalar;
1082 let size = value.size(cx);
1083 assert!(size.bits() <= 128);
1084 let max_value = size.unsigned_int_max();
1086 // Find out how many values are outside the valid range.
1087 let niche = v.end.wrapping_add(1)..v.start;
1088 niche.end.wrapping_sub(niche.start) & max_value
1091 pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> {
1094 let Scalar { value, valid_range: v } = self.scalar;
1095 let size = value.size(cx);
1096 assert!(size.bits() <= 128);
1097 let max_value = size.unsigned_int_max();
1099 let niche = v.end.wrapping_add(1)..v.start;
1100 let available = niche.end.wrapping_sub(niche.start) & max_value;
1101 if count > available {
1105 // Extend the range of valid values being reserved by moving either `v.start` or `v.end` bound.
1106 // Given an eventual `Option<T>`, we try to maximize the chance for `None` to occupy the niche of zero.
1107 // This is accomplished by prefering enums with 2 variants(`count==1`) and always taking the shortest path to niche zero.
1108 // Having `None` in niche zero can enable some special optimizations.
1110 // Bound selection criteria:
1111 // 1. Select closest to zero given wrapping semantics.
1112 // 2. Avoid moving past zero if possible.
1114 // In practice this means that enums with `count > 1` are unlikely to claim niche zero, since they have to fit perfectly.
1115 // If niche zero is already reserved, the selection of bounds are of little interest.
1116 let move_start = |v: WrappingRange| {
1117 let start = v.start.wrapping_sub(count) & max_value;
1118 Some((start, Scalar { value, valid_range: v.with_start(start) }))
1120 let move_end = |v: WrappingRange| {
1121 let start = v.end.wrapping_add(1) & max_value;
1122 let end = v.end.wrapping_add(count) & max_value;
1123 Some((start, Scalar { value, valid_range: v.with_end(end) }))
1125 let distance_end_zero = max_value - v.end;
1126 if v.start > v.end {
1127 // zero is unavailable because wrapping occurs
1129 } else if v.start <= distance_end_zero {
1130 if count <= v.start {
1133 // moved past zero, use other bound
1137 let end = v.end.wrapping_add(count) & max_value;
1138 let overshot_zero = (1..=v.end).contains(&end);
1140 // moved past zero, use other bound
1149 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1151 /// Says where the fields are located within the layout.
1152 pub fields: FieldsShape,
1154 /// Encodes information about multi-variant layouts.
1155 /// Even with `Multiple` variants, a layout still has its own fields! Those are then
1156 /// shared between all variants. One of them will be the discriminant,
1157 /// but e.g. generators can have more.
1159 /// To access all fields of this layout, both `fields` and the fields of the active variant
1160 /// must be taken into account.
1161 pub variants: Variants,
1163 /// The `abi` defines how this data is passed between functions, and it defines
1164 /// value restrictions via `valid_range`.
1166 /// Note that this is entirely orthogonal to the recursive structure defined by
1167 /// `variants` and `fields`; for example, `ManuallyDrop<Result<isize, isize>>` has
1168 /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants`
1169 /// have to be taken into account to find all fields of this layout.
1172 /// The leaf scalar with the largest number of invalid values
1173 /// (i.e. outside of its `valid_range`), if it exists.
1174 pub largest_niche: Option<Niche>,
1176 pub align: AbiAndPrefAlign,
1181 pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
1182 let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar);
1183 let size = scalar.value.size(cx);
1184 let align = scalar.value.align(cx);
1186 variants: Variants::Single { index: VariantIdx::new(0) },
1187 fields: FieldsShape::Primitive,
1188 abi: Abi::Scalar(scalar),
1196 /// The layout of a type, alongside the type itself.
1197 /// Provides various type traversal APIs (e.g., recursing into fields).
1199 /// Note that the layout is NOT guaranteed to always be identical
1200 /// to that obtained from `layout_of(ty)`, as we need to produce
1201 /// layouts for which Rust types do not exist, such as enum variants
1202 /// or synthetic fields of enums (i.e., discriminants) and fat pointers.
1203 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)]
1204 pub struct TyAndLayout<'a, Ty> {
1206 pub layout: &'a Layout,
1209 impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
1210 type Target = &'a Layout;
1211 fn deref(&self) -> &&'a Layout {
1216 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1217 pub enum PointerKind {
1218 /// Most general case, we know no restrictions to tell LLVM.
1221 /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
1224 /// `&mut T` which is `noalias` but not `readonly`.
1227 /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
1231 #[derive(Copy, Clone, Debug)]
1232 pub struct PointeeInfo {
1235 pub safe: Option<PointerKind>,
1236 pub address_space: AddressSpace,
1239 /// Trait that needs to be implemented by the higher-level type representation
1240 /// (e.g. `rustc_middle::ty::Ty`), to provide `rustc_target::abi` functionality.
1241 pub trait TyAbiInterface<'a, C>: Sized {
1242 fn ty_and_layout_for_variant(
1243 this: TyAndLayout<'a, Self>,
1245 variant_index: VariantIdx,
1246 ) -> TyAndLayout<'a, Self>;
1247 fn ty_and_layout_field(this: TyAndLayout<'a, Self>, cx: &C, i: usize) -> TyAndLayout<'a, Self>;
1248 fn ty_and_layout_pointee_info_at(
1249 this: TyAndLayout<'a, Self>,
1252 ) -> Option<PointeeInfo>;
1255 impl<'a, Ty> TyAndLayout<'a, Ty> {
1256 pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
1258 Ty: TyAbiInterface<'a, C>,
1260 Ty::ty_and_layout_for_variant(self, cx, variant_index)
1263 pub fn field<C>(self, cx: &C, i: usize) -> Self
1265 Ty: TyAbiInterface<'a, C>,
1267 Ty::ty_and_layout_field(self, cx, i)
1270 pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
1272 Ty: TyAbiInterface<'a, C>,
1274 Ty::ty_and_layout_pointee_info_at(self, cx, offset)
1277 pub fn is_single_fp_element<C>(self, cx: &C) -> bool
1279 Ty: TyAbiInterface<'a, C>,
1283 Abi::Scalar(scalar) => scalar.value.is_float(),
1284 Abi::Aggregate { .. } => {
1285 if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
1286 self.field(cx, 0).is_single_fp_element(cx)
1296 impl<'a, Ty> TyAndLayout<'a, Ty> {
1297 /// Returns `true` if the layout corresponds to an unsized type.
1298 pub fn is_unsized(&self) -> bool {
1299 self.abi.is_unsized()
1302 /// Returns `true` if the type is a ZST and not unsized.
1303 pub fn is_zst(&self) -> bool {
1305 Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
1306 Abi::Uninhabited => self.size.bytes() == 0,
1307 Abi::Aggregate { sized } => sized && self.size.bytes() == 0,
1311 /// Determines if this type permits "raw" initialization by just transmuting some
1312 /// memory into an instance of `T`.
1313 /// `zero` indicates if the memory is zero-initialized, or alternatively
1314 /// left entirely uninitialized.
1315 /// This is conservative: in doubt, it will answer `true`.
1317 /// FIXME: Once we removed all the conservatism, we could alternatively
1318 /// create an all-0/all-undef constant and run the const value validator to see if
1319 /// this is a valid value for the given type.
1320 pub fn might_permit_raw_init<C>(self, cx: &C, zero: bool) -> bool
1323 Ty: TyAbiInterface<'a, C>,
1326 let scalar_allows_raw_init = move |s: Scalar| -> bool {
1328 // The range must contain 0.
1329 s.valid_range.contains(0)
1331 // The range must include all values.
1332 s.is_always_valid(cx)
1337 let valid = match self.abi {
1338 Abi::Uninhabited => false, // definitely UB
1339 Abi::Scalar(s) => scalar_allows_raw_init(s),
1340 Abi::ScalarPair(s1, s2) => scalar_allows_raw_init(s1) && scalar_allows_raw_init(s2),
1341 Abi::Vector { element: s, count } => count == 0 || scalar_allows_raw_init(s),
1342 Abi::Aggregate { .. } => true, // Fields are checked below.
1345 // This is definitely not okay.
1349 // If we have not found an error yet, we need to recursively descend into fields.
1350 match &self.fields {
1351 FieldsShape::Primitive | FieldsShape::Union { .. } => {}
1352 FieldsShape::Array { .. } => {
1353 // FIXME(#66151): For now, we are conservative and do not check arrays.
1355 FieldsShape::Arbitrary { offsets, .. } => {
1356 for idx in 0..offsets.len() {
1357 if !self.field(cx, idx).might_permit_raw_init(cx, zero) {
1358 // We found a field that is unhappy with this kind of initialization.
1365 // FIXME(#66151): For now, we are conservative and do not check `self.variants`.