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    Align, BackendRepr, FieldsShape, Float, HasDataLayout, Integer, LayoutData, Niche, Numeric,
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]#[doc(hidden)]unsafe impl<'a>
    ::core::clone::TrivialClone for Layout<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for Layout<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'a,
                LayoutData<FieldIdx, VariantIdx>>>;
        *self
    }
}Clone, #[automatically_derived]impl<'a> ::core::marker::StructuralPartialEq for
    Layout<'a> {
}
#[automatically_derived]impl<'a> ::core::cmp::PartialEq for Layout<'a> {
    #[inline]
    fn eq(&self, other: &Self) -> 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#[cfg_attr(bootstrap, rustc_pass_by_value)]
18#[cfg_attr(not(bootstrap), lint::pass_by_value)]
19pub struct Layout<'a>(pub Interned<'a, LayoutData<FieldIdx, VariantIdx>>);
20
21impl<'a> fmt::Debug for Layout<'a> {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        // See comment on `<LayoutData as Debug>::fmt` above.
24        self.0.0.fmt(f)
25    }
26}
27
28impl<'a> Deref for Layout<'a> {
29    type Target = &'a LayoutData<FieldIdx, VariantIdx>;
30    fn deref(&self) -> &&'a LayoutData<FieldIdx, VariantIdx> {
31        &self.0.0
32    }
33}
34
35impl<'a> Layout<'a> {
36    pub fn fields(self) -> &'a FieldsShape<FieldIdx> {
37        &self.0.0.fields
38    }
39
40    pub fn variants(self) -> &'a Variants<FieldIdx, VariantIdx> {
41        &self.0.0.variants
42    }
43
44    pub fn backend_repr(self) -> BackendRepr {
45        self.0.0.backend_repr
46    }
47
48    pub fn largest_niche(self) -> Option<Niche> {
49        self.0.0.largest_niche
50    }
51
52    pub fn align(self) -> Align {
53        self.0.0.align
54    }
55
56    pub fn size(self) -> Size {
57        self.0.0.size
58    }
59
60    pub fn max_repr_align(self) -> Option<Align> {
61        self.0.0.max_repr_align
62    }
63
64    pub fn unadjusted_abi_align(self) -> Align {
65        self.0.0.unadjusted_abi_align
66    }
67}
68
69/// The layout of a type, alongside the type itself.
70/// Provides various type traversal APIs (e.g., recursing into fields).
71///
72/// Note that the layout is NOT guaranteed to always be identical
73/// to that obtained from `layout_of(ty)`, as we need to produce
74/// layouts for which Rust types do not exist, such as enum variants
75/// or synthetic fields of enums (i.e., discriminants) and wide pointers.
76#[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]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        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::marker::StructuralPartialEq for TyAndLayout<'a, Ty> {
}
#[automatically_derived]impl<'a, Ty: ::core::cmp::PartialEq>
    ::core::cmp::PartialEq for TyAndLayout<'a, Ty> {
    #[inline]
    fn eq(&self, other: &Self) -> 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)]
