Skip to main content

rustc_codegen_llvm/debuginfo/metadata/
type_map.rs

1use std::cell::RefCell;
2
3use libc::c_uint;
4use rustc_abi::{Align, Size, VariantIdx};
5use rustc_data_structures::fingerprint::Fingerprint;
6use rustc_data_structures::fx::FxHashMap;
7use rustc_data_structures::stable_hash::{StableHash, StableHasher};
8use rustc_macros::StableHash;
9use rustc_middle::bug;
10use rustc_middle::ty::{self, ExistentialTraitRef, Ty, TyCtxt};
11
12use super::{DefinitionLocation, SmallVec, UNKNOWN_LINE_NUMBER, unknown_file_metadata};
13use crate::common::CodegenCx;
14use crate::debuginfo::utils::{DIB, create_DIArray, debug_context};
15use crate::llvm;
16use crate::llvm::debuginfo::{DIFlags, DIScope, DIType};
17
18mod private {
19    use rustc_macros::StableHash;
20
21    // This type cannot be constructed outside of this module because
22    // it has a private field. We make use of this in order to prevent
23    // `UniqueTypeId` from being constructed directly, without asserting
24    // the preconditions.
25    #[derive(#[automatically_derived]
impl ::core::fmt::Debug for HiddenZst {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "HiddenZst")
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for HiddenZst {
    #[inline]
    fn clone(&self) -> HiddenZst { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for HiddenZst { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for HiddenZst {
    #[inline]
    fn eq(&self, other: &HiddenZst) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for HiddenZst {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for HiddenZst {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {}
}Hash, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for HiddenZst {
            #[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 { HiddenZst => {} }
            }
        }
    };StableHash)]
26    pub(crate) struct HiddenZst;
27}
28
29/// A unique identifier for anything that we create a debuginfo node for.
30/// The types it contains are expected to already be normalized (which
31/// is asserted in the constructors).
32///
33/// Note that there are some things that only show up in debuginfo, like
34/// the separate type descriptions for each enum variant. These get an ID
35/// too because they have their own debuginfo node in LLVM IR.
36#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UniqueTypeId<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            UniqueTypeId::Ty(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Ty",
                    __self_0, &__self_1),
            UniqueTypeId::VariantPart(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "VariantPart", __self_0, &__self_1),
            UniqueTypeId::VariantStructType(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "VariantStructType", __self_0, __self_1, &__self_2),
            UniqueTypeId::VariantStructTypeCppLikeWrapper(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "VariantStructTypeCppLikeWrapper", __self_0, __self_1,
                    &__self_2),
            UniqueTypeId::VTableTy(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "VTableTy", __self_0, __self_1, &__self_2),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for UniqueTypeId<'tcx> {
    #[inline]
    fn clone(&self) -> UniqueTypeId<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<private::HiddenZst>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<private::HiddenZst>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<VariantIdx>;
        let _: ::core::clone::AssertParamIsClone<private::HiddenZst>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<private::HiddenZst>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _:
                ::core::clone::AssertParamIsClone<Option<ExistentialTraitRef<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<private::HiddenZst>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for UniqueTypeId<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for UniqueTypeId<'tcx> {
    #[inline]
    fn eq(&self, other: &UniqueTypeId<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (UniqueTypeId::Ty(__self_0, __self_1),
                    UniqueTypeId::Ty(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (UniqueTypeId::VariantPart(__self_0, __self_1),
                    UniqueTypeId::VariantPart(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (UniqueTypeId::VariantStructType(__self_0, __self_1,
                    __self_2),
                    UniqueTypeId::VariantStructType(__arg1_0, __arg1_1,
                    __arg1_2)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                (UniqueTypeId::VariantStructTypeCppLikeWrapper(__self_0,
                    __self_1, __self_2),
                    UniqueTypeId::VariantStructTypeCppLikeWrapper(__arg1_0,
                    __arg1_1, __arg1_2)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                (UniqueTypeId::VTableTy(__self_0, __self_1, __self_2),
                    UniqueTypeId::VTableTy(__arg1_0, __arg1_1, __arg1_2)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for UniqueTypeId<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<private::HiddenZst>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<private::HiddenZst>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<VariantIdx>;
        let _: ::core::cmp::AssertParamIsEq<private::HiddenZst>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<private::HiddenZst>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _:
                ::core::cmp::AssertParamIsEq<Option<ExistentialTraitRef<'tcx>>>;
        let _: ::core::cmp::AssertParamIsEq<private::HiddenZst>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for UniqueTypeId<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            UniqueTypeId::Ty(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            UniqueTypeId::VariantPart(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            UniqueTypeId::VariantStructType(__self_0, __self_1, __self_2) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state)
            }
            UniqueTypeId::VariantStructTypeCppLikeWrapper(__self_0, __self_1,
                __self_2) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state)
            }
            UniqueTypeId::VTableTy(__self_0, __self_1, __self_2) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state)
            }
        }
    }
}Hash, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            UniqueTypeId<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    UniqueTypeId::Ty(ref __binding_0, ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    UniqueTypeId::VariantPart(ref __binding_0, ref __binding_1)
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    UniqueTypeId::VariantStructType(ref __binding_0,
                        ref __binding_1, ref __binding_2) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                    UniqueTypeId::VariantStructTypeCppLikeWrapper(ref __binding_0,
                        ref __binding_1, ref __binding_2) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                    UniqueTypeId::VTableTy(ref __binding_0, ref __binding_1,
                        ref __binding_2) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
37pub(super) enum UniqueTypeId<'tcx> {
38    /// The ID of a regular type as it shows up at the language level.
39    Ty(Ty<'tcx>, private::HiddenZst),
40    /// The ID for the single DW_TAG_variant_part nested inside the top-level
41    /// DW_TAG_structure_type that describes enums and coroutines.
42    VariantPart(Ty<'tcx>, private::HiddenZst),
43    /// The ID for the artificial struct type describing a single enum variant.
44    VariantStructType(Ty<'tcx>, VariantIdx, private::HiddenZst),
45    /// The ID for the additional wrapper struct type describing an enum variant in CPP-like mode.
46    VariantStructTypeCppLikeWrapper(Ty<'tcx>, VariantIdx, private::HiddenZst),
47    /// The ID of the artificial type we create for VTables.
48    VTableTy(Ty<'tcx>, Option<ExistentialTraitRef<'tcx>>, private::HiddenZst),
49}
50
51impl<'tcx> UniqueTypeId<'tcx> {
52    pub(crate) fn for_ty(tcx: TyCtxt<'tcx>, t: Ty<'tcx>) -> Self {
53        tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), t);
54        UniqueTypeId::Ty(t, private::HiddenZst)
55    }
56
57    pub(crate) fn for_enum_variant_part(tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>) -> Self {
58        tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), enum_ty);
59        UniqueTypeId::VariantPart(enum_ty, private::HiddenZst)
60    }
61
62    pub(crate) fn for_enum_variant_struct_type(
63        tcx: TyCtxt<'tcx>,
64        enum_ty: Ty<'tcx>,
65        variant_idx: VariantIdx,
66    ) -> Self {
67        tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), enum_ty);
68        UniqueTypeId::VariantStructType(enum_ty, variant_idx, private::HiddenZst)
69    }
70
71    pub(crate) fn for_enum_variant_struct_type_wrapper(
72        tcx: TyCtxt<'tcx>,
73        enum_ty: Ty<'tcx>,
74        variant_idx: VariantIdx,
75    ) -> Self {
76        tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), enum_ty);
77        UniqueTypeId::VariantStructTypeCppLikeWrapper(enum_ty, variant_idx, private::HiddenZst)
78    }
79
80    pub(crate) fn for_vtable_ty(
81        tcx: TyCtxt<'tcx>,
82        self_type: Ty<'tcx>,
83        implemented_trait: Option<ExistentialTraitRef<'tcx>>,
84    ) -> Self {
85        tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), self_type);
86        tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), implemented_trait);
87        UniqueTypeId::VTableTy(self_type, implemented_trait, private::HiddenZst)
88    }
89
90    /// Generates a string version of this [UniqueTypeId], which can be used as the `UniqueId`
91    /// argument of the various `LLVMRustDIBuilderCreate*Type()` methods.
92    ///
93    /// Right now this takes the form of a hex-encoded opaque hash value.
94    fn generate_unique_id_string(self, tcx: TyCtxt<'tcx>) -> String {
95        let mut hasher = StableHasher::new();
96        tcx.with_stable_hashing_context(|mut hcx| {
97            hcx.while_hashing_spans(false, |hcx| self.stable_hash(hcx, &mut hasher))
98        });
99        hasher.finish::<Fingerprint>().to_hex()
100    }
101
102    pub(crate) fn expect_ty(self) -> Ty<'tcx> {
103        match self {
104            UniqueTypeId::Ty(ty, _) => ty,
105            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Expected `UniqueTypeId::Ty` but found `{0:?}`",
        self))bug!("Expected `UniqueTypeId::Ty` but found `{:?}`", self),
