Skip to main content

rustc_codegen_llvm/debuginfo/
metadata.rs

1use std::borrow::Cow;
2use std::fmt::{self, Write};
3use std::hash::{Hash, Hasher};
4use std::path::PathBuf;
5use std::sync::Arc;
6use std::{assert_matches, iter, ptr};
7
8use libc::{c_longlong, c_uint};
9use rustc_abi::{Align, Layout, NumScalableVectors, Size};
10use rustc_codegen_ssa::debuginfo::type_names::{VTableNameKind, cpp_like_debuginfo};
11use rustc_codegen_ssa::traits::*;
12use rustc_hir::def::{CtorKind, DefKind};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14use rustc_middle::bug;
15use rustc_middle::ty::layout::{
16    HasTypingEnv, LayoutOf, TyAndLayout, WIDE_PTR_ADDR, WIDE_PTR_EXTRA,
17};
18use rustc_middle::ty::{
19    self, AdtDef, AdtKind, CoroutineArgsExt, ExistentialTraitRef, Instance, Ty, TyCtxt, Visibility,
20};
21use rustc_session::config::{self, DebugInfo, Lto};
22use rustc_span::{DUMMY_SP, FileName, RemapPathScopeComponents, SourceFile, Span, Symbol, hygiene};
23use rustc_symbol_mangling::typeid_for_trait_ref;
24use rustc_target::spec::{Arch, DebuginfoKind};
25use smallvec::smallvec;
26use tracing::{debug, instrument};
27
28pub(crate) use self::type_map::TypeMap;
29use self::type_map::{DINodeCreationResult, Stub, UniqueTypeId};
30use super::CodegenUnitDebugContext;
31use super::namespace::mangled_name_of_instance;
32use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
33use super::utils::{DIB, debug_context, get_namespace_for_item, is_node_local_to_unit};
34use crate::common::{AsCCharPtr, CodegenCx};
35use crate::debuginfo::metadata::type_map::build_type_with_children;
36use crate::debuginfo::utils::{WidePtrKind, create_DIArray, wide_pointer_kind};
37use crate::debuginfo::{DIBuilderExt, dwarf_const};
38use crate::llvm::debuginfo::{
39    DIBasicType, DIBuilder, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock,
40    DIScope, DIType, DebugEmissionKind, DebugNameTableKind,
41};
42use crate::llvm::{self, FromGeneric, Value};
43
44impl PartialEq for llvm::Metadata {
45    fn eq(&self, other: &Self) -> bool {
46        ptr::eq(self, other)
47    }
48}
49
50impl Eq for llvm::Metadata {}
51
52impl Hash for llvm::Metadata {
53    fn hash<H: Hasher>(&self, hasher: &mut H) {
54        (self as *const Self).hash(hasher);
55    }
56}
57
58impl fmt::Debug for llvm::Metadata {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        (self as *const Self).fmt(f)
61    }
62}
63
64pub(super) const UNKNOWN_LINE_NUMBER: c_uint = 0;
65pub(super) const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
66
67const NO_SCOPE_METADATA: Option<&DIScope> = None;
68/// A function that returns an empty list of generic parameter debuginfo nodes.
69const NO_GENERICS: for<'ll> fn(&CodegenCx<'ll, '_>) -> SmallVec<Option<&'ll DIType>> =
70    |_| SmallVec::new();
71
72// SmallVec is used quite a bit in this module, so create a shorthand.
73// The actual number of elements is not so important.
74type SmallVec<T> = smallvec::SmallVec<[T; 16]>;
75
76mod enums;
77mod type_map;
78
79/// Returns from the enclosing function if the type debuginfo node with the given
80/// unique ID can be found in the type map.
81macro_rules! return_if_di_node_created_in_meantime {
82    ($cx: expr, $unique_type_id: expr) => {
83        if let Some(di_node) = debug_context($cx).type_map.di_node_for_unique_id($unique_type_id) {
84            return DINodeCreationResult::new(di_node, true);
85        }
86    };
87}
88
89/// Extract size and alignment from a TyAndLayout.
90#[inline]
91fn size_and_align_of(ty_and_layout: TyAndLayout<'_>) -> (Size, Align) {
92    (ty_and_layout.size, ty_and_layout.align.abi)
93}
94
95/// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
96/// For slices (that is, "arrays" of unknown size) use [build_slice_type_di_node].
97fn build_fixed_size_array_di_node<'ll, 'tcx>(
98    cx: &CodegenCx<'ll, 'tcx>,
99    unique_type_id: UniqueTypeId<'tcx>,
100    array_type: Ty<'tcx>,
101    span: Span,
102) -> DINodeCreationResult<'ll> {
103    let ty::Array(element_type, len) = array_type.kind() else {
104        ::rustc_middle::util::bug::bug_fmt(format_args!("build_fixed_size_array_di_node() called with non-ty::Array type `{0:?}`",
        array_type))bug!("build_fixed_size_array_di_node() called with non-ty::Array type `{:?}`", array_type)
105    };
106
107    let element_type_di_node = spanned_type_di_node(cx, *element_type, span);
108
109    if let Some(di_node) =
        debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
    return DINodeCreationResult::new(di_node, true);
};return_if_di_node_created_in_meantime!(cx, unique_type_id);
110
111    let (size, align) = cx.spanned_size_and_align_of(array_type, span);
112
113    let upper_bound = len
114        .try_to_target_usize(cx.tcx)
115        .expect("expected monomorphic const in codegen") as c_longlong;
116
117    let subrange = unsafe { llvm::LLVMDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound) };
118    let subscripts = &[subrange];
119
120    let di_node = unsafe {
121        llvm::LLVMDIBuilderCreateArrayType(
122            DIB(cx),
123            size.bits(),
124            align.bits() as u32,
125            element_type_di_node,
126            subscripts.as_ptr(),
127            subscripts.len() as c_uint,
128        )
129    };
130
131    DINodeCreationResult::new(di_node, false)
132}
133
134/// Creates debuginfo for built-in pointer-like things:
135///
136///  - ty::Ref
137///  - ty::RawPtr
138///  - ty::Adt in the case it's Box
139///
140/// At some point we might want to remove the special handling of Box
141/// and treat it the same as other smart pointers (like Rc, Arc, ...).
142fn build_pointer_or_reference_di_node<'ll, 'tcx>(
143    cx: &CodegenCx<'ll, 'tcx>,
144    ptr_type: Ty<'tcx>,
145    pointee_type: Ty<'tcx>,
146    unique_type_id: UniqueTypeId<'tcx>,
147) -> DINodeCreationResult<'ll> {
148    // The debuginfo generated by this function is only valid if `ptr_type` is really just
149    // a (wide) pointer. Make sure it is not called for e.g. `Box<T, NonZSTAllocator>`.
150    match (&cx.size_and_align_of(ptr_type),
        &cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type))) {
    (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!(
151        cx.size_and_align_of(ptr_type),
152        cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type))
153    );
154
155    let pointee_type_di_node = type_di_node(cx, pointee_type);
156
157    if let Some(di_node) =
        debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
    return DINodeCreationResult::new(di_node, true);
};return_if_di_node_created_in_meantime!(cx, unique_type_id);
158
159    let data_layout = &cx.tcx.data_layout;
160    let pointer_size = data_layout.pointer_size();
161    let pointer_align = data_layout.pointer_align();
162    let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
163
164    match wide_pointer_kind(cx, pointee_type) {
165        None => {
166            // This is a thin pointer. Create a regular pointer type and give it the correct name.
167            match (&(pointer_size, pointer_align.abi), &cx.size_and_align_of(ptr_type)) {
    (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::Some(format_args!("ptr_type={0}, pointee_type={1}",
                        ptr_type, pointee_type)));
        }
    }
};assert_eq!(
168                (pointer_size, pointer_align.abi),
169                cx.size_and_align_of(ptr_type),
170                "ptr_type={ptr_type}, pointee_type={pointee_type}",
171            );
172
173            let di_node = create_pointer_type(
174                cx,
175                pointee_type_di_node,
176                pointer_size,
177                pointer_align.abi,
178                &ptr_type_debuginfo_name,
179            );
180
181            DINodeCreationResult { di_node, already_stored_in_typemap: false }
182        }
183        Some(wide_pointer_kind) => {
184            type_map::build_type_with_children(
185                cx,
186                type_map::stub(
187                    cx,
188                    Stub::Struct,
189                    unique_type_id,
190                    &ptr_type_debuginfo_name,
191                    None,
192                    cx.size_and_align_of(ptr_type),
193                    NO_SCOPE_METADATA,
194                    DIFlags::FlagZero,
195                ),
196                |cx, owner| {
197                    // FIXME: If this wide pointer is a `Box` then we don't want to use its
198                    //        type layout and instead use the layout of the raw pointer inside
199                    //        of it.
200                    //        The proper way to handle this is to not treat Box as a pointer
201                    //        at all and instead emit regular struct debuginfo for it. We just
202                    //        need to make sure that we don't break existing debuginfo consumers
203                    //        by doing that (at least not without a warning period).
204                    let layout_type = if ptr_type.is_box() {
205                        // The assertion at the start of this function ensures we have a ZST
206                        // allocator. We'll make debuginfo "skip" all ZST allocators, not just the
207                        // default allocator.
208                        Ty::new_mut_ptr(cx.tcx, pointee_type)
209                    } else {
210                        ptr_type
211                    };
212
213                    let layout = cx.layout_of(layout_type);
214                    let addr_field = layout.field(cx, WIDE_PTR_ADDR);
215                    let extra_field = layout.field(cx, WIDE_PTR_EXTRA);
216
217                    let (addr_field_name, extra_field_name) = match wide_pointer_kind {
218                        WidePtrKind::Dyn => ("pointer", "vtable"),
219                        WidePtrKind::Slice => ("data_ptr", "length"),
220                    };
221
222                    match (&WIDE_PTR_ADDR, &0) {
    (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!(WIDE_PTR_ADDR, 0);
223                    match (&WIDE_PTR_EXTRA, &1) {
    (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!(WIDE_PTR_EXTRA, 1);
224
225                    // The data pointer type is a regular, thin pointer, regardless of whether this
226                    // is a slice or a trait object.
227                    let data_ptr_type_di_node = create_pointer_type(
228                        cx,
229                        pointee_type_di_node,
230                        addr_field.size,
231                        addr_field.align.abi,
232                        "",
233                    );
234
235                    {
    let count = 0usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(build_field_di_node(cx, owner, addr_field_name, addr_field,
                layout.fields.offset(WIDE_PTR_ADDR), DIFlags::FlagZero,
                data_ptr_type_di_node, None));
        vec.push(build_field_di_node(cx, owner, extra_field_name, extra_field,
                layout.fields.offset(WIDE_PTR_EXTRA), DIFlags::FlagZero,
                type_di_node(cx, extra_field.ty), None));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [build_field_di_node(cx, owner, addr_field_name, addr_field,
                                layout.fields.offset(WIDE_PTR_ADDR), DIFlags::FlagZero,
                                data_ptr_type_di_node, None),
                            build_field_di_node(cx, owner, extra_field_name,
                                extra_field, layout.fields.offset(WIDE_PTR_EXTRA),
                                DIFlags::FlagZero, type_di_node(cx, extra_field.ty),
                                None)])))
    }
}smallvec![
236                        build_field_di_node(
237                            cx,
238                            owner,
239                            addr_field_name,
240                            addr_field,
241                            layout.fields.offset(WIDE_PTR_ADDR),
242                            DIFlags::FlagZero,
243                            data_ptr_type_di_node,
244                            None,
245                        ),
246                        build_field_di_node(
247                            cx,
248                            owner,
249                            extra_field_name,
250                            extra_field,
251                            layout.fields.offset(WIDE_PTR_EXTRA),
252                            DIFlags::FlagZero,
253                            type_di_node(cx, extra_field.ty),
254                            None,
255                        ),
256                    ]
257                },
258                NO_GENERICS,
259            )
260        }
261    }
262}
263
264fn build_subroutine_type_di_node<'ll, 'tcx>(
265    cx: &CodegenCx<'ll, 'tcx>,
266    unique_type_id: UniqueTypeId<'tcx>,
267) -> DINodeCreationResult<'ll> {
268    // It's possible to create a self-referential type in Rust by using 'impl trait':
269    //
270    // fn foo() -> impl Copy { foo }
271    //
272    // Unfortunately LLVM's API does not allow us to create recursive subroutine types.
273    // In order to work around that restriction we place a marker type in the type map,
274    // before creating the actual type. If the actual type is recursive, it will hit the
275    // marker type. So we end up with a type that looks like
276    //
277    // fn foo() -> <recursive_type>
278    //
279    // Once that is created, we replace the marker in the typemap with the actual type.
280    debug_context(cx)
281        .type_map
282        .unique_id_to_di_node
283        .borrow_mut()
284        .insert(unique_type_id, recursion_marker_type_di_node(cx));
285
286    let fn_ty = unique_type_id.expect_ty();
287    let signature =
288        cx.tcx.normalize_erasing_late_bound_regions(cx.typing_env(), fn_ty.fn_sig(cx.tcx));
289
290    let signature_di_nodes: SmallVec<_> = iter::once(
291        // return type
292        match signature.output().kind() {
293            ty::Tuple(tys) if tys.is_empty() => {
294                // this is a "void" function
295                None
296            }
297            _ => Some(type_di_node(cx, signature.output())),
298        },
299    )
300    .chain(
301        // regular arguments
302        signature.inputs().iter().map(|&argument_type| Some(type_di_node(cx, argument_type))),
303    )
304    .collect();
305
306    debug_context(cx).type_map.unique_id_to_di_node.borrow_mut().remove(&unique_type_id);
307
308    let fn_di_node = create_subroutine_type(cx, &signature_di_nodes[..]);
309
310    // This is actually a function pointer, so wrap it in pointer DI.
311    let name = compute_debuginfo_type_name(cx.tcx, fn_ty, false);
312    let (size, align) = match fn_ty.kind() {
313        ty::FnDef(..) => (Size::ZERO, Align::ONE),
314        ty::FnPtr(..) => {
315            (cx.tcx.data_layout.pointer_size(), cx.tcx.data_layout.pointer_align().abi)
316        }
317        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
318    };
319    let di_node = create_pointer_type(cx, fn_di_node, size, align, &name);
320
321    DINodeCreationResult::new(di_node, false)
322}
323
324pub(super) fn create_subroutine_type<'ll>(
325    cx: &CodegenCx<'ll, '_>,
326    signature: &[Option<&'ll llvm::Metadata>],
327) -> &'ll DICompositeType {
328    unsafe {
329        llvm::LLVMDIBuilderCreateSubroutineType(
330            DIB(cx),
331            None, // ("File" is ignored and has no effect)
332            signature.as_ptr(),
333            signature.len() as c_uint,
334            DIFlags::FlagZero, // (default value)
335        )
336    }
337}
338
339fn create_pointer_type<'ll>(
340    cx: &CodegenCx<'ll, '_>,
341    pointee_ty: &'ll llvm::Metadata,
342    size: Size,
343    align: Align,
344    name: &str,
345) -> &'ll llvm::Metadata {
346    unsafe {
347        llvm::LLVMDIBuilderCreatePointerType(
348            DIB(cx),
349            pointee_ty,
350            size.bits(),
351            align.bits() as u32,
352            0, // Ignore DWARF address space.
353            name.as_ptr(),
354            name.len(),
355        )
356    }
357}
358
359/// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
360/// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
361fn build_dyn_type_di_node<'ll, 'tcx>(
362    cx: &CodegenCx<'ll, 'tcx>,
363    dyn_type: Ty<'tcx>,
364    unique_type_id: UniqueTypeId<'tcx>,
365) -> DINodeCreationResult<'ll> {
366    if let ty::Dynamic(..) = dyn_type.kind() {
367        let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
368        type_map::build_type_with_children(
369            cx,
370            type_map::stub(
371                cx,
372                Stub::Struct,
373                unique_type_id,
374                &type_name,
375                None,
376                cx.size_and_align_of(dyn_type),
377                NO_SCOPE_METADATA,
378                DIFlags::FlagZero,
379            ),
380            |_, _| ::smallvec::SmallVec::new()smallvec![],
381            NO_GENERICS,
382        )
383    } else {
384        ::rustc_middle::util::bug::bug_fmt(format_args!("Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {0:?} instead.",
        dyn_type))bug!(
385            "Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {:?} instead.",
386            dyn_type
387        )
388    }
389}
390
391/// Create debuginfo for `[T]` and `str`. These are unsized.
392///
393/// NOTE: We currently emit just emit the debuginfo for the element type here
394/// (i.e. `T` for slices and `u8` for `str`), so that we end up with
395/// `*const T` for the `data_ptr` field of the corresponding wide-pointer
396/// debuginfo of `&[T]`.
397///
398/// It would be preferable and more accurate if we emitted a DIArray of T
399/// without an upper bound instead. That is, LLVM already supports emitting
400/// debuginfo of arrays of unknown size. But GDB currently seems to end up
401/// in an infinite loop when confronted with such a type.
402///
403/// As a side effect of the current encoding every instance of a type like
404/// `struct Foo { unsized_field: [u8] }` will look like
405/// `struct Foo { unsized_field: u8 }` in debuginfo. If the length of the
406/// slice is zero, then accessing `unsized_field` in the debugger would
407/// result in an out-of-bounds access.
408fn build_slice_type_di_node<'ll, 'tcx>(
409    cx: &CodegenCx<'ll, 'tcx>,
410    slice_type: Ty<'tcx>,
411    unique_type_id: UniqueTypeId<'tcx>,
412) -> DINodeCreationResult<'ll> {
413    let element_type = match slice_type.kind() {
414        ty::Slice(element_type) => *element_type,
415        ty::Str => cx.tcx.types.u8,
416        _ => {
417            ::rustc_middle::util::bug::bug_fmt(format_args!("Only ty::Slice is valid for build_slice_type_di_node(). Found {0:?} instead.",
        slice_type))bug!(
418                "Only ty::Slice is valid for build_slice_type_di_node(). Found {:?} instead.",
419                slice_type
420            )
421        }
422    };
423
424    let element_type_di_node = type_di_node(cx, element_type);
425    if let Some(di_node) =
        debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
    return DINodeCreationResult::new(di_node, true);
};return_if_di_node_created_in_meantime!(cx, unique_type_id);
426    DINodeCreationResult { di_node: element_type_di_node, already_stored_in_typemap: false }
427}
428
429/// Get the debuginfo node for the given type.
430///
431/// This function will look up the debuginfo node in the TypeMap. If it can't find it, it
432/// will create the node by dispatching to the corresponding `build_*_di_node()` function.
433pub(crate) fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
434    spanned_type_di_node(cx, t, DUMMY_SP)
435}
436
437pub(crate) fn spanned_type_di_node<'ll, 'tcx>(
438    cx: &CodegenCx<'ll, 'tcx>,
439    t: Ty<'tcx>,
440    span: Span,
441) -> &'ll DIType {
442    let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t);
443
444    if let Some(existing_di_node) = debug_context(cx).type_map.di_node_for_unique_id(unique_type_id)
445    {
446        return existing_di_node;
447    }
448
449    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:449",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(449u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("type_di_node: {0:?} kind: {1:?}",
                                                    t, t.kind()) as &dyn Value))])
            });
    } else { ; }
};debug!("type_di_node: {:?} kind: {:?}", t, t.kind());
450
451    let DINodeCreationResult { di_node, already_stored_in_typemap } = match *t.kind() {
452        ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
453            build_basic_type_di_node(cx, t)
454        }
455        ty::Tuple(elements) if elements.is_empty() => build_basic_type_di_node(cx, t),
456        ty::Array(..) => build_fixed_size_array_di_node(cx, unique_type_id, t, span),
457        ty::Slice(_) | ty::Str => build_slice_type_di_node(cx, t, unique_type_id),
458        ty::Dynamic(..) => build_dyn_type_di_node(cx, t, unique_type_id),
459        ty::Foreign(..) => build_foreign_type_di_node(cx, t, unique_type_id),
460        ty::RawPtr(pointee_type, _) | ty::Ref(_, pointee_type, _) => {
461            build_pointer_or_reference_di_node(cx, t, pointee_type, unique_type_id)
462        }
463        // Some `Box` are newtyped pointers, make debuginfo aware of that.
464        // Only works if the allocator argument is a 1-ZST and hence irrelevant for layout
465        // (or if there is no allocator argument).
466        ty::Adt(def, args)
467            if def.is_box()
468                && args.get(1).is_none_or(|arg| cx.layout_of(arg.expect_ty()).is_1zst()) =>
469        {
470            build_pointer_or_reference_di_node(cx, t, t.expect_boxed_ty(), unique_type_id)
471        }
472        ty::FnDef(..) | ty::FnPtr(..) => build_subroutine_type_di_node(cx, unique_type_id),
473        ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id),
474        ty::CoroutineClosure(..) => build_closure_env_di_node(cx, unique_type_id),
475        ty::Coroutine(..) => enums::build_coroutine_di_node(cx, unique_type_id),
476        ty::Adt(def, ..) => match def.adt_kind() {
477            AdtKind::Struct => build_struct_type_di_node(cx, unique_type_id, span),
478            AdtKind::Union => build_union_type_di_node(cx, unique_type_id, span),
479            AdtKind::Enum => enums::build_enum_type_di_node(cx, unique_type_id, span),
480        },
481        ty::Tuple(_) => build_tuple_type_di_node(cx, unique_type_id),
482        ty::Pat(base, _) => return type_di_node(cx, base),
483        ty::UnsafeBinder(_) => build_unsafe_binder_type_di_node(cx, t, unique_type_id),
484        ty::Alias(..)
485        | ty::Param(_)
486        | ty::Bound(..)
487        | ty::Infer(_)
488        | ty::Placeholder(_)
489        | ty::CoroutineWitness(..)
490        | ty::Error(_) => {
491            ::rustc_middle::util::bug::bug_fmt(format_args!("debuginfo: unexpected type in type_di_node(): {0:?}",
        t))bug!("debuginfo: unexpected type in type_di_node(): {:?}", t)
492        }
493    };
494
495    {
496        if already_stored_in_typemap {
497            // Make sure that we really do have a `TypeMap` entry for the unique type ID.
498            let di_node_for_uid =
499                match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
500                    Some(di_node) => di_node,
501                    None => {
502                        ::rustc_middle::util::bug::bug_fmt(format_args!("expected type debuginfo node for unique type ID \'{0:?}\' to already be in the `debuginfo::TypeMap` but it was not.",
        unique_type_id));bug!(
503                            "expected type debuginfo node for unique \
504                               type ID '{:?}' to already be in \
505                               the `debuginfo::TypeMap` but it \
506                               was not.",
507                            unique_type_id,
508                        );
509                    }
510                };
511
512            match (&(di_node_for_uid as *const _), &(di_node as *const _)) {
    (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!(di_node_for_uid as *const _, di_node as *const _);
513        } else {
514            debug_context(cx).type_map.insert(unique_type_id, di_node);
515        }
516    }
517
518    di_node
519}
520
521// FIXME(mw): Cache this via a regular UniqueTypeId instead of an extra field in the debug context.
522fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
523    *debug_context(cx).recursion_marker_type.get_or_init(move || {
524        // The choice of type here is pretty arbitrary -
525        // anything reading the debuginfo for a recursive
526        // type is going to see *something* weird - the only
527        // question is what exactly it will see.
528        //
529        // FIXME: the name `<recur_type>` does not fit the naming scheme
530        //        of other types.
531        //
532        // FIXME: it might make sense to use an actual pointer type here
533        //        so that debuggers can show the address.
534        create_basic_type(
535            cx,
536            "<recur_type>",
537            cx.tcx.data_layout.pointer_size(),
538            dwarf_const::DW_ATE_unsigned,
539        )
540    })
541}
542
543fn hex_encode(data: &[u8]) -> String {
544    let mut hex_string = String::with_capacity(data.len() * 2);
545    for byte in data.iter() {
546        (&mut hex_string).write_fmt(format_args!("{0:02x}", byte))write!(&mut hex_string, "{byte:02x}").unwrap();
547    }
548    hex_string
549}
550
551pub(crate) fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
552    let cache_key = Some((source_file.stable_id, source_file.src_hash));
553    return debug_context(cx)
554        .created_files
555        .borrow_mut()
556        .entry(cache_key)
557        .or_insert_with(|| alloc_new_file_metadata(cx, source_file));
558
559    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("alloc_new_file_metadata",
                                    "rustc_codegen_llvm::debuginfo::metadata",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                    ::tracing_core::__macro_support::Option::Some(559u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'ll DIFile = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:564",
                                    "rustc_codegen_llvm::debuginfo::metadata",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                    ::tracing_core::__macro_support::Option::Some(564u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                    ::tracing_core::field::FieldSet::new(&["source_file.name"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&source_file.name)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let (directory, file_name) =
                match &source_file.name {
                    FileName::Real(filename) => {
                        let (working_directory, embeddable_name) =
                            filename.embeddable_name(RemapPathScopeComponents::DEBUGINFO);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:571",
                                                "rustc_codegen_llvm::debuginfo::metadata",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                                ::tracing_core::__macro_support::Option::Some(571u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                                ::tracing_core::field::FieldSet::new(&["working_directory",
                                                                "embeddable_name"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&working_directory)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&embeddable_name)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        if let Ok(rel_path) =
                                embeddable_name.strip_prefix(working_directory) {
                            (working_directory.to_string_lossy(),
                                rel_path.to_string_lossy().into_owned())
                        } else {
                            ("".into(), embeddable_name.to_string_lossy().into_owned())
                        }
                    }
                    other => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:596",
                                                "rustc_codegen_llvm::debuginfo::metadata",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                                ::tracing_core::__macro_support::Option::Some(596u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                                ::tracing_core::field::FieldSet::new(&["other"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&other) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        ("".into(),
                            other.display(RemapPathScopeComponents::DEBUGINFO).to_string())
                    }
                };
            let hash_kind =
                match source_file.src_hash.kind {
                    rustc_span::SourceFileHashAlgorithm::Md5 =>
                        llvm::ChecksumKind::MD5,
                    rustc_span::SourceFileHashAlgorithm::Sha1 =>
                        llvm::ChecksumKind::SHA1,
                    rustc_span::SourceFileHashAlgorithm::Sha256 =>
                        llvm::ChecksumKind::SHA256,
                    rustc_span::SourceFileHashAlgorithm::Blake3 =>
                        llvm::ChecksumKind::None,
                };
            let hash_value = hex_encode(source_file.src_hash.hash_bytes());
            let source =
                cx.sess().opts.unstable_opts.embed_source.then_some(()).and(source_file.src.as_ref());
            create_file(DIB(cx), &file_name, &directory, &hash_value,
                hash_kind, source)
        }
    }
}#[instrument(skip(cx, source_file), level = "debug")]
560    fn alloc_new_file_metadata<'ll>(
561        cx: &CodegenCx<'ll, '_>,
562        source_file: &SourceFile,
563    ) -> &'ll DIFile {
564        debug!(?source_file.name);
565
566        let (directory, file_name) = match &source_file.name {
567            FileName::Real(filename) => {
568                let (working_directory, embeddable_name) =
569                    filename.embeddable_name(RemapPathScopeComponents::DEBUGINFO);
570
571                debug!(?working_directory, ?embeddable_name);
572
573                if let Ok(rel_path) = embeddable_name.strip_prefix(working_directory) {
574                    // If the compiler's working directory (which also is the DW_AT_comp_dir of
575                    // the compilation unit) is a prefix of the path we are about to emit, then
576                    // only emit the part relative to the working directory. Because of path
577                    // remapping we sometimes see strange things here: `abs_path` might
578                    // actually look like a relative path (e.g.
579                    // `<crate-name-and-version>/src/lib.rs`), so if we emit it without taking
580                    // the working directory into account, downstream tooling will interpret it
581                    // as `<working-directory>/<crate-name-and-version>/src/lib.rs`, which
582                    // makes no sense. Usually in such cases the working directory will also be
583                    // remapped to `<crate-name-and-version>` or some other prefix of the path
584                    // we are remapping, so we end up with
585                    // `<crate-name-and-version>/<crate-name-and-version>/src/lib.rs`.
586                    //
587                    // By moving the working directory portion into the `directory` part of the
588                    // DIFile, we allow LLVM to emit just the relative path for DWARF, while
589                    // still emitting the correct absolute path for CodeView.
590                    (working_directory.to_string_lossy(), rel_path.to_string_lossy().into_owned())
591                } else {
592                    ("".into(), embeddable_name.to_string_lossy().into_owned())
593                }
594            }
595            other => {
596                debug!(?other);
597                ("".into(), other.display(RemapPathScopeComponents::DEBUGINFO).to_string())
598            }
599        };
600
601        let hash_kind = match source_file.src_hash.kind {
602            rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
603            rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
604            rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
605            rustc_span::SourceFileHashAlgorithm::Blake3 => llvm::ChecksumKind::None,
606        };
607        let hash_value = hex_encode(source_file.src_hash.hash_bytes());
608
609        let source =
610            cx.sess().opts.unstable_opts.embed_source.then_some(()).and(source_file.src.as_ref());
611
612        create_file(DIB(cx), &file_name, &directory, &hash_value, hash_kind, source)
613    }
614}
615
616fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
617    debug_context(cx).created_files.borrow_mut().entry(None).or_insert_with(|| {
618        create_file(DIB(cx), "<unknown>", "", "", llvm::ChecksumKind::None, None)
619    })
620}
621
622fn create_file<'ll>(
623    builder: &DIBuilder<'ll>,
624    file_name: &str,
625    directory: &str,
626    hash_value: &str,
627    hash_kind: llvm::ChecksumKind,
628    source: Option<&Arc<String>>,
629) -> &'ll DIFile {
630    unsafe {
631        llvm::LLVMRustDIBuilderCreateFile(
632            builder,
633            file_name.as_c_char_ptr(),
634            file_name.len(),
635            directory.as_c_char_ptr(),
636            directory.len(),
637            hash_kind,
638            hash_value.as_c_char_ptr(),
639            hash_value.len(),
640            source.map_or(ptr::null(), |x| x.as_c_char_ptr()),
641            source.map_or(0, |x| x.len()),
642        )
643    }
644}
645
646trait MsvcBasicName {
647    fn msvc_basic_name(self) -> &'static str;
648}
649
650impl MsvcBasicName for ty::IntTy {
651    fn msvc_basic_name(self) -> &'static str {
652        match self {
653            ty::IntTy::Isize => "ptrdiff_t",
654            ty::IntTy::I8 => "__int8",
655            ty::IntTy::I16 => "__int16",
656            ty::IntTy::I32 => "__int32",
657            ty::IntTy::I64 => "__int64",
658            ty::IntTy::I128 => "__int128",
659        }
660    }
661}
662
663impl MsvcBasicName for ty::UintTy {
664    fn msvc_basic_name(self) -> &'static str {
665        match self {
666            ty::UintTy::Usize => "size_t",
667            ty::UintTy::U8 => "unsigned __int8",
668            ty::UintTy::U16 => "unsigned __int16",
669            ty::UintTy::U32 => "unsigned __int32",
670            ty::UintTy::U64 => "unsigned __int64",
671            ty::UintTy::U128 => "unsigned __int128",
672        }
673    }
674}
675
676impl MsvcBasicName for ty::FloatTy {
677    fn msvc_basic_name(self) -> &'static str {
678        // FIXME(f128): `f128` has no MSVC representation. We could improve the debuginfo.
679        // See: <https://github.com/rust-lang/rust/issues/121837>
680        match self {
681            ty::FloatTy::F16 => {
682                ::rustc_middle::util::bug::bug_fmt(format_args!("`f16` should have been handled in `build_basic_type_di_node`"))bug!("`f16` should have been handled in `build_basic_type_di_node`")
683            }
684            ty::FloatTy::F32 => "float",
685            ty::FloatTy::F64 => "double",
686            ty::FloatTy::F128 => "fp128",
687        }
688    }
689}
690
691fn build_cpp_f16_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> DINodeCreationResult<'ll> {
692    // MSVC has no native support for `f16`. Instead, emit `struct f16 { bits: u16 }` to allow the
693    // `f16`'s value to be displayed using a Natvis visualiser in `intrinsic.natvis`.
694    let float_ty = cx.tcx.types.f16;
695    let bits_ty = cx.tcx.types.u16;
696    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
697        match float_ty.kind() {
698            ty::Adt(def, _) => Some(file_metadata_from_def_id(cx, Some(def.did()))),
699            _ => None,
700        }
701    } else {
702        None
703    };
704    type_map::build_type_with_children(
705        cx,
706        type_map::stub(
707            cx,
708            Stub::Struct,
709            UniqueTypeId::for_ty(cx.tcx, float_ty),
710            "f16",
711            def_location,
712            cx.size_and_align_of(float_ty),
713            NO_SCOPE_METADATA,
714            DIFlags::FlagZero,
715        ),
716        // Fields:
717        |cx, float_di_node| {
718            let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
719                match bits_ty.kind() {
720                    ty::Adt(def, _) => Some(def.did()),
721                    _ => None,
722                }
723            } else {
724                None
725            };
726            {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(build_field_di_node(cx, float_di_node, "bits",
                cx.layout_of(bits_ty), Size::ZERO, DIFlags::FlagZero,
                type_di_node(cx, bits_ty), def_id));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [build_field_di_node(cx, float_di_node, "bits",
                                cx.layout_of(bits_ty), Size::ZERO, DIFlags::FlagZero,
                                type_di_node(cx, bits_ty), def_id)])))
    }
}smallvec![build_field_di_node(
727                cx,
728                float_di_node,
729                "bits",
730                cx.layout_of(bits_ty),
731                Size::ZERO,
732                DIFlags::FlagZero,
733                type_di_node(cx, bits_ty),
734                def_id,
735            )]
736        },
737        NO_GENERICS,
738    )
739}
740
741fn build_basic_type_di_node<'ll, 'tcx>(
742    cx: &CodegenCx<'ll, 'tcx>,
743    t: Ty<'tcx>,
744) -> DINodeCreationResult<'ll> {
745    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:745",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(745u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("build_basic_type_di_node: {0:?}",
                                                    t) as &dyn Value))])
            });
    } else { ; }
};debug!("build_basic_type_di_node: {:?}", t);
746
747    // When targeting MSVC, emit MSVC style type names for compatibility with
748    // .natvis visualizers (and perhaps other existing native debuggers?)
749    let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
750
751    use dwarf_const::{DW_ATE_UTF, DW_ATE_boolean, DW_ATE_float, DW_ATE_signed, DW_ATE_unsigned};
752
753    let (name, encoding) = match t.kind() {
754        ty::Never => ("!", DW_ATE_unsigned),
755        ty::Tuple(elements) if elements.is_empty() => {
756            if cpp_like_debuginfo {
757                return build_tuple_type_di_node(cx, UniqueTypeId::for_ty(cx.tcx, t));
758            } else {
759                ("()", DW_ATE_unsigned)
760            }
761        }
762        ty::Bool => ("bool", DW_ATE_boolean),
763        ty::Char => ("char", DW_ATE_UTF),
764        ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
765        ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
766        ty::Float(ty::FloatTy::F16) if cpp_like_debuginfo => {
767            return build_cpp_f16_di_node(cx);
768        }
769        ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
770        ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
771        ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
772        ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
773        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("debuginfo::build_basic_type_di_node - `t` is invalid type"))bug!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
774    };
775
776    let ty_di_node = create_basic_type(cx, name, cx.size_of(t), encoding);
777
778    if !cpp_like_debuginfo {
779        return DINodeCreationResult::new(ty_di_node, false);
780    }
781
782    let typedef_name = match t.kind() {
783        ty::Int(int_ty) => int_ty.name_str(),
784        ty::Uint(uint_ty) => uint_ty.name_str(),
785        ty::Float(float_ty) => float_ty.name_str(),
786        _ => return DINodeCreationResult::new(ty_di_node, false),
787    };
788
789    let typedef_di_node = unsafe {
790        llvm::LLVMDIBuilderCreateTypedef(
791            DIB(cx),
792            ty_di_node,
793            typedef_name.as_ptr(),
794            typedef_name.len(),
795            unknown_file_metadata(cx),
796            0,    // (no line number)
797            None, // (no scope)
798            0u32, // (no alignment specified)
799        )
800    };
801
802    DINodeCreationResult::new(typedef_di_node, false)
803}
804
805fn create_basic_type<'ll, 'tcx>(
806    cx: &CodegenCx<'ll, 'tcx>,
807    name: &str,
808    size: Size,
809    encoding: u32,
810) -> &'ll DIBasicType {
811    unsafe {
812        llvm::LLVMDIBuilderCreateBasicType(
813            DIB(cx),
814            name.as_ptr(),
815            name.len(),
816            size.bits(),
817            encoding,
818            DIFlags::FlagZero,
819        )
820    }
821}
822
823fn build_foreign_type_di_node<'ll, 'tcx>(
824    cx: &CodegenCx<'ll, 'tcx>,
825    t: Ty<'tcx>,
826    unique_type_id: UniqueTypeId<'tcx>,
827) -> DINodeCreationResult<'ll> {
828    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:828",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(828u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("build_foreign_type_di_node: {0:?}",
                                                    t) as &dyn Value))])
            });
    } else { ; }
};debug!("build_foreign_type_di_node: {:?}", t);
829
830    let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else {
831        ::rustc_middle::util::bug::bug_fmt(format_args!("build_foreign_type_di_node() called with unexpected type: {0:?}",
        unique_type_id.expect_ty()));bug!(
832            "build_foreign_type_di_node() called with unexpected type: {:?}",
833            unique_type_id.expect_ty()
834        );
835    };
836
837    build_type_with_children(
838        cx,
839        type_map::stub(
840            cx,
841            Stub::Struct,
842            unique_type_id,
843            &compute_debuginfo_type_name(cx.tcx, t, false),
844            None,
845            cx.size_and_align_of(t),
846            Some(get_namespace_for_item(cx, def_id)),
847            DIFlags::FlagZero,
848        ),
849        |_, _| ::smallvec::SmallVec::new()smallvec![],
850        NO_GENERICS,
851    )
852}
853
854pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
855    tcx: TyCtxt<'tcx>,
856    codegen_unit_name: &str,
857    debug_context: &CodegenUnitDebugContext<'ll, 'tcx>,
858) -> &'ll DIDescriptor {
859    let mut name_in_debuginfo = tcx
860        .sess
861        .local_crate_source_file()
862        .map(|src| src.path(RemapPathScopeComponents::DEBUGINFO).to_path_buf())
863        .unwrap_or_else(|| PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()));
864
865    // To avoid breaking split DWARF, we need to ensure that each codegen unit
866    // has a unique `DW_AT_name`. This is because there's a remote chance that
867    // different codegen units for the same module will have entirely
868    // identical DWARF entries for the purpose of the DWO ID, which would
869    // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
870    // specification. LLVM uses the algorithm specified in section 7.32 "Type
871    // Signature Computation" to compute the DWO ID, which does not include
872    // any fields that would distinguish compilation units. So we must embed
873    // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
874    //
875    // Additionally, the OSX linker has an idiosyncrasy where it will ignore
876    // some debuginfo if multiple object files with the same `DW_AT_name` are
877    // linked together.
878    //
879    // As a workaround for these two issues, we generate unique names for each
880    // object file. Those do not correspond to an actual source file but that
881    // is harmless.
882    name_in_debuginfo.push("@");
883    name_in_debuginfo.push(codegen_unit_name);
884
885    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:885",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(885u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("build_compile_unit_di_node: {0:?}",
                                                    name_in_debuginfo) as &dyn Value))])
            });
    } else { ; }
};debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
886    let rustc_producer = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc version {0}",
                tcx.sess.cfg_version))
    })format!("rustc version {}", tcx.sess.cfg_version);