77pub struct TyAndLayout<'a, Ty> {
78    pub ty: Ty,
79    pub layout: Layout<'a>,
80}
81
82impl<'a, Ty: fmt::Display> fmt::Debug for TyAndLayout<'a, Ty> {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        // Print the type in a readable way, not its debug representation.
85        f.debug_struct("TyAndLayout")
86            .field("ty", &format_args!("{0}", self.ty)format_args!("{}", self.ty))
87            .field("layout", &self.layout)
88            .finish()
89    }
90}
91
92impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
93    type Target = &'a LayoutData<FieldIdx, VariantIdx>;
94    fn deref(&self) -> &&'a LayoutData<FieldIdx, VariantIdx> {
95        &self.layout.0.0
96    }
97}
98
99impl<'a, Ty> AsRef<LayoutData<FieldIdx, VariantIdx>> for TyAndLayout<'a, Ty> {
100    fn as_ref(&self) -> &LayoutData<FieldIdx, VariantIdx> {
101        &*self.layout.0.0
102    }
103}
104
105/// Trait that needs to be implemented by the higher-level type representation
106/// (e.g. `rustc_middle::ty::Ty`), to provide `rustc_target::abi` functionality.
107pub trait TyAbiInterface<'a, C>: Sized + std::fmt::Debug + std::fmt::Display {
108    fn ty_and_layout_for_variant(
109        this: TyAndLayout<'a, Self>,
110        cx: &C,
111        variant_index: VariantIdx,
112    ) -> TyAndLayout<'a, Self>;
113    fn ty_and_layout_field(this: TyAndLayout<'a, Self>, cx: &C, i: usize) -> TyAndLayout<'a, Self>;
114    fn ty_and_layout_pointee_info_at(
115        this: TyAndLayout<'a, Self>,
116        cx: &C,
117        offset: Size,
118    ) -> Option<PointeeInfo>;
119    fn is_adt(this: TyAndLayout<'a, Self>) -> bool;
120    fn is_enum(this: TyAndLayout<'a, Self>) -> bool;
121    fn is_never(this: TyAndLayout<'a, Self>) -> bool;
122    fn is_tuple(this: TyAndLayout<'a, Self>) -> bool;
123    fn is_unit(this: TyAndLayout<'a, Self>) -> bool;
124    fn is_transparent(this: TyAndLayout<'a, Self>) -> bool;
125    fn is_complex_number_lang_item(this: TyAndLayout<'a, Self>, cx: &C) -> bool;
126    fn is_x87_f80_lang_item(this: TyAndLayout<'a, Self>, cx: &C) -> bool;
127    fn is_scalable_vector(this: TyAndLayout<'a, Self>) -> bool;
128    /// See [`TyAndLayout::pass_indirectly_in_non_rustic_abis`] for details.
129    fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'a, Self>) -> bool;
130}
131
132impl<'a, Ty> TyAndLayout<'a, Ty> {
133    /// Synthetize a layout representing the variant-specific fields of an enum-like layout.
134    ///
135    /// Note that the resulting layout *does not* fully describes `self.ty` at that specific
136    /// variant: prefix fields (e.g. in coroutines) and tag information are lost.
137    ///
138    /// If you don't need type information about the variant's fields, prefer using
139    /// `self.layout.variants` directly.
140    pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
141    where
142        Ty: TyAbiInterface<'a, C>,
143    {
144        Ty::ty_and_layout_for_variant(self, cx, variant_index)
145    }
146
147    pub fn field<C>(self, cx: &C, i: usize) -> Self
148    where
149        Ty: TyAbiInterface<'a, C>,
150    {
151        Ty::ty_and_layout_field(self, cx, i)
152    }
153
154    pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
155    where
156        Ty: TyAbiInterface<'a, C>,
157    {
158        Ty::ty_and_layout_pointee_info_at(self, cx, offset)
159    }
160
161    pub fn is_single_vector_element<C>(self, cx: &C, expected_size: Size) -> bool
162    where
163        Ty: TyAbiInterface<'a, C>,
164        C: HasDataLayout,
165    {
166        match self.backend_repr {
167            BackendRepr::SimdVector { .. } => self.size == expected_size,
168            BackendRepr::Memory { .. } => {
169                if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
170                    self.field(cx, 0).is_single_vector_element(cx, expected_size)
171                } else {
172                    false
173                }
174            }
175            _ => false,
176        }
177    }
178
179    pub fn is_adt<C>(self) -> bool
180    where
181        Ty: TyAbiInterface<'a, C>,
182    {
183        Ty::is_adt(self)
184    }
185
186    pub fn is_enum<C>(self) -> bool
187    where
188        Ty: TyAbiInterface<'a, C>,
189    {
190        Ty::is_enum(self)
191    }
192
193    pub fn is_never<C>(self) -> bool
194    where
195        Ty: TyAbiInterface<'a, C>,
196    {
197        Ty::is_never(self)
198    }
199
200    pub fn is_tuple<C>(self) -> bool
201    where
202        Ty: TyAbiInterface<'a, C>,
203    {
204        Ty::is_tuple(self)
205    }
206
207    pub fn is_unit<C>(self) -> bool
208    where
209        Ty: TyAbiInterface<'a, C>,
210    {
211        Ty::is_unit(self)
212    }
213
214    pub fn is_transparent<C>(self) -> bool
215    where
216        Ty: TyAbiInterface<'a, C>,
217    {
218        Ty::is_transparent(self)
219    }
220
221    /// Returns `true` if this type needs to match the ABI of the C `_Complex` type. See
222    /// [`TyAndLayout::complex_number`] for details.
223    pub fn is_complex_number<C>(self, cx: &C) -> bool
224    where
225        Ty: TyAbiInterface<'a, C> + Copy,
226    {
227        self.complex_number(cx).is_some()
228    }
229
230    pub fn is_scalable_vector<C>(self) -> bool
231    where
232        Ty: TyAbiInterface<'a, C>,
233    {
234        Ty::is_scalable_vector(self)
235    }
236
237    /// Returns `true` if this type is the `x87_f80` lang item.
238    ///
239    /// Note that this function returns `false` for the `x87_f80_raw` lang item.
240    pub fn is_x87_f80<C>(self, cx: &C) -> bool
241    where
242        Ty: TyAbiInterface<'a, C> + Copy,
243    {
244        // A 1-ZST is never x87_f80.
245        Ty::is_x87_f80_lang_item(self.peel_transparent_wrappers_from_non_1zst(cx), cx)
246    }
247
248    /// If this method returns `true`, then this type should always have a `PassMode` of
249    /// `Indirect { mode: IndirectMode::Pointer, .. }` when being used as the argument type of a
250    /// function with a non-Rustic ABI (this is true for structs annotated with the
251    /// `#[rustc_pass_indirectly_in_non_rustic_abis]` attribute).
252    ///
253    /// This is used to replicate some of the behaviour of C array-to-pointer decay; however unlike
254    /// C any changes the caller makes to the passed value will not be reflected in the callee, so
255    /// the attribute is only useful for types where observing the value in the caller after the
256    /// function call isn't allowed (a.k.a. `va_list`).
257    ///
258    /// This function handles transparent types automatically.
259    pub fn pass_indirectly_in_non_rustic_abis<C>(self, cx: &C) -> bool
260    where
261        Ty: TyAbiInterface<'a, C> + Copy,
262    {
263        // FIXME: Peeling the wrappers above would not work correctly if we are a 1-ZST. So we make
264        // `#[rustc_pass_indirectly_in_non_rustic_abis]` a NOP on 1-ZST. In the future,
265        // `non_1zst_field` should become `non_trivial_abi_field` and
266        // `#[rustc_pass_indirectly_in_non_rustic_abis]` should make a type have non-trivial ABI.
267        if self.is_1zst() {
268            return false;
269        }
270
271        let base = self.peel_transparent_wrappers_from_non_1zst(cx);
272        Ty::is_pass_indirectly_in_non_rustic_abis_flag_set(base)
273    }
274
275    /// Recursively peel away transparent wrappers, returning the inner value.
276    /// Will not peel anything if `self` is a 1-ZST! Callers need to either check
277    /// that the result is not a 1-ZST, or have separate logic for that.
278    ///
279    /// The return value is not `repr(transparent)` and/or does
280    /// not have a non-1zst field.
281    pub fn peel_transparent_wrappers_from_non_1zst<C>(mut self, cx: &C) -> Self
282    where
283        Ty: TyAbiInterface<'a, C> + Copy,
284    {
285        while self.is_transparent()
286            && let Some((_, field)) = self.non_1zst_field(cx)
287        {
288            self = field;
289        }
290
291        self
292    }
293
294    /// Finds the one field that is not a 1-ZST.
295    /// Returns `None` if there are multiple non-1-ZST fields or only 1-ZST-fields.
296    pub fn non_1zst_field<C>(&self, cx: &C) -> Option<(FieldIdx, Self)>
297    where
298        Ty: TyAbiInterface<'a, C> + Copy,
299    {
300        let mut found = None;
301        for field_idx in 0..self.fields.count() {
302            let field = self.field(cx, field_idx);
303            if field.is_1zst() {
304                continue;
305            }
306            if found.is_some() {
307                // More than one non-1-ZST field.
308                return None;
309            }
310            found = Some((FieldIdx::from_usize(field_idx), field));
311        }
312        found
313    }
314
315    /// Finds the one field that is not a ZST.
316    /// Returns `None` if there are multiple non-ZST fields or only ZST-fields.
317    ///
318    /// Note that this function checks for ZSTs, not just 1-ZSTs.
319    pub fn non_zst_field_ignore_alignment<C>(&self, cx: &C) -> Option<(FieldIdx, Self)>
320    where
321        Ty: TyAbiInterface<'a, C> + Copy,
322    {
323        let mut found = None;
324        for field_idx in 0..self.fields.count() {
325            let field = self.field(cx, field_idx);
326            if field.is_zst() {
327                continue;
328            }
329            if found.is_some() {
330                // More than one non-ZST field.
331                return None;
332            }
333            found = Some((FieldIdx::from_usize(field_idx), field));
334        }
335        found
336    }
337
338    /// If this type should match the ABI of the C `_Complex` type, returns the primitive that is
339    /// used for its components.
340    ///
341    /// This function only returns `Some(T)` for `core::num::Complex<T>` where `T` is
342    /// either a float or an integer. `repr(transparent)` wrapper types are automatically handled.
343    pub fn complex_number<C>(&self, cx: &C) -> Option<Numeric>
344    where
345        Ty: TyAbiInterface<'a, C> + Copy,
346    {
347        // We're checking for scalar repr below which excludes 1-ZST.
348        let complex = self.peel_transparent_wrappers_from_non_1zst(cx);
349        if !Ty::is_complex_number_lang_item(complex, cx) {
350            return None;
351        }
352
353        let component = complex.field(cx, 0).peel_transparent_wrappers_from_non_1zst(cx);
354
355        if component.is_x87_f80(cx) {
356            return Some(Numeric::Float(Float::X87F80));
357        }
358
359        let BackendRepr::Scalar(scalar) = component.backend_repr else {
360            return None;
361        };
362
363        // Only Complex<{ float }> and Complex<{ integer }> have special layout.
364        //
365        // Explicitly spell out all the float types so that any new ones have to be added to
366        // one of the match branches.
367        let primitive = scalar.primitive();
368        match primitive {
369            Primitive::Bool => Some(Numeric::Int(Integer::I8, false)),
370            Primitive::Int(integer, is_signed) => Some(Numeric::Int(integer, is_signed)),
371            Primitive::Float(
372                float @ (Float::F16 | Float::F32 | Float::F64 | Float::F128 | Float::PpcF128),
373            ) => Some(Numeric::Float(float)),
374            Primitive::Float(Float::X87F80) => None, // x87_f80_raw has incorrect alignment.
375            Primitive::Pointer(..) | Primitive::Float(Float::F16B) => None,
376        }
377    }
378
379    /// Returns `Some` if this type has the ABI of the C `_Complex` type with float components.
380    /// See [`TyAndLayout::complex_number`] for details.
381    pub fn complex_float<C>(&self, cx: &C) -> Option<Float>
382    where
383        Ty: TyAbiInterface<'a, C> + Copy,
384    {
385        match self.complex_number(cx) {
386            Some(Numeric::Float(float)) => Some(float),
387            _ => None,
388        }
389    }
390
391    /// Whether this type/layout has any padding that is dependent on a variant, i.e. has bytes that
392    /// are padding for some, but not all, valid values of this type.
393    pub fn has_variant_dependent_padding<C>(&self, cx: &C) -> bool
394    where
395        Ty: TyAbiInterface<'a, C> + Copy,
396    {
397        match self.variants {
398            Variants::Multiple { .. } => true,
399            Variants::Empty => false,
400            Variants::Single { .. } => match &self.fields {
401                FieldsShape::Primitive | FieldsShape::Union(_) => false,
402                FieldsShape::Array { count, .. } => {
403                    *count > 0 && self.field(cx, 0).has_variant_dependent_padding(cx)
404                }
405                FieldsShape::Arbitrary { offsets, .. } => {
406                    (0..offsets.len()).any(|i| self.field(cx, i).has_variant_dependent_padding(cx))
407                }
408            },
409        }
410    }
411
412    /// The ranges of bytes that are always ignored by the representation relation of this type.
413    ///
414    /// In other words, for any sequence of bytes, if we reset the these padding bytes to uninit,
415    /// then these two sequences of bytes represent the same value (or they are both invalid).
416    /// This is the "guaranteed" padding. There may be more bytes that are padding for some
417    /// but not all variants of this type; those are not included.
418    /// (E.g. `Option<i8>` has no guaranteed padding so the empty range set is returned, but its `None` value still has padding).
419    pub fn variant_independent_padding_ranges<C>(&self, cx: &C) -> Vec<Range<Size>>
420    where
421        Ty: TyAbiInterface<'a, C> + Copy,
422    {
423        let mut data = RangeSet::new();
424        self.add_data_ranges(cx, Size::ZERO, &mut data);
425
426        // Find gaps between the data ranges.
427        let mut uninit_ranges = Vec::new();
428        let mut covered_until = Size::ZERO;
429        for &(offset, size) in data.0.iter() {
430            if offset > covered_until {
431                uninit_ranges.push(covered_until..offset);
432            }
433            covered_until = Ord::max(covered_until, offset + size);
434        }
435
436        // Add trailing padding.
437        if self.size > covered_until {
438            uninit_ranges.push(covered_until..self.size);
439        }
440
441        uninit_ranges
442    }
443
444    /// The ranges of bytes that are ignored by the representation relation of this variant.
445    ///
446    /// The result does not include variant-independent padding.
447    pub fn variant_dependent_padding_ranges<C>(
448        &self,
449        cx: &C,
450        variant_index: VariantIdx,
451    ) -> Vec<Range<Size>>
452    where
453        Ty: TyAbiInterface<'a, C> + Copy,
454    {
455        let Variants::Multiple { .. } = self.variants else {
456            return Vec::new();
457        };
458
459        // Bytes that are data in some variant.
460        let mut any = RangeSet::new();
461        self.add_data_ranges(cx, Size::ZERO, &mut any);
462
463        // Bytes that are data in this variant.
464        let mut this = RangeSet::new();
465
466        // The variants do not contain e.g. the discriminant or coroutine upvars.
467        let FieldsShape::Arbitrary { offsets, in_memory_order: _ } = &self.fields else {
468            {
    ::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")
469        };
470
471        // So add them explicitly.
472        for (field, &offset) in offsets.iter_enumerated() {
473            let field = self.field(cx, field.as_usize());
474            field.add_data_ranges(cx, offset, &mut this);
475        }
476
477        self.for_variant(cx, variant_index).add_data_ranges(cx, Size::ZERO, &mut this);
478
479        // Padding specific to this variant: data in some variant, but not in this one.
480        any.difference(&this).0.iter().map(|&(offset, size)| offset..offset + size).collect()
481    }
482
483    /// Extend `out` with all ranges of bytes that *may* carry relevant data for values of this type.
484    /// For enums and unions there are offsets that are initialized for some
485    /// variants but not for others; those offset *will* get added to `out`.
486    fn add_data_ranges<C>(self, cx: &C, base_offset: Size, out: &mut RangeSet<Size>)
487    where
488        Ty: TyAbiInterface<'a, C> + Copy,
489    {
490        if self.is_zst() {
491            return;
492        }
493
494        // Visit the fields of this value. For enum values the fields include the discriminant.
495        match &self.fields {
496            FieldsShape::Primitive => {
497                out.add_range(base_offset, self.size);
498            }
499            &FieldsShape::Union(field_count) => {
500                for field in 0..field_count.get() {
501                    let field = self.field(cx, field);
502                    field.add_data_ranges(cx, base_offset, out);
503                }
504            }
505            &FieldsShape::Array { stride, count } => {
506                let elem = self.field(cx, 0);
507
508                // For scalars we know there is no padding between the elements,
509                // so the entire array is a single big data range.
510                if elem.backend_repr.is_scalar() {
511                    out.add_range(base_offset, elem.size * count);
512                } else {
513                    // FIXME: this is really inefficient for large arrays.
514                    for idx in 0..count {
515                        elem.add_data_ranges(cx, base_offset + idx * stride, out);
516                    }
517                }
518            }
519            FieldsShape::Arbitrary { offsets, in_memory_order: _ } => {
520                for (field, &offset) in offsets.iter_enumerated() {
521                    let field = self.field(cx, field.as_usize());
522                    field.add_data_ranges(cx, base_offset + offset, out);
523                }
524            }
525        }
526
527        // Visit the fields of each variant.
528        match &self.variants {
529            Variants::Empty | Variants::Single { index: _ } => { /* done */ }
530            Variants::Multiple { variants, .. } => {
531                for variant in variants.indices() {
532                    let variant = self.for_variant(cx, variant);
533                    variant.add_data_ranges(cx, base_offset, out);
534                }
535            }
536        }
537    }
538}