106        }
107    }
108}
109
110/// The `TypeMap` is where the debug context holds the type metadata nodes
111/// created so far. The debuginfo nodes are identified by `UniqueTypeId`.
112#[derive(#[automatically_derived]
impl<'ll, 'tcx> ::core::default::Default for TypeMap<'ll, 'tcx> {
    #[inline]
    fn default() -> TypeMap<'ll, 'tcx> {
        TypeMap { unique_id_to_di_node: ::core::default::Default::default() }
    }
}Default)]
113pub(crate) struct TypeMap<'ll, 'tcx> {
114    pub(super) unique_id_to_di_node: RefCell<FxHashMap<UniqueTypeId<'tcx>, &'ll DIType>>,
115}
116
117impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
118    /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
119    /// fail if the mapping already exists.
120    pub(super) fn insert(&self, unique_type_id: UniqueTypeId<'tcx>, metadata: &'ll DIType) {
121        if self.unique_id_to_di_node.borrow_mut().insert(unique_type_id, metadata).is_some() {
122            ::rustc_middle::util::bug::bug_fmt(format_args!("type metadata for unique ID \'{0:?}\' is already in the `TypeMap`!",
        unique_type_id));bug!("type metadata for unique ID '{:?}' is already in the `TypeMap`!", unique_type_id);
123        }
124    }
125
126    pub(super) fn di_node_for_unique_id(
127        &self,
128        unique_type_id: UniqueTypeId<'tcx>,
129    ) -> Option<&'ll DIType> {
130        self.unique_id_to_di_node.borrow().get(&unique_type_id).cloned()
131    }
132}
133
134pub(crate) struct DINodeCreationResult<'ll> {
135    pub di_node: &'ll DIType,
136    pub already_stored_in_typemap: bool,
137}
138
139impl<'ll> DINodeCreationResult<'ll> {
140    pub(crate) fn new(di_node: &'ll DIType, already_stored_in_typemap: bool) -> Self {
141        DINodeCreationResult { di_node, already_stored_in_typemap }
142    }
143}
144
145#[derive(#[automatically_derived]
impl<'ll> ::core::fmt::Debug for Stub<'ll> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Stub::Struct => ::core::fmt::Formatter::write_str(f, "Struct"),
            Stub::Union => ::core::fmt::Formatter::write_str(f, "Union"),
            Stub::VTableTy { vtable_holder: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "VTableTy", "vtable_holder", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'ll> ::core::marker::Copy for Stub<'ll> { }Copy, #[automatically_derived]
impl<'ll> ::core::clone::Clone for Stub<'ll> {
    #[inline]
    fn clone(&self) -> Stub<'ll> {
        let _: ::core::clone::AssertParamIsClone<&'ll DIType>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ll> ::core::cmp::Eq for Stub<'ll> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<&'ll DIType>;
    }
}Eq, #[automatically_derived]
impl<'ll> ::core::cmp::PartialEq for Stub<'ll> {
    #[inline]
    fn eq(&self, other: &Stub<'ll>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Stub::VTableTy { vtable_holder: __self_0 }, Stub::VTableTy {
                    vtable_holder: __arg1_0 }) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
