Skip to main content

rustc_abi/layout/
ty.rs

1use std::fmt;
2use std::ops::{Deref, Range};
3
4use rustc_data_structures::intern::Interned;
5use rustc_data_structures::range_set::RangeSet;
6use rustc_macros::StableHash;
7
8use crate::layout::{FieldIdx, VariantIdx};
9use crate::{
10    AbiAlign, Align, BackendRepr, FieldsShape, Float, HasDataLayout, LayoutData, Niche,
11    PointeeInfo, Primitive, Size, Variants,
12};
13
14// Explicitly import `Float` to avoid ambiguity with `Primitive::Float`.
15
16#[derive(#[automatically_derived]
impl<'a> ::core::marker::Copy for Layout<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::clone::Clone for Layout<'a> {
    #[inline]
    fn clone(&self) -> Layout<'a> {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'a,
                LayoutData<FieldIdx, VariantIdx>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::cmp::PartialEq for Layout<'a> {
    #[inline]
    fn eq(&self, other: &Layout<'a>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'a> ::core::cmp::Eq for Layout<'a> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<Interned<'a,
                LayoutData<FieldIdx, VariantIdx>>>;
    }
}Eq, #[automatically_derived]
impl<'a> ::core::hash::Hash for Layout<'a> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<'a> ::rustc_data_structures::stable_hash::StableHash for
            Layout<'a> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Layout(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