887    // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
888    let producer = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("clang LLVM ({0})", rustc_producer))
    })format!("clang LLVM ({rustc_producer})");
889
890    let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
891    let work_dir = tcx.sess.psess.source_map().working_dir();
892    let output_filenames = tcx.output_filenames(());
893    let split_name = if tcx.sess.target_can_use_split_dwarf()
894        && let Some(f) = output_filenames.split_dwarf_path(
895            tcx.sess.split_debuginfo(),
896            tcx.sess.opts.unstable_opts.split_dwarf_kind,
897            codegen_unit_name,
898            tcx.sess.invocation_temp.as_deref(),
899        ) {
900        // We get a path relative to the working directory from split_dwarf_path
901        Some(tcx.sess.source_map().path_mapping().to_real_filename(work_dir, f))
902    } else {
903        None
904    };
905    let split_name = split_name
906        .as_ref()
907        .map(|f| f.path(RemapPathScopeComponents::DEBUGINFO).to_string_lossy())
908        .unwrap_or_default();
909    let work_dir = work_dir.path(RemapPathScopeComponents::DEBUGINFO).to_string_lossy();
910    let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
911
912    let dwarf_version = tcx.sess.dwarf_version();
913    let is_dwarf_kind =
914        #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.target.debuginfo_kind
    {
    DebuginfoKind::Dwarf | DebuginfoKind::DwarfDsym => true,
    _ => false,
}matches!(tcx.sess.target.debuginfo_kind, DebuginfoKind::Dwarf | DebuginfoKind::DwarfDsym);
915    // Don't emit `.debug_pubnames` and `.debug_pubtypes` on DWARFv4 or lower.
916    let debug_name_table_kind = if is_dwarf_kind && dwarf_version <= 4 {
917        DebugNameTableKind::None
918    } else {
919        DebugNameTableKind::Default
920    };
921
922    unsafe {
923        let compile_unit_file = create_file(
924            debug_context.builder.as_ref(),
925            &name_in_debuginfo,
926            &work_dir,
927            "",
928            llvm::ChecksumKind::None,
929            None,
930        );
931
932        let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
933            debug_context.builder.as_ref(),
934            dwarf_const::DW_LANG_Rust,
935            compile_unit_file,
936            producer.as_c_char_ptr(),
937            producer.len(),
938            tcx.sess.opts.optimize != config::OptLevel::No,
939            c"".as_ptr(),
940            0,
941            // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
942            // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
943            // output(s).
944            split_name.as_c_char_ptr(),
945            split_name.len(),
946            kind,
947            0,
948            tcx.sess.opts.unstable_opts.split_dwarf_inlining,
949            debug_name_table_kind,
950        );
951
952        return unit_metadata;
953    };
954}
955
956/// Creates a `DW_TAG_member` entry inside the DIE represented by the given `type_di_node`.
957fn build_field_di_node<'ll, 'tcx>(
958    cx: &CodegenCx<'ll, 'tcx>,
959    owner: &'ll DIScope,
960    name: &str,
961    layout: TyAndLayout<'tcx>,
962    offset: Size,
963    flags: DIFlags,
964    type_di_node: &'ll DIType,
965    def_id: Option<DefId>,
966) -> &'ll DIType {
967    let (file_metadata, line_number) = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers
968    {
969        file_metadata_from_def_id(cx, def_id)
970    } else {
971        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
972    };
973    create_member_type(
974        cx,
975        owner,
976        name,
977        file_metadata,
978        line_number,
979        layout,
980        offset,
981        flags,
982        type_di_node,
983    )
984}
985
986fn create_member_type<'ll, 'tcx>(
987    cx: &CodegenCx<'ll, 'tcx>,
988    owner: &'ll DIScope,
989    name: &str,
990    file_metadata: &'ll DIType,
991    line_number: u32,
992    layout: TyAndLayout<'tcx>,
993    offset: Size,
994    flags: DIFlags,
995    type_di_node: &'ll DIType,
996) -> &'ll DIType {
997    unsafe {
998        llvm::LLVMDIBuilderCreateMemberType(
999            DIB(cx),
1000            owner,
1001            name.as_ptr(),
1002            name.len(),
1003            file_metadata,
1004            line_number,
1005            layout.size.bits(),
1006            layout.align.bits() as u32,
1007            offset.bits(),
1008            flags,
1009            type_di_node,
1010        )
1011    }
1012}
1013
1014/// Returns the `DIFlags` corresponding to the visibility of the item identified by `did`.
1015///
1016/// `DIFlags::Flag{Public,Protected,Private}` correspond to `DW_AT_accessibility`
1017/// (public/protected/private) aren't exactly right for Rust, but neither is `DW_AT_visibility`
1018/// (local/exported/qualified), and there's no way to set `DW_AT_visibility` in LLVM's API.
1019fn visibility_di_flags<'ll, 'tcx>(
1020    cx: &CodegenCx<'ll, 'tcx>,
1021    did: DefId,
1022    type_did: DefId,
1023) -> DIFlags {
1024    let parent_did = cx.tcx.parent(type_did);
1025    let visibility = cx.tcx.visibility(did);
1026    match visibility {
1027        Visibility::Public => DIFlags::FlagPublic,
1028        // Private fields have a restricted visibility of the module containing the type.
1029        Visibility::Restricted(did) if did == parent_did => DIFlags::FlagPrivate,
1030        // `pub(crate)`/`pub(super)` visibilities are any other restricted visibility.
1031        Visibility::Restricted(..) => DIFlags::FlagProtected,
1032    }
1033}
1034
1035/// Creates the debuginfo node for a Rust struct type. Maybe be a regular struct or a tuple-struct.
1036fn build_struct_type_di_node<'ll, 'tcx>(
1037    cx: &CodegenCx<'ll, 'tcx>,
1038    unique_type_id: UniqueTypeId<'tcx>,
1039    span: Span,
1040) -> DINodeCreationResult<'ll> {
1041    let struct_type = unique_type_id.expect_ty();
1042
1043    let ty::Adt(adt_def, _) = struct_type.kind() else {
1044        ::rustc_middle::util::bug::bug_fmt(format_args!("build_struct_type_di_node() called with non-struct-type: {0:?}",
        struct_type));bug!("build_struct_type_di_node() called with non-struct-type: {:?}", struct_type);
1045    };
1046    if !adt_def.is_struct() {
    ::core::panicking::panic("assertion failed: adt_def.is_struct()")
};assert!(adt_def.is_struct());
1047    let containing_scope = get_namespace_for_item(cx, adt_def.did());
1048    let struct_type_and_layout = cx.spanned_layout_of(struct_type, span);
1049    let variant_def = adt_def.non_enum_variant();
1050    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1051        Some(file_metadata_from_def_id(cx, Some(adt_def.did())))
1052    } else {
1053        None
1054    };
1055    let name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1056
1057    if struct_type.is_scalable_vector() {
1058        let parts = struct_type.scalable_vector_parts(cx.tcx).unwrap();
1059        return build_scalable_vector_di_node(
1060            cx,
1061            unique_type_id,
1062            name,
1063            *adt_def,
1064            parts,
1065            struct_type_and_layout.layout,
1066            def_location,
1067            containing_scope,
1068        );
1069    }
1070
1071    type_map::build_type_with_children(
1072        cx,
1073        type_map::stub(
1074            cx,
1075            Stub::Struct,
1076            unique_type_id,
1077            &name,
1078            def_location,
1079            size_and_align_of(struct_type_and_layout),
1080            Some(containing_scope),
1081            visibility_di_flags(cx, adt_def.did(), adt_def.did()),
1082        ),
1083        // Fields:
1084        |cx, owner| {
1085            variant_def
1086                .fields
1087                .iter()
1088                .enumerate()
1089                .map(|(i, f)| {
1090                    let field_name = if variant_def.ctor_kind() == Some(CtorKind::Fn) {
1091                        // This is a tuple struct
1092                        tuple_field_name(i)
1093                    } else {
1094                        // This is struct with named fields
1095                        Cow::Borrowed(f.name.as_str())
1096                    };
1097                    let field_layout = struct_type_and_layout.field(cx, i);
1098                    let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1099                        Some(f.did)
1100                    } else {
1101                        None
1102                    };
1103                    build_field_di_node(
1104                        cx,
1105                        owner,
1106                        &field_name[..],
1107                        field_layout,
1108                        struct_type_and_layout.fields.offset(i),
1109                        visibility_di_flags(cx, f.did, adt_def.did()),
1110                        type_di_node(cx, field_layout.ty),
1111                        def_id,
1112                    )
1113                })
1114                .collect()
1115        },
1116        |cx| build_generic_type_param_di_nodes(cx, struct_type),
1117    )
1118}
1119
1120/// Generate debuginfo for a `#[rustc_scalable_vector]` type.
1121///
1122/// Debuginfo for a scalable vector uses a derived type based on a composite type. The composite
1123/// type has the  `DIFlagVector` flag set and is based on the element type of the scalable vector.
1124/// The composite type has a subrange from 0 to an expression that calculates the number of
1125/// elements in the vector.
1126///
1127/// ```text,ignore
1128/// !1 = !DIDerivedType(tag: DW_TAG_typedef, name: "svint16_t", ..., baseType: !2, ...)
1129/// !2 = !DICompositeType(tag: DW_TAG_array_type, baseType: !3, ..., flags: DIFlagVector, elements: !4)
1130/// !3 = !DIBasicType(name: "i16", size: 16, encoding: DW_ATE_signed)
1131/// !4 = !{!5}
1132/// !5 = !DISubrange(lowerBound: 0, upperBound: !DIExpression(DW_OP_constu, 4, DW_OP_bregx, 46, 0, DW_OP_mul, DW_OP_constu, 1, DW_OP_minus))
1133/// ```
1134///
1135/// See the `CodegenType::CreateType(const BuiltinType *BT)` implementation in Clang for how this
1136/// is generated for C and C++.
1137fn build_scalable_vector_di_node<'ll, 'tcx>(
1138    cx: &CodegenCx<'ll, 'tcx>,
1139    unique_type_id: UniqueTypeId<'tcx>,
1140    name: String,
1141    adt_def: AdtDef<'tcx>,
1142    (element_count, element_ty, number_of_vectors): (u16, Ty<'tcx>, NumScalableVectors),
1143    layout: Layout<'tcx>,
1144    def_location: Option<DefinitionLocation<'ll>>,
1145    containing_scope: &'ll DIScope,
1146) -> DINodeCreationResult<'ll> {
1147    use dwarf_const::{DW_OP_bregx, DW_OP_constu, DW_OP_minus, DW_OP_mul};
1148    if !adt_def.repr().scalable() {
    ::core::panicking::panic("assertion failed: adt_def.repr().scalable()")
};assert!(adt_def.repr().scalable());
1149    // This logic is specific to AArch64 for the moment, but can be extended for other architectures
1150    // later.
1151    match cx.tcx.sess.target.arch {
    Arch::AArch64 => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val, "Arch::AArch64",
            ::core::option::Option::None);
    }
};assert_matches!(cx.tcx.sess.target.arch, Arch::AArch64);
1152
1153    let (file_metadata, line_number) = if let Some(def_location) = def_location {
1154        (def_location.0, def_location.1)
1155    } else {
1156        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1157    };
1158
1159    let (bitstride, element_di_node) = if element_ty.is_bool() {
1160        (Some(llvm::LLVMValueAsMetadata(cx.const_i64(1))), type_di_node(cx, cx.tcx.types.u8))
1161    } else {
1162        (None, type_di_node(cx, element_ty))
1163    };
1164
1165    let number_of_elements: u64 = (element_count as u64) * (number_of_vectors.0 as u64);
1166    let number_of_elements_per_vg = number_of_elements / 2;
1167    let mut expr = smallvec::SmallVec::<[u64; 9]>::new();
1168    // `($number_of_elements_per_vector_granule * (value_of_register(AArch64::VG) + 0)) - 1`
1169    expr.push(DW_OP_constu); // Push a constant onto the stack
1170    expr.push(number_of_elements_per_vg);
1171    expr.push(DW_OP_bregx); // Push the value of a register + offset on to the stack
1172    expr.push(/* AArch64::VG */ 46u64);
1173    expr.push(0u64);
1174    expr.push(DW_OP_mul); // Multiply top two values on stack
1175    expr.push(DW_OP_constu); // Push a constant onto the stack
1176    expr.push(1u64);
1177    expr.push(DW_OP_minus); // Subtract top two values on stack
1178
1179    let di_builder = DIB(cx);
1180    let metadata = unsafe {
1181        let upper = llvm::LLVMDIBuilderCreateExpression(di_builder, expr.as_ptr(), expr.len());
1182        let subrange = llvm::LLVMRustDIGetOrCreateSubrange(
1183            di_builder,
1184            /* CountNode */ None,
1185            llvm::LLVMValueAsMetadata(cx.const_i64(0)),
1186            upper,
1187            /* Stride */ None,
1188        );
1189        let subscripts = create_DIArray(di_builder, &[Some(subrange)]);
1190        let vector_ty = llvm::LLVMRustDICreateVectorType(
1191            di_builder,
1192            /* Size */ 0,
1193            layout.align.bits() as u32,
1194            element_di_node,
1195            subscripts,
1196            bitstride,
1197        );
1198        llvm::LLVMDIBuilderCreateTypedef(
1199            di_builder,
1200            vector_ty,
1201            name.as_ptr(),
1202            name.len(),
1203            file_metadata,
1204            line_number,
1205            Some(containing_scope),
1206            layout.align.bits() as u32,
1207        )
1208    };
1209
1210    debug_context(cx).type_map.insert(unique_type_id, metadata);
1211    DINodeCreationResult { di_node: metadata, already_stored_in_typemap: true }
1212}
1213
1214//=-----------------------------------------------------------------------------
1215// Tuples
1216//=-----------------------------------------------------------------------------
1217
1218/// Builds the DW_TAG_member debuginfo nodes for the upvars of a closure or coroutine.
1219/// For a coroutine, this will handle upvars shared by all states.
1220fn build_upvar_field_di_nodes<'ll, 'tcx>(
1221    cx: &CodegenCx<'ll, 'tcx>,
1222    closure_or_coroutine_ty: Ty<'tcx>,
1223    closure_or_coroutine_di_node: &'ll DIType,
1224) -> SmallVec<&'ll DIType> {
1225    let (&def_id, up_var_tys) = match closure_or_coroutine_ty.kind() {
1226        ty::Coroutine(def_id, args) => (def_id, args.as_coroutine().prefix_tys()),
1227        ty::Closure(def_id, args) => (def_id, args.as_closure().upvar_tys()),
1228        ty::CoroutineClosure(def_id, args) => (def_id, args.as_coroutine_closure().upvar_tys()),
1229        _ => {
1230            ::rustc_middle::util::bug::bug_fmt(format_args!("build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {0:?}",
        closure_or_coroutine_ty))bug!(
1231                "build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {:?}",
1232                closure_or_coroutine_ty
1233            )
1234        }
1235    };
1236
1237    if !up_var_tys.iter().all(|t|
                t == cx.tcx.normalize_erasing_regions(cx.typing_env(), t)) {
    ::core::panicking::panic("assertion failed: up_var_tys.iter().all(|t|\n        t == cx.tcx.normalize_erasing_regions(cx.typing_env(), t))")
};assert!(up_var_tys.iter().all(|t| t == cx.tcx.normalize_erasing_regions(cx.typing_env(), t)));
1238
1239    let capture_names = cx.tcx.closure_saved_names_of_captured_variables(def_id);
1240    let layout = cx.layout_of(closure_or_coroutine_ty);
1241
1242    up_var_tys
1243        .into_iter()
1244        .zip(capture_names.iter())
1245        .enumerate()
1246        .map(|(index, (up_var_ty, capture_name))| {
1247            build_field_di_node(
1248                cx,
1249                closure_or_coroutine_di_node,
1250                capture_name.as_str(),
1251                cx.layout_of(up_var_ty),
1252                layout.fields.offset(index),
1253                DIFlags::FlagZero,
1254                type_di_node(cx, up_var_ty),
1255                None,
1256            )
1257        })
1258        .collect()
1259}
1260
1261/// Builds the DW_TAG_structure_type debuginfo node for a Rust tuple type.
1262fn build_tuple_type_di_node<'ll, 'tcx>(
1263    cx: &CodegenCx<'ll, 'tcx>,
1264    unique_type_id: UniqueTypeId<'tcx>,
1265) -> DINodeCreationResult<'ll> {
1266    let tuple_type = unique_type_id.expect_ty();
1267    let &ty::Tuple(component_types) = tuple_type.kind() else {
1268        ::rustc_middle::util::bug::bug_fmt(format_args!("build_tuple_type_di_node() called with non-tuple-type: {0:?}",
        tuple_type))bug!("build_tuple_type_di_node() called with non-tuple-type: {:?}", tuple_type)
1269    };
1270
1271    let tuple_type_and_layout = cx.layout_of(tuple_type);
1272    let type_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1273
1274    type_map::build_type_with_children(
1275        cx,
1276        type_map::stub(
1277            cx,
1278            Stub::Struct,
1279            unique_type_id,
1280            &type_name,
1281            None,
1282            size_and_align_of(tuple_type_and_layout),
1283            NO_SCOPE_METADATA,
1284            DIFlags::FlagZero,
1285        ),
1286        // Fields:
1287        |cx, tuple_di_node| {
1288            component_types
1289                .into_iter()
1290                .enumerate()
1291                .map(|(index, component_type)| {
1292                    build_field_di_node(
1293                        cx,
1294                        tuple_di_node,
1295                        &tuple_field_name(index),
1296                        cx.layout_of(component_type),
1297                        tuple_type_and_layout.fields.offset(index),
1298                        DIFlags::FlagZero,
1299                        type_di_node(cx, component_type),
1300                        None,
1301                    )
1302                })
1303                .collect()
1304        },
1305        NO_GENERICS,
1306    )
1307}
1308
1309/// Builds the debuginfo node for a closure environment.
1310fn build_closure_env_di_node<'ll, 'tcx>(
1311    cx: &CodegenCx<'ll, 'tcx>,
1312    unique_type_id: UniqueTypeId<'tcx>,
1313) -> DINodeCreationResult<'ll> {
1314    let closure_env_type = unique_type_id.expect_ty();
1315    let &(ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _)) = closure_env_type.kind()
1316    else {
1317        ::rustc_middle::util::bug::bug_fmt(format_args!("build_closure_env_di_node() called with non-closure-type: {0:?}",
        closure_env_type))bug!("build_closure_env_di_node() called with non-closure-type: {:?}", closure_env_type)
1318    };
1319    let containing_scope = get_namespace_for_item(cx, def_id);
1320    let type_name = compute_debuginfo_type_name(cx.tcx, closure_env_type, false);
1321
1322    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1323        Some(file_metadata_from_def_id(cx, Some(def_id)))
1324    } else {
1325        None
1326    };
1327
1328    type_map::build_type_with_children(
1329        cx,
1330        type_map::stub(
1331            cx,
1332            Stub::Struct,
1333            unique_type_id,
1334            &type_name,
1335            def_location,
1336            cx.size_and_align_of(closure_env_type),
1337            Some(containing_scope),
1338            DIFlags::FlagZero,
1339        ),
1340        // Fields:
1341        |cx, owner| build_upvar_field_di_nodes(cx, closure_env_type, owner),
1342        NO_GENERICS,
1343    )
1344}
1345
1346/// Build the debuginfo node for a Rust `union` type.
1347fn build_union_type_di_node<'ll, 'tcx>(
1348    cx: &CodegenCx<'ll, 'tcx>,
1349    unique_type_id: UniqueTypeId<'tcx>,
1350    span: Span,
1351) -> DINodeCreationResult<'ll> {
1352    let union_type = unique_type_id.expect_ty();
1353    let (union_def_id, variant_def) = match union_type.kind() {
1354        ty::Adt(def, _) => (def.did(), def.non_enum_variant()),
1355        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("build_union_type_di_node on a non-ADT"))bug!("build_union_type_di_node on a non-ADT"),
1356    };
1357    let containing_scope = get_namespace_for_item(cx, union_def_id);
1358    let union_ty_and_layout = cx.spanned_layout_of(union_type, span);
1359    let type_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1360    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1361        Some(file_metadata_from_def_id(cx, Some(union_def_id)))
1362    } else {
1363        None
1364    };
1365
1366    type_map::build_type_with_children(
1367        cx,
1368        type_map::stub(
1369            cx,
1370            Stub::Union,
1371            unique_type_id,
1372            &type_name,
1373            def_location,
1374            size_and_align_of(union_ty_and_layout),
1375            Some(containing_scope),
1376            DIFlags::FlagZero,
1377        ),
1378        // Fields:
1379        |cx, owner| {
1380            variant_def
1381                .fields
1382                .iter()
1383                .enumerate()
1384                .map(|(i, f)| {
1385                    let field_layout = union_ty_and_layout.field(cx, i);
1386                    let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1387                        Some(f.did)
1388                    } else {
1389                        None
1390                    };
1391                    build_field_di_node(
1392                        cx,
1393                        owner,
1394                        f.name.as_str(),
1395                        field_layout,
1396                        Size::ZERO,
1397                        DIFlags::FlagZero,
1398                        type_di_node(cx, field_layout.ty),
1399                        def_id,
1400                    )
1401                })
1402                .collect()
1403        },
1404        // Generics:
1405        |cx| build_generic_type_param_di_nodes(cx, union_type),
1406    )
1407}
1408
1409/// Computes the type parameters for a type, if any, for the given metadata.
1410fn build_generic_type_param_di_nodes<'ll, 'tcx>(
1411    cx: &CodegenCx<'ll, 'tcx>,
1412    ty: Ty<'tcx>,
1413) -> SmallVec<Option<&'ll DIType>> {
1414    if let ty::Adt(def, args) = *ty.kind() {
1415        if args.types().next().is_some() {
1416            let generics = cx.tcx.generics_of(def.did());
1417            let names = get_parameter_names(cx, generics);
1418            let template_params: SmallVec<_> = iter::zip(args, names)
1419                .filter_map(|(kind, name)| {
1420                    kind.as_type().map(|ty| {
1421                        let actual_type = cx.tcx.normalize_erasing_regions(cx.typing_env(), ty);
1422                        let actual_type_di_node = type_di_node(cx, actual_type);
1423                        Some(cx.create_template_type_parameter(name.as_str(), actual_type_di_node))
1424                    })
1425                })
1426                .collect();
1427
1428            return template_params;
1429        }
1430    }
1431
1432    return ::smallvec::SmallVec::new()smallvec![];
1433
1434    fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
1435        let mut names = generics
1436            .parent
1437            .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
1438        names.extend(generics.own_params.iter().map(|param| param.name));
1439        names
1440    }
1441}
1442
1443/// Creates debug information for the given global variable.
1444///
1445/// Adds the created debuginfo nodes directly to the crate's IR.
1446pub(crate) fn build_global_var_di_node<'ll>(
1447    cx: &CodegenCx<'ll, '_>,
1448    def_id: DefId,
1449    global: &'ll Value,
1450) {
1451    if cx.dbg_cx.is_none() {
1452        return;
1453    }
1454
1455    // Only create type information if full debuginfo is enabled
1456    if cx.sess().opts.debuginfo != DebugInfo::Full {
1457        return;
1458    }
1459
1460    let tcx = cx.tcx;
1461
1462    // We may want to remove the namespace scope if we're in an extern block (see
1463    // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
1464    let var_scope = get_namespace_for_item(cx, def_id);
1465    let (file_metadata, line_number) = file_metadata_from_def_id(cx, Some(def_id));
1466
1467    let is_local_to_unit = is_node_local_to_unit(cx, def_id);
1468
1469    let DefKind::Static { nested, .. } = cx.tcx.def_kind(def_id) else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1470    if nested {
1471        return;
1472    }
1473    let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, cx.typing_env());
1474    let type_di_node = type_di_node(cx, variable_type);
1475    let var_name = tcx.item_name(def_id);
1476    let var_name = var_name.as_str();
1477    let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
1478    // When empty, linkage_name field is omitted,
1479    // which is what we want for no_mangle statics
1480    let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
1481
1482    let global_align = cx.align_of(variable_type);
1483
1484    DIB(cx).create_static_variable(
1485        Some(var_scope),
1486        var_name,
1487        linkage_name,
1488        file_metadata,
1489        line_number,
1490        type_di_node,
1491        is_local_to_unit,
1492        global, // (value)
1493        None,   // (decl)
1494        Some(global_align),
1495    );
1496}
1497
1498/// Generates LLVM debuginfo for a vtable.
1499///
1500/// The vtable type looks like a struct with a field for each function pointer and super-trait
1501/// pointer it contains (plus the `size` and `align` fields).
1502///
1503/// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
1504/// the name of the method they implement. This can be implemented in the future once there
1505/// is a proper disambiguation scheme for dealing with methods from different traits that have
1506/// the same name.
1507fn build_vtable_type_di_node<'ll, 'tcx>(
1508    cx: &CodegenCx<'ll, 'tcx>,
1509    ty: Ty<'tcx>,
1510    poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1511) -> &'ll DIType {
1512    let tcx = cx.tcx;
1513
1514    let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
1515        let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
1516        let trait_ref = tcx.erase_and_anonymize_regions(trait_ref);
1517
1518        tcx.vtable_entries(trait_ref)
1519    } else {
1520        TyCtxt::COMMON_VTABLE_ENTRIES
1521    };
1522
1523    // All function pointers are described as opaque pointers. This could be improved in the future
1524    // by describing them as actual function pointers.
1525    let void_pointer_ty = Ty::new_imm_ptr(tcx, tcx.types.unit);
1526    let void_pointer_type_di_node = type_di_node(cx, void_pointer_ty);
1527    let usize_di_node = type_di_node(cx, tcx.types.usize);
1528    let pointer_layout = cx.layout_of(void_pointer_ty);
1529    let pointer_size = pointer_layout.size;
1530    let pointer_align = pointer_layout.align.abi;
1531    // If `usize` is not pointer-sized and -aligned then the size and alignment computations
1532    // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
1533    // platforms.
1534    match (&cx.size_and_align_of(tcx.types.usize), &(pointer_size, pointer_align))
    {
    (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!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
1535
1536    let vtable_type_name =
1537        compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
1538    let unique_type_id = UniqueTypeId::for_vtable_ty(tcx, ty, poly_trait_ref);
1539    let size = pointer_size * vtable_entries.len() as u64;
1540
1541    // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
1542    // the vtable to the type it is for.
1543    let vtable_holder = type_di_node(cx, ty);
1544
1545    build_type_with_children(
1546        cx,
1547        type_map::stub(
1548            cx,
1549            Stub::VTableTy { vtable_holder },
1550            unique_type_id,
1551            &vtable_type_name,
1552            None,
1553            (size, pointer_align),
1554            NO_SCOPE_METADATA,
1555            DIFlags::FlagArtificial,
1556        ),
1557        |cx, vtable_type_di_node| {
1558            vtable_entries
1559                .iter()
1560                .enumerate()
1561                .filter_map(|(index, vtable_entry)| {
1562                    let (field_name, field_type_di_node) = match vtable_entry {
1563                        ty::VtblEntry::MetadataDropInPlace => {
1564                            ("drop_in_place".to_string(), void_pointer_type_di_node)
1565                        }
1566                        ty::VtblEntry::Method(_) => {
1567                            // Note: This code does not try to give a proper name to each method
1568                            //       because their might be multiple methods with the same name
1569                            //       (coming from different traits).
1570                            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__method{0}", index))
    })format!("__method{index}"), void_pointer_type_di_node)
1571                        }
1572                        ty::VtblEntry::TraitVPtr(_) => {
1573                            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__super_trait_ptr{0}", index))
    })format!("__super_trait_ptr{index}"), void_pointer_type_di_node)
1574                        }
1575                        ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node),
1576                        ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node),
1577                        ty::VtblEntry::Vacant => return None,
1578                    };
1579
1580                    let field_offset = pointer_size * index as u64;
1581
1582                    Some(build_field_di_node(
1583                        cx,
1584                        vtable_type_di_node,
1585                        &field_name,
1586                        pointer_layout,
1587                        field_offset,
1588                        DIFlags::FlagZero,
1589                        field_type_di_node,
1590                        None,
1591                    ))
1592                })
1593                .collect()
1594        },
1595        NO_GENERICS,
1596    )
1597    .di_node
1598}
1599
1600/// Creates the debuginfo node for `unsafe<'a> T` binder types.
1601///
1602/// We treat an unsafe binder like a struct with a single field named `inner`
1603/// rather than delegating to the inner type's DI node directly. This way the
1604/// debugger shows the binder's own type name, and the wrapped value is still
1605/// accessible through the `inner` field.
1606fn build_unsafe_binder_type_di_node<'ll, 'tcx>(
1607    cx: &CodegenCx<'ll, 'tcx>,
1608    binder_type: Ty<'tcx>,
1609    unique_type_id: UniqueTypeId<'tcx>,
1610) -> DINodeCreationResult<'ll> {
1611    let ty::UnsafeBinder(inner) = binder_type.kind() else {
1612        ::rustc_middle::util::bug::bug_fmt(format_args!("Only ty::UnsafeBinder is valid for build_unsafe_binder_type_di_node. Found {0:?} instead.",
        binder_type))bug!(
1613            "Only ty::UnsafeBinder is valid for build_unsafe_binder_type_di_node. Found {:?} instead.",
1614            binder_type
1615        )
1616    };
1617    let inner_type = inner.skip_binder();
1618    let inner_type_di_node = type_di_node(cx, inner_type);
1619
1620    let type_name = compute_debuginfo_type_name(cx.tcx, binder_type, true);
1621    type_map::build_type_with_children(
1622        cx,
1623        type_map::stub(
1624            cx,
1625            Stub::Struct,
1626            unique_type_id,
1627            &type_name,
1628            None,
1629            cx.size_and_align_of(binder_type),
1630            NO_SCOPE_METADATA,
1631            DIFlags::FlagZero,
1632        ),
1633        |cx, unsafe_binder_type_di_node| {
1634            let inner_layout = cx.layout_of(inner_type);
1635            {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(build_field_di_node(cx, unsafe_binder_type_di_node, "inner",
                inner_layout, Size::ZERO, DIFlags::FlagZero,
                inner_type_di_node, None));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [build_field_di_node(cx, unsafe_binder_type_di_node,
                                "inner", inner_layout, Size::ZERO, DIFlags::FlagZero,
                                inner_type_di_node, None)])))
    }
}smallvec![build_field_di_node(
1636                cx,
1637                unsafe_binder_type_di_node,
1638                "inner",
1639                inner_layout,
1640                Size::ZERO,
1641                DIFlags::FlagZero,
1642                inner_type_di_node,
1643                None,
1644            )]
1645        },
1646        NO_GENERICS,
1647    )
1648}
1649
1650/// Get the global variable for the vtable.
1651///
1652/// When using global variables, we may have created an addrspacecast to get a pointer to the
1653/// default address space if global variables are created in a different address space.
1654/// For modifying the vtable, we need the real global variable. This function accepts either a
1655/// global variable (which is simply returned), or an addrspacecast constant expression.
1656/// If the given value is an addrspacecast, the cast is removed and the global variable behind
1657/// the cast is returned.
1658fn find_vtable_behind_cast<'ll>(vtable: &'ll Value) -> &'ll Value {
1659    // The vtable is a global variable, which may be behind an addrspacecast.
1660    unsafe {
1661        if let Some(c) = llvm::LLVMIsAConstantExpr(vtable) {
1662            if llvm::LLVMGetConstOpcode(c) == llvm::Opcode::AddrSpaceCast {
1663                return llvm::LLVMGetOperand(c, 0).unwrap();
1664            }
1665        }
1666    }
1667    vtable
1668}
1669
1670pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>(
1671    cx: &CodegenCx<'ll, 'tcx>,
1672    ty: Ty<'tcx>,
1673    trait_ref: Option<ExistentialTraitRef<'tcx>>,
1674    vtable: &'ll Value,
1675) {
1676    // FIXME(flip1995): The virtual function elimination optimization only works with full LTO in
1677    // LLVM at the moment.
1678    if !cx.sess().opts.unstable_opts.virtual_function_elimination || cx.sess().lto() != Lto::Fat {
1679        return;
1680    }
1681
1682    enum VCallVisibility {
1683        Public = 0,
1684        LinkageUnit = 1,
1685        TranslationUnit = 2,
1686    }
1687
1688    let Some(trait_ref) = trait_ref else { return };
1689
1690    // Unwrap potential addrspacecast
1691    let vtable = find_vtable_behind_cast(vtable);
1692    let trait_ref_self = trait_ref.with_self_ty(cx.tcx, ty);
1693    let trait_def_id = trait_ref_self.def_id;
1694    let trait_vis = cx.tcx.visibility(trait_def_id);
1695
1696    let cgus = cx.sess().codegen_units().as_usize();
1697    let single_cgu = cgus == 1;
1698
1699    let lto = cx.sess().lto();
1700
1701    // Since LLVM requires full LTO for the virtual function elimination optimization to apply,
1702    // only the `Lto::Fat` cases are relevant currently.
1703    let vcall_visibility = match (lto, trait_vis, single_cgu) {
1704        // If there is not LTO and the visibility in public, we have to assume that the vtable can
1705        // be seen from anywhere. With multiple CGUs, the vtable is quasi-public.
1706        (Lto::No | Lto::ThinLocal, Visibility::Public, _)
1707        | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public,
1708        // With LTO and a quasi-public visibility, the usages of the functions of the vtable are
1709        // all known by the `LinkageUnit`.
1710        // FIXME: LLVM only supports this optimization for `Lto::Fat` currently. Once it also
1711        // supports `Lto::Thin` the `VCallVisibility` may have to be adjusted for those.
1712        (Lto::Fat | Lto::Thin, Visibility::Public, _)
1713        | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => {
1714            VCallVisibility::LinkageUnit
1715        }
1716        // If there is only one CGU, private vtables can only be seen by that CGU/translation unit
1717        // and therefore we know of all usages of functions in the vtable.
1718        (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit,
1719    };
1720
1721    let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref);
1722    let typeid = cx.create_metadata(trait_ref_typeid.as_bytes());
1723
1724    let type_ = [llvm::LLVMValueAsMetadata(cx.const_usize(0)), typeid];
1725    cx.global_add_metadata_node(vtable, llvm::MD_type, &type_);
1726
1727    let vcall_visibility = [llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64))];
1728    cx.global_set_metadata_node(vtable, llvm::MD_vcall_visibility, &vcall_visibility);
1729}
1730
1731/// Creates debug information for the given vtable, which is for the
1732/// given type.
1733///
1734/// Adds the created metadata nodes directly to the crate's IR.
1735pub(crate) fn create_vtable_di_node<'ll, 'tcx>(
1736    cx: &CodegenCx<'ll, 'tcx>,
1737    ty: Ty<'tcx>,
1738    poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1739    vtable: &'ll Value,
1740) {
1741    if cx.dbg_cx.is_none() {
1742        return;
1743    }
1744
1745    // Only create type information if full debuginfo is enabled
1746    if cx.sess().opts.debuginfo != DebugInfo::Full {
1747        return;
1748    }
1749
1750    // Unwrap potential addrspacecast
1751    let vtable = find_vtable_behind_cast(vtable);
1752
1753    // When full debuginfo is enabled, we want to try and prevent vtables from being
1754    // merged. Otherwise debuggers will have a hard time mapping from dyn pointer
1755    // to concrete type.
1756    llvm::set_unnamed_address(vtable, llvm::UnnamedAddr::No);
1757
1758    let vtable_name =
1759        compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
1760    let vtable_type_di_node = build_vtable_type_di_node(cx, ty, poly_trait_ref);
1761
1762    DIB(cx).create_static_variable(
1763        NO_SCOPE_METADATA,
1764        &vtable_name,
1765        "", // (linkage_name)
1766        unknown_file_metadata(cx),
1767        UNKNOWN_LINE_NUMBER,
1768        vtable_type_di_node,
1769        true,   // (is_local_to_unit)
1770        vtable, // (value)
1771        None,   // (decl)
1772        None::<Align>,
1773    );
1774}
1775
1776/// Creates an "extension" of an existing `DIScope` into another file.
1777pub(crate) fn extend_scope_to_file<'ll>(
1778    cx: &CodegenCx<'ll, '_>,
1779    scope_metadata: &'ll DIScope,
1780    file: &SourceFile,
1781) -> &'ll DILexicalBlock {
1782    let file_metadata = file_metadata(cx, file);
1783    unsafe {
1784        llvm::LLVMDIBuilderCreateLexicalBlockFile(
1785            DIB(cx),
1786            scope_metadata,
1787            file_metadata,
1788            /* Discriminator (default) */ 0u32,
1789        )
1790    }
1791}
1792
1793fn tuple_field_name(field_index: usize) -> Cow<'static, str> {
1794    const TUPLE_FIELD_NAMES: [&'static str; 16] = [
1795        "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11",
1796        "__12", "__13", "__14", "__15",
1797    ];
1798    TUPLE_FIELD_NAMES
1799        .get(field_index)
1800        .map(|s| Cow::from(*s))
1801        .unwrap_or_else(|| Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__{0}", field_index))
    })format!("__{field_index}")))
1802}
1803
1804pub(crate) type DefinitionLocation<'ll> = (&'ll DIFile, c_uint);
1805
1806pub(crate) fn file_metadata_from_def_id<'ll>(
1807    cx: &CodegenCx<'ll, '_>,
1808    def_id: Option<DefId>,
1809) -> DefinitionLocation<'ll> {
1810    if let Some(def_id) = def_id
1811        && let span = hygiene::walk_chain_collapsed(cx.tcx.def_span(def_id), DUMMY_SP)
1812        && !span.is_dummy()
1813    {
1814        let loc = cx.lookup_debug_loc(span.lo());
1815        (file_metadata(cx, &loc.file), loc.line)
1816    } else {
1817        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1818    }
1819}