146pub(crate) enum Stub<'ll> {
147    Struct,
148    Union,
149    VTableTy { vtable_holder: &'ll DIType },
150}
151
152pub(crate) struct StubInfo<'ll, 'tcx> {
153    metadata: &'ll DIType,
154    unique_type_id: UniqueTypeId<'tcx>,
155}
156
157impl<'ll, 'tcx> StubInfo<'ll, 'tcx> {
158    pub(super) fn new(
159        cx: &CodegenCx<'ll, 'tcx>,
160        unique_type_id: UniqueTypeId<'tcx>,
161        build: impl FnOnce(&CodegenCx<'ll, 'tcx>, /* unique_type_id_str: */ &str) -> &'ll DIType,
162    ) -> StubInfo<'ll, 'tcx> {
163        let unique_type_id_str = unique_type_id.generate_unique_id_string(cx.tcx);
164        let di_node = build(cx, &unique_type_id_str);
165        StubInfo { metadata: di_node, unique_type_id }
166    }
167}
168
169/// Create a stub debuginfo node onto which fields and nested types can be attached.
170pub(super) fn stub<'ll, 'tcx>(
171    cx: &CodegenCx<'ll, 'tcx>,
172    kind: Stub<'ll>,
173    unique_type_id: UniqueTypeId<'tcx>,
174    name: &str,
175    def_location: Option<DefinitionLocation<'ll>>,
176    (size, align): (Size, Align),
177    containing_scope: Option<&'ll DIScope>,
178    flags: DIFlags,
179) -> StubInfo<'ll, 'tcx> {
180    let no_elements: &[Option<&llvm::Metadata>] = &[];
181    let unique_type_id_str = unique_type_id.generate_unique_id_string(cx.tcx);
182
183    let (file_metadata, line_number) = if let Some(def_location) = def_location {
184        (def_location.0, def_location.1)
185    } else {
186        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
187    };
188
189    let metadata = match kind {
190        Stub::Struct | Stub::VTableTy { .. } => {
191            let vtable_holder = match kind {
192                Stub::VTableTy { vtable_holder } => Some(vtable_holder),
193                _ => None,
194            };
195            unsafe {
196                llvm::LLVMDIBuilderCreateStructType(
197                    DIB(cx),
198                    containing_scope,
199                    name.as_ptr(),
200                    name.len(),
201                    file_metadata,
202                    line_number,
203                    size.bits(),
204                    align.bits() as u32,
205                    flags,
206                    None,
207                    no_elements.as_ptr(),
208                    no_elements.len() as c_uint,
209                    0u32, // (Objective-C runtime version; default is 0)
210                    vtable_holder,
211                    unique_type_id_str.as_ptr(),
212                    unique_type_id_str.len(),
213                )
214            }
215        }
216        Stub::Union => unsafe {
217            llvm::LLVMDIBuilderCreateUnionType(
218                DIB(cx),
219                containing_scope,
220                name.as_ptr(),
221                name.len(),
222                file_metadata,
223                line_number,
224                size.bits(),
225                align.bits() as u32,
226                flags,
227                no_elements.as_ptr(),
228                no_elements.len() as c_uint,
229                0u32, // (Objective-C runtime version; default is 0)
230                unique_type_id_str.as_ptr(),
231                unique_type_id_str.len(),
232            )
233        },
234    };
235    StubInfo { metadata, unique_type_id }
236}
237
238struct AdtStackPopGuard<'ll, 'tcx, 'a> {
239    cx: &'a CodegenCx<'ll, 'tcx>,
240}
241
242impl<'ll, 'tcx, 'a> Drop for AdtStackPopGuard<'ll, 'tcx, 'a> {
243    fn drop(&mut self) {
244        debug_context(self.cx).adt_stack.borrow_mut().pop();
245    }
246}
247
248/// This function enables creating debuginfo nodes that can recursively refer to themselves.
249/// It will first insert the given stub into the type map and only then execute the `members`
250/// and `generics` closures passed in. These closures have access to the stub so they can
251/// directly attach fields to them. If the type of a field transitively refers back
252/// to the type currently being built, the stub will already be found in the type map,
253/// which effectively breaks the recursion cycle.
254pub(super) fn build_type_with_children<'ll, 'tcx>(
255    cx: &CodegenCx<'ll, 'tcx>,
256    stub_info: StubInfo<'ll, 'tcx>,
257    members: impl FnOnce(&CodegenCx<'ll, 'tcx>, &'ll DIType) -> SmallVec<&'ll DIType>,
258    generics: impl FnOnce(&CodegenCx<'ll, 'tcx>) -> SmallVec<Option<&'ll DIType>>,
259) -> DINodeCreationResult<'ll> {
260    match (&debug_context(cx).type_map.di_node_for_unique_id(stub_info.unique_type_id),
        &None) {
    (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);
        }
    }
};assert_eq!(debug_context(cx).type_map.di_node_for_unique_id(stub_info.unique_type_id), None);
261
262    let mut _adt_stack_pop_guard = None;
263    if let UniqueTypeId::Ty(ty, ..) = stub_info.unique_type_id
264        && let ty::Adt(adt_def, args) = ty.kind()
265    {
266        let def_id = adt_def.did();
267        // If any child type references the original type definition and the child type has a type
268        // parameter that strictly contains the original parameter, the original type is a recursive
269        // type that can expanding indefinitely. Example,
270        // ```
271        // enum Recursive<T> {
272        //     Recurse(*const Recursive<Wrap<T>>),
273        //     Item(T),
274        // }
275        // ```
276        let is_expanding_recursive = {
277            let stack = debug_context(cx).adt_stack.borrow();
278            stack
279                .iter()
280                .enumerate()
281                .rev()
282                .skip(1)
283                .filter(|(_, (ancestor_def_id, _))| def_id == *ancestor_def_id)
284                .any(|(ancestor_index, (_, ancestor_args))| {
285                    args.iter()
286                        .zip(ancestor_args.iter())
287                        .filter_map(|(arg, ancestor_arg)| arg.as_type().zip(ancestor_arg.as_type()))
288                        .any(|(arg, ancestor_arg)|
289                            // Strictly contains.
290                            (arg != ancestor_arg && arg.contains(ancestor_arg))
291                            // Check all types between current and ancestor use the
292                            // ancestor_arg.
293                            // Otherwise, duplicate wrappers in normal recursive type may be
294                            // regarded as expanding.
295                            // ```
296                            // struct Recursive {
297                            //     a: Box<Box<Recursive>>,
298                            // }
299                            // ```
300                            // It can produce an ADT stack like this,
301                            // - Box<Recursive>
302                            // - Recursive
303                            // - Box<Box<Recursive>>
304                            && stack[ancestor_index + 1..stack.len()].iter().all(
305                                |(_, intermediate_args)|
306                                    intermediate_args
307                                        .iter()
308                                        .filter_map(|arg| arg.as_type())
309                                        .any(|mid_arg| mid_arg.contains(ancestor_arg))
310                            ))
311                })
312        };
313        if is_expanding_recursive {
314            // FIXME: indicate that this is an expanding recursive type in stub metadata?
315            return DINodeCreationResult::new(stub_info.metadata, false);
316        } else {
317            debug_context(cx).adt_stack.borrow_mut().push((def_id, args));
318            _adt_stack_pop_guard = Some(AdtStackPopGuard { cx });
319        }
320    }
321
322    debug_context(cx).type_map.insert(stub_info.unique_type_id, stub_info.metadata);
323
324    let members: SmallVec<_> =
325        members(cx, stub_info.metadata).into_iter().map(|node| Some(node)).collect();
326    let generics = generics(cx);
327
328    if !(members.is_empty() && generics.is_empty()) {
329        unsafe {
330            let members_array = create_DIArray(DIB(cx), &members[..]);
331            let generics_array = create_DIArray(DIB(cx), &generics[..]);
332            llvm::LLVMRustDICompositeTypeReplaceArrays(
333                DIB(cx),
334                stub_info.metadata,
335                Some(members_array),
336                Some(generics_array),
337            );
338        }
339    }
340
341    DINodeCreationResult { di_node: stub_info.metadata, already_stored_in_typemap: true }
342}