17#[rustc_pass_by_value]
18pub struct Layout<'a>(pub Interned<'a, LayoutData<FieldIdx, VariantIdx>>);
19
20impl<'a> fmt::Debug for Layout<'a> {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        // See comment on `<LayoutData as Debug>::fmt` above.
23        self.0.0.fmt(f)
24    }
25}
26
27impl<'a> Deref for Layout<'a> {
28    type Target = &'a LayoutData<FieldIdx, VariantIdx>;
29    fn deref(&self) -> &&'a LayoutData<FieldIdx, VariantIdx> {
30        &self.0.0
31    }
32}
33
34impl<'a> Layout<'a> {
35    pub fn fields(self) -> &'a FieldsShape<FieldIdx> {
36        &self.0.0.fields
37    }
38
39    pub fn variants(self) -> &'a Variants<FieldIdx, VariantIdx> {
40        &self.0.0.variants
41    }
42
43    pub fn backend_repr(self) -> BackendRepr {
44        self.0.0.backend_repr
45    }
46
47    pub fn largest_niche(self) -> Option<Niche> {
48        self.0.0.largest_niche
49    }
50
51    pub fn align(self) -> AbiAlign {
52        self.0.0.align
53    }
54
55    pub fn size(self) -> Size {
56        self.0.0.size
57    }
58
59    pub fn max_repr_align(self) -> Option<Align> {
60        self.0.0.max_repr_align
61    }
62
63    pub fn unadjusted_abi_align(self) -> Align {
64        self.0.0.unadjusted_abi_align
65    }
66}
67
68/// The layout of a type, alongside the type itself.
69/// Provides various type traversal APIs (e.g., recursing into fields).
70///
71/// Note that the layout is NOT guaranteed to always be identical
72/// to that obtained from `layout_of(ty)`, as we need to produce
73/// layouts for which Rust types do not exist, such as enum variants
74/// or synthetic fields of enums (i.e., discriminants) and wide pointers.
75#[derive(#[automatically_derived]
impl<'a, Ty: ::core::marker::Copy> ::core::marker::Copy for
    TyAndLayout<'a, Ty> {
}Copy, #[automatically_derived]
impl<'a, Ty: ::core::clone::Clone> ::core::clone::Clone for
    TyAndLayout<'a, Ty> {
    #[inline]
    fn clone(&self) -> TyAndLayout<'a, Ty> {
        TyAndLayout {
            ty: ::core::clone::Clone::clone(&self.ty),
            layout: ::core::clone::Clone::clone(&self.layout),
        }
    }
}Clone, #[automatically_derived]
impl<'a, Ty: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
    TyAndLayout<'a, Ty> {
    #[inline]
    fn eq(&self, other: &TyAndLayout<'a, Ty>) -> bool {
        self.ty == other.ty && self.layout == other.layout
    }
}PartialEq, #[automatically_derived]
impl<'a, Ty: ::core::cmp::Eq> ::core::cmp::Eq for TyAndLayout<'a, Ty> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Ty>;
        let _: ::core::cmp::AssertParamIsEq<Layout<'a>>;
    }
}Eq, #[automatically_derived]
impl<'a, Ty: ::core::hash::Hash> ::core::hash::Hash for TyAndLayout<'a, Ty> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.ty, state);
        ::core::hash::Hash::hash(&self.layout, state)
    }
}Hash, const _: () =
    {
        impl<'a, Ty> ::rustc_data_structures::stable_hash::StableHash for
            TyAndLayout<'a, Ty> where
            Ty: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    TyAndLayout { ty: ref __binding_0, layout: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
76pub struct TyAndLayout<'a, Ty> {
77    pub ty: Ty,
78    pub layout: Layout<'a>,
79}
80
81impl<'a, Ty: fmt::Display> fmt::Debug for TyAndLayout<'a, Ty> {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        // Print the type in a readable way, not its debug representation.
84        f.debug_struct("TyAndLayout")
85            .field("ty", &format_args!("{0}", self.ty)format_args!("{}", self.ty))
86            .field("layout", &self.layout)
87            .finish()
88    }
89}
90
91impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
92    type Target = &'a LayoutData<FieldIdx, VariantIdx>;
93    fn deref(&self) -> &&'a LayoutData<FieldIdx, VariantIdx> {
94        &self.layout.0.0
95    }
96}
97
98impl<'a, Ty> AsRef<LayoutData<FieldIdx, VariantIdx>> for TyAndLayout<'a, Ty> {
99    fn as_ref(&self) -> &LayoutData<FieldIdx, VariantIdx> {
100        &*self.layout.0.0
101    }
102}
103
104/// Trait that needs to be implemented by the higher-level type representation
105/// (e.g. `rustc_middle::ty::Ty`), to provide `rustc_target::abi` functionality.
106pub trait TyAbiInterface<'a, C>: Sized + std::fmt::Debug + std::fmt::Display {
107    fn ty_and_layout_for_variant(
108        this: TyAndLayout<'a, Self>,
109        cx: &C,
110        variant_index: VariantIdx,
111    ) -> TyAndLayout<'a, Self>;
112    fn ty_and_layout_field(this: TyAndLayout<'a, Self>, cx: &C, i: usize) -> TyAndLayout<'a, Self>;
113    fn ty_and_layout_pointee_info_at(
114        this: TyAndLayout<'a, Self>,
115        cx: &C,
116        offset: Size,
117    ) -> Option<PointeeInfo>;
118    fn is_adt(this: TyAndLayout<'a, Self>) -> bool;
119    fn is_never(this: TyAndLayout<'a, Self>) -> bool;
120    fn is_tuple(this: TyAndLayout<'a, Self>) -> bool;
121    fn is_unit(this: TyAndLayout<'a, Self>) -> bool;
122    fn is_transparent(this: TyAndLayout<'a, Self>) -> bool;
123    fn is_complex_number(this: TyAndLayout<'a, Self>, cx: &C) -> bool;
124    fn is_scalable_vector(this: TyAndLayout<'a, Self>) -> bool;
125    /// See [`TyAndLayout::pass_indirectly_in_non_rustic_abis`] for details.
126    fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'a, Self>) -> bool;
127}
128
129impl<'a, Ty> TyAndLayout<'a, Ty> {
130    /// Synthetize a layout representing the variant-specific fields of an enum-like layout.
131    ///
132    /// Note that the resulting layout *does not* fully describes `self.ty` at that specific
133    /// variant: prefix fields (e.g. in coroutines) and tag information are lost.
134    ///
135    /// If you don't need type information about the variant's fields, prefer using
136    /// `self.layout.variants` directly.
137    pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
138    where
139        Ty: TyAbiInterface<'a, C>,
140    {
141        Ty::ty_and_layout_for_variant(self, cx, variant_index)
142    }
143
144    pub fn field<C>(self, cx: &C, i: usize) -> Self
145    where
146        Ty: TyAbiInterface<'a, C>,
147    {
148        Ty::ty_and_layout_field(self, cx, i)
149    }
150
151    pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
152    where
153        Ty: TyAbiInterface<'a, C>,
154    {
155        Ty::ty_and_layout_pointee_info_at(self, cx, offset)
156    }
157
158    pub fn is_single_fp_element<C>(self, cx: &C) -> bool
159    where
160        Ty: TyAbiInterface<'a, C>,
161        C: HasDataLayout,
162    {
163        match self.backend_repr {
164            BackendRepr::Scalar(scalar) => {
165                #[allow(non_exhaustive_omitted_patterns)] match scalar.primitive() {
    Primitive::Float(Float::F32 | Float::F64) => true,
    _ => false,
}matches!(scalar.primitive(), Primitive::Float(Float::F32 | Float::F64))
166            }
167            BackendRepr::Memory { .. } => {
168                if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
169                    self.field(cx, 0).is_single_fp_element(cx)
170                } else {
171                    false
172                }
173            }
174            _ => false,
175        }
176    }
177
178    pub fn is_single_vector_element<C>(self, cx: &C, expected_size: Size) -> bool
179    where
180        Ty: TyAbiInterface<'a, C>,
181        C: HasDataLayout,
182    {
183        match self.backend_repr {
184            BackendRepr::SimdVector { .. } => self.size == expected_size,
185            BackendRepr::Memory { .. } => {
186                if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
187                    self.field(cx, 0).is_single_vector_element(cx, expected_size)
188                } else {
189                    false
190                }
191            }
192            _ => false,
193        }
194    }
195
196    pub fn is_adt<C>(self) -> bool
197    where
198        Ty: TyAbiInterface<'a, C>,
199    {
200        Ty::is_adt(self)
201    }
202
203    pub fn is_never<C>(self) -> bool
204    where
205        Ty: TyAbiInterface<'a, C>,
206    {
207        Ty::is_never(self)
208    }
209
210    pub fn is_tuple<C>(self) -> bool
211    where
212        Ty: TyAbiInterface<'a, C>,
213    {
214        Ty::is_tuple(self)
215    }
216
217    pub fn is_unit<C>(self) -> bool
218    where
219        Ty: TyAbiInterface<'a, C>,
220    {
221        Ty::is_unit(self)
222    }
223
224    pub fn is_transparent<C>(self) -> bool
225    where
226        Ty: TyAbiInterface<'a, C>,
227    {
228        Ty::is_transparent(self)
229    }
230
231    pub fn is_complex_number<C>(self, cx: &C) -> bool
232    where
233        Ty: TyAbiInterface<'a, C> + Copy,
234    {
235        Ty::is_complex_number(self.peel_transparent_wrappers(cx), cx)
236    }
237
238    pub fn is_scalable_vector<C>(self) -> bool
239    where
240        Ty: TyAbiInterface<'a, C>,
241    {
242        Ty::is_scalable_vector(self)
243    }
244
245    /// If this method returns `true`, then this type should always have a `PassMode` of
246    /// `Indirect { on_stack: false, .. }` when being used as the argument type of a function with a
247    /// non-Rustic ABI (this is true for structs annotated with the
248    /// `#[rustc_pass_indirectly_in_non_rustic_abis]` attribute).
249    ///
250    /// This is used to replicate some of the behaviour of C array-to-pointer decay; however unlike
251    /// C any changes the caller makes to the passed value will not be reflected in the callee, so
252    /// the attribute is only useful for types where observing the value in the caller after the
253    /// function call isn't allowed (a.k.a. `va_list`).
254    ///
255    /// This function handles transparent types automatically.
256    pub fn pass_indirectly_in_non_rustic_abis<C>(self, cx: &C) -> bool
257    where
258        Ty: TyAbiInterface<'a, C> + Copy,
259    {
260        let base = self.peel_transparent_wrappers(cx);
261        Ty::is_pass_indirectly_in_non_rustic_abis_flag_set(base)
262    }
263
264    /// Recursively peel away transparent wrappers, returning the inner value.
265    ///
266    /// The return value is not `repr(transparent)` and/or does
267    /// not have a non-1zst field.
268    pub fn peel_transparent_wrappers<C>(mut self, cx: &C) -> Self
269    where
270        Ty: TyAbiInterface<'a, C> + Copy,
271    {
272        while self.is_transparent()
273            && let Some((_, field)) = self.non_1zst_field(cx)
274        {
275            self = field;
276        }
277
278        self
279    }
280
281    /// Finds the one field that is not a 1-ZST.
282    /// Returns `None` if there are multiple non-1-ZST fields or only 1-ZST-fields.
283    pub fn non_1zst_field<C>(&self, cx: &C) -> Option<(FieldIdx, Self)>
284    where
285        Ty: TyAbiInterface<'a, C> + Copy,
286    {
287        let mut found = None;
288        for field_idx in 0..self.fields.count() {
289            let field = self.field(cx, field_idx);
290            if field.is_1zst() {
291                continue;
292            }
293            if found.is_some() {
294                // More than one non-1-ZST field.
295                return None;
296            }
297            found = Some((FieldIdx::from_usize(field_idx), field));
298        }
299        found
300    }
301
302    pub fn complex_float<C>(&self, cx: &C) -> Option<Float>
303    where
304        Ty: TyAbiInterface<'a, C> + Copy,
305    {
306        if !Ty::is_complex_number(*self, cx) {
307            return None;
308        }
309
310        let BackendRepr::ScalarPair { a, b, .. } = self.backend_repr else {
311            return None;
312        };
313
314        if true {
    {
        match (&a, &b) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(a, b);
315
316        match a.primitive() {
317            Primitive::Float(f) => Some(f),
318            _ => None,
319        }
320    }
321
322    /// Whether this type/layout has any padding that is dependent on a variant, i.e. has bytes that
323    /// are padding for some, but not all, valid values of this type.
324    pub fn has_variant_dependent_padding<C>(&self, cx: &C) -> bool
325    where
326        Ty: TyAbiInterface<'a, C> + Copy,
327    {
328        match self.variants {
329            Variants::Multiple { .. } => true,
330            Variants::Empty => false,
331            Variants::Single { .. } => match &self.fields {
332                FieldsShape::Primitive | FieldsShape::Union(_) => false,
333                FieldsShape::Array { count, .. } => {
334                    *count > 0 && self.field(cx, 0).has_variant_dependent_padding(cx)
335                }
336                FieldsShape::Arbitrary { offsets, .. } => {
337                    (0..offsets.len()).any(|i| self.field(cx, i).has_variant_dependent_padding(cx))
338                }
339            },
340        }
341    }
342
343    /// The ranges of bytes that are always ignored by the representation relation of this type.
344    ///
345    /// In other words, for any sequence of bytes, if we reset the these padding bytes to uninit,
346    /// then these two sequences of bytes represent the same value (or they are both invalid).
347    /// This is the "guaranteed" padding. There may be more bytes that are padding for some
348    /// but not all variants of this type; those are not included.
349    /// (E.g. `Option<i8>` has no guaranteed padding so the empty range set is returned, but its `None` value still has padding).
350    pub fn variant_independent_padding_ranges<C>(&self, cx: &C) -> Vec<Range<Size>>
351    where
352        Ty: TyAbiInterface<'a, C> + Copy,
353    {
354        let mut data = RangeSet::new();
355        self.add_data_ranges(cx, Size::ZERO, &mut data);
356
357        // Find gaps between the data ranges.
358        let mut uninit_ranges = Vec::new();
359        let mut covered_until = Size::ZERO;
360        for &(offset, size) in data.0.iter() {
361            if offset > covered_until {
362                uninit_ranges.push(covered_until..offset);
363            }
364            covered_until = Ord::max(covered_until, offset + size);
365        }
366
367        // Add trailing padding.
368        if self.size > covered_until {
369            uninit_ranges.push(covered_until..self.size);
370        }
371
372        uninit_ranges
373    }
374
375    /// The ranges of bytes that are ignored by the representation relation of this variant.
376    ///
377    /// The result does not include variant-independent padding.
378    pub fn variant_dependent_padding_ranges<C>(
379        &self,
380        cx: &C,
381        variant_index: VariantIdx,
382    ) -> Vec<Range<Size>>
383    where
384        Ty: TyAbiInterface<'a, C> + Copy,
385    {
386        let Variants::Multiple { .. } = self.variants else {
387            return Vec::new();
388        };
389
390        // Bytes that are data in some variant.
391        let mut any = RangeSet::new();
392        self.add_data_ranges(cx, Size::ZERO, &mut any);
393
394        // Bytes that are data in this variant.
395        let mut this = RangeSet::new();
396
397        // The variants do not contain e.g. the discriminant or coroutine upvars.
398        let FieldsShape::Arbitrary { offsets, in_memory_order: _ } = &self.fields else {
399            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("a multi-variant layout should have `Arbitrary` fields")));
}unreachable!("a multi-variant layout should have `Arbitrary` fields")
400        };
401
402        // So add them explicitly.
403        for (field, &offset) in offsets.iter_enumerated() {
404            let field = self.field(cx, field.as_usize());
405            field.add_data_ranges(cx, offset, &mut this);
406        }
407
408        self.for_variant(cx, variant_index).add_data_ranges(cx, Size::ZERO, &mut this);
409
410        // Padding specific to this variant: data in some variant, but not in this one.
411        any.difference(&this).0.iter().map(|&(offset, size)| offset..offset + size).collect()
412    }
413
414    /// Extend `out` with all ranges of bytes that *may* carry relevant data for values of this type.
415    /// For enums and unions there are offsets that are initialized for some
416    /// variants but not for others; those offset *will* get added to `out`.
417    fn add_data_ranges<C>(self, cx: &C, base_offset: Size, out: &mut RangeSet<Size>)
418    where
419        Ty: TyAbiInterface<'a, C> + Copy,
420    {
421        if self.is_zst() {
422            return;
423        }
424
425        // Visit the fields of this value. For enum values the fields include the discriminant.
426        match &self.fields {
427            FieldsShape::Primitive => {
428                out.add_range(base_offset, self.size);
429            }
430            &FieldsShape::Union(field_count) => {
431                for field in 0..field_count.get() {
432                    let field = self.field(cx, field);
433                    field.add_data_ranges(cx, base_offset, out);
434                }
435            }
436            &FieldsShape::Array { stride, count } => {
437                let elem = self.field(cx, 0);
438
439                // For scalars we know there is no padding between the elements,
440                // so the entire array is a single big data range.
441                if elem.backend_repr.is_scalar() {
442                    out.add_range(base_offset, elem.size * count);
443                } else {
444                    // FIXME: this is really inefficient for large arrays.
445                    for idx in 0..count {
446                        elem.add_data_ranges(cx, base_offset + idx * stride, out);
447                    }
448                }
449            }
450            FieldsShape::Arbitrary { offsets, in_memory_order: _ } => {
451                for (field, &offset) in offsets.iter_enumerated() {
452                    let field = self.field(cx, field.as_usize());
453                    field.add_data_ranges(cx, base_offset + offset, out);
454                }
455            }
456        }
457
458        // Visit the fields of each variant.
459        match &self.variants {
460            Variants::Empty | Variants::Single { index: _ } => { /* done */ }
461            Variants::Multiple { variants, .. } => {
462                for variant in variants.indices() {
463                    let variant = self.for_variant(cx, variant);
464                    variant.add_data_ranges(cx, base_offset, out);
465                }
466            }
467        }
468    }
469}