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::{assert_matches, iter, ptr};
6
7use libc::{c_longlong, c_uint};
8use rustc_abi::{Align, Layout, NumScalableVectors, Size};
9use rustc_codegen_ssa::debuginfo::type_names::{VTableNameKind, cpp_like_debuginfo};
10use rustc_codegen_ssa::traits::*;
11use rustc_hir::def::{CtorKind, DefKind};
12use rustc_hir::def_id::{DefId, LOCAL_CRATE};
13use rustc_middle::ty::layout::{
14    HasTypingEnv, LayoutOf, TyAndLayout, WIDE_PTR_ADDR, WIDE_PTR_EXTRA,
15};
16use rustc_middle::ty::{
17    self, AdtDef, AdtKind, ExistentialTraitRef, Instance, Ty, TyCtxt, Unnormalized, Visibility,
18};
19use rustc_session::config::{self, DebugInfo, Lto};
20use rustc_span::{
21    DUMMY_SP, FileName, RemapPathScopeComponents, SourceFile, Span, Symbol, bug, hygiene,
22};
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        bug_impl(None,
    format_args!("build_fixed_size_array_di_node() called with non-ty::Array type `{0:?}`",
        array_type), Location::caller())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    span: Span,
148) -> DINodeCreationResult<'ll> {
149    // The debuginfo generated by this function is only valid if `ptr_type` is really just
150    // a (wide) pointer. Make sure it is not called for e.g. `Box<T, NonZSTAllocator>`.
151    {
    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!(
152        cx.size_and_align_of(ptr_type),
153        cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type))
154    );
155
156    let pointee_type_di_node = match pointee_type.kind() {
157        // `&[T]` will look like `{ data_ptr: *const T, length: usize }`
158        ty::Slice(element_type) => spanned_type_di_node(cx, *element_type, span),
159        // `&str` will look like `{ data_ptr: *const u8, length: usize }`
160        ty::Str => type_di_node(cx, cx.tcx.types.u8),
161
162        // `&dyn K` will look like `{ pointer: _, vtable: _}`
163        // any Adt `Foo` containing an unsized type (eg `&[_]` or `&dyn _`)
164        //   will look like `{ data_ptr: *const Foo, length: usize }`
165        // and thin pointers `&Foo` will just look like `*const Foo`.
166        //
167        // in all those cases, we just use the pointee_type
168        _ => spanned_type_di_node(cx, pointee_type, span),
169    };
170
171    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);
172
173    let data_layout = &cx.tcx.data_layout;
174    let pointer_size = data_layout.pointer_size();
175    let pointer_align = data_layout.pointer_align();
176    let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
177
178    match wide_pointer_kind(cx, pointee_type) {
179        None => {
180            // This is a thin pointer. Create a regular pointer type and give it the correct name.
181            {
    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!(
182                (pointer_size, pointer_align.abi),
183                cx.size_and_align_of(ptr_type),
184                "ptr_type={ptr_type}, pointee_type={pointee_type}",
185            );
186
187            let di_node = create_pointer_type(
188                cx,
189                pointee_type_di_node,
190                pointer_size,
191                pointer_align.abi,
192                &ptr_type_debuginfo_name,
193            );
194
195            DINodeCreationResult { di_node, already_stored_in_typemap: false }
196        }
197        Some(wide_pointer_kind) => {
198            type_map::build_type_with_children(
199                cx,
200                type_map::stub(
201                    cx,
202                    Stub::Struct,
203                    unique_type_id,
204                    &ptr_type_debuginfo_name,
205                    None,
206                    cx.size_and_align_of(ptr_type),
207                    NO_SCOPE_METADATA,
208                    DIFlags::FlagZero,
209                ),
210                |cx, owner| {
211                    // FIXME: If this wide pointer is a `Box` then we don't want to use its
212                    //        type layout and instead use the layout of the raw pointer inside
213                    //        of it.
214                    //        The proper way to handle this is to not treat Box as a pointer
215                    //        at all and instead emit regular struct debuginfo for it. We just
216                    //        need to make sure that we don't break existing debuginfo consumers
217                    //        by doing that (at least not without a warning period).
218                    let layout_type = if ptr_type.is_box() {
219                        // The assertion at the start of this function ensures we have a ZST
220                        // allocator. We'll make debuginfo "skip" all ZST allocators, not just the
221                        // default allocator.
222                        Ty::new_mut_ptr(cx.tcx, pointee_type)
223                    } else {
224                        ptr_type
225                    };
226
227                    let layout = cx.layout_of(layout_type);
228                    let addr_field = layout.field(cx, WIDE_PTR_ADDR);
229                    let extra_field = layout.field(cx, WIDE_PTR_EXTRA);
230
231                    let (addr_field_name, extra_field_name) = match wide_pointer_kind {
232                        WidePtrKind::Dyn => ("pointer", "vtable"),
233                        WidePtrKind::Slice => ("data_ptr", "length"),
234                    };
235
236                    {
    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);
237                    {
    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);
238
239                    // The data pointer type is a regular, thin pointer, regardless of whether this
240                    // is a slice or a trait object.
241                    let data_ptr_type_di_node = create_pointer_type(
242                        cx,
243                        pointee_type_di_node,
244                        addr_field.size,
245                        addr_field.align.abi,
246                        "",
247                    );
248
249                    {
    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![
250                        build_field_di_node(
251                            cx,
252                            owner,
253                            addr_field_name,
254                            addr_field,
255                            layout.fields.offset(WIDE_PTR_ADDR),
256                            DIFlags::FlagZero,
257                            data_ptr_type_di_node,
258                            None,
259                        ),
260                        build_field_di_node(
261                            cx,
262                            owner,
263                            extra_field_name,
264                            extra_field,
265                            layout.fields.offset(WIDE_PTR_EXTRA),
266                            DIFlags::FlagZero,
267                            type_di_node(cx, extra_field.ty),
268                            None,
269                        ),
270                    ]
271                },
272                NO_GENERICS,
273            )
274        }
275    }
276}
277
278fn build_subroutine_type_di_node<'ll, 'tcx>(
279    cx: &CodegenCx<'ll, 'tcx>,
280    unique_type_id: UniqueTypeId<'tcx>,
281) -> DINodeCreationResult<'ll> {
282    // It's possible to create a self-referential type in Rust by using 'impl trait':
283    //
284    // fn foo() -> impl Copy { foo }
285    //
286    // Unfortunately LLVM's API does not allow us to create recursive subroutine types.
287    // In order to work around that restriction we place a marker type in the type map,
288    // before creating the actual type. If the actual type is recursive, it will hit the
289    // marker type. So we end up with a type that looks like
290    //
291    // fn foo() -> <recursive_type>
292    //
293    // Once that is created, we replace the marker in the typemap with the actual type.
294    debug_context(cx)
295        .type_map
296        .unique_id_to_di_node
297        .borrow_mut()
298        .insert(unique_type_id, recursion_marker_type_di_node(cx));
299
300    let fn_ty = unique_type_id.expect_ty();
301    let signature =
302        cx.tcx.normalize_erasing_late_bound_regions(cx.typing_env(), fn_ty.fn_sig(cx.tcx));
303
304    let signature_di_nodes: SmallVec<_> = iter::once(
305        // return type
306        match signature.output().kind() {
307            ty::Tuple(tys) if tys.is_empty() => {
308                // this is a "void" function
309                None
310            }
311            _ => Some(type_di_node(cx, signature.output())),
312        },
313    )
314    .chain(
315        // regular arguments
316        signature.inputs().iter().map(|&argument_type| Some(type_di_node(cx, argument_type))),
317    )
318    .collect();
319
320    debug_context(cx).type_map.unique_id_to_di_node.borrow_mut().remove(&unique_type_id);
321
322    let fn_di_node = create_subroutine_type(cx, &signature_di_nodes[..]);
323
324    // This is actually a function pointer, so wrap it in pointer DI.
325    let name = compute_debuginfo_type_name(cx.tcx, fn_ty, false);
326    let (size, align) = match fn_ty.kind() {
327        ty::FnDef(..) => (Size::ZERO, Align::ONE),
328        ty::FnPtr(..) => {
329            (cx.tcx.data_layout.pointer_size(), cx.tcx.data_layout.pointer_align().abi)
330        }
331        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
332    };
333    let di_node = create_pointer_type(cx, fn_di_node, size, align, &name);
334
335    DINodeCreationResult::new(di_node, false)
336}
337
338pub(super) fn create_subroutine_type<'ll>(
339    cx: &CodegenCx<'ll, '_>,
340    signature: &[Option<&'ll llvm::Metadata>],
341) -> &'ll DICompositeType {
342    unsafe {
343        llvm::LLVMDIBuilderCreateSubroutineType(
344            DIB(cx),
345            None, // ("File" is ignored and has no effect)
346            signature.as_ptr(),
347            signature.len() as c_uint,
348            DIFlags::FlagZero, // (default value)
349        )
350    }
351}
352
353fn create_pointer_type<'ll>(
354    cx: &CodegenCx<'ll, '_>,
355    pointee_ty: &'ll llvm::Metadata,
356    size: Size,
357    align: Align,
358    name: &str,
359) -> &'ll llvm::Metadata {
360    unsafe {
361        llvm::LLVMDIBuilderCreatePointerType(
362            DIB(cx),
363            pointee_ty,
364            size.bits(),
365            align.bits() as u32,
366            0, // Ignore DWARF address space.
367            name.as_ptr(),
368            name.len(),
369        )
370    }
371}
372
373/// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
374/// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
375fn build_dyn_type_di_node<'ll, 'tcx>(
376    cx: &CodegenCx<'ll, 'tcx>,
377    dyn_type: Ty<'tcx>,
378    unique_type_id: UniqueTypeId<'tcx>,
379) -> DINodeCreationResult<'ll> {
380    if let ty::Dynamic(..) = dyn_type.kind() {
381        let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
382        type_map::build_type_with_children(
383            cx,
384            type_map::stub(
385                cx,
386                Stub::Struct,
387                unique_type_id,
388                &type_name,
389                None,
390                cx.size_and_align_of(dyn_type),
391                NO_SCOPE_METADATA,
392                DIFlags::FlagZero,
393            ),
394            |_, _| ::smallvec::SmallVec::new()smallvec![],
395            NO_GENERICS,
396        )
397    } else {
398        bug_impl(None,
    format_args!("Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {0:?} instead.",
        dyn_type), Location::caller())bug!(
399            "Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {:?} instead.",
400            dyn_type
401        )
402    }
403}
404
405/// Create debuginfo for `[T]` and `str`. These are unsized.
406fn build_slice_type_di_node<'ll, 'tcx>(
407    cx: &CodegenCx<'ll, 'tcx>,
408    slice_type: Ty<'tcx>,
409    unique_type_id: UniqueTypeId<'tcx>,
410    span: Span,
411) -> DINodeCreationResult<'ll> {
412    let element_type = match slice_type.kind() {
413        ty::Slice(element_type) => *element_type,
414        ty::Str => cx.tcx.types.u8,
415        _ => {
416            bug_impl(None,
    format_args!("Only ty::Slice is valid for build_slice_type_di_node(). Found {0:?} instead.",
        slice_type), Location::caller())bug!(
417                "Only ty::Slice is valid for build_slice_type_di_node(). Found {:?} instead.",
418                slice_type
419            )
420        }
421    };
422
423    let element_type_di_node = type_di_node(cx, element_type);
424    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);
425    let (size, align) = cx.spanned_size_and_align_of(slice_type, span);
426    let subrange = unsafe { llvm::LLVMDIBuilderGetOrCreateSubrange(DIB(cx), 0, -1) };
427    let subscripts = &[subrange];
428    let di_node = unsafe {
429        llvm::LLVMDIBuilderCreateArrayType(
430            DIB(cx),
431            size.bits(),
432            align.bits() as u32,
433            element_type_di_node,
434            subscripts.as_ptr(),
435            subscripts.len() as c_uint,
436        )
437    };
438    DINodeCreationResult { di_node, already_stored_in_typemap: false }
439}
440
441/// Get the debuginfo node for the given type.
442///
443/// This function will look up the debuginfo node in the TypeMap. If it can't find it, it
444/// will create the node by dispatching to the corresponding `build_*_di_node()` function.
445pub(crate) fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
446    spanned_type_di_node(cx, t, DUMMY_SP)
447}
448
449pub(crate) fn spanned_type_di_node<'ll, 'tcx>(
450    cx: &CodegenCx<'ll, 'tcx>,
451    t: Ty<'tcx>,
452    span: Span,
453) -> &'ll DIType {
454    let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t);
455
456    if let Some(existing_di_node) = debug_context(cx).type_map.di_node_for_unique_id(unique_type_id)
457    {
458        return existing_di_node;
459    }
460
461    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:461",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(461u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type_di_node: {0:?} kind: {1:?}",
                                                    t, t.kind()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("type_di_node: {:?} kind: {:?}", t, t.kind());
462
463    let DINodeCreationResult { di_node, already_stored_in_typemap } = match *t.kind() {
464        ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
465            build_basic_type_di_node(cx, t)
466        }
467        ty::Tuple(elements) if elements.is_empty() => build_basic_type_di_node(cx, t),
468        ty::Array(..) => build_fixed_size_array_di_node(cx, unique_type_id, t, span),
469        ty::Slice(_) | ty::Str => build_slice_type_di_node(cx, t, unique_type_id, span),
470        ty::Dynamic(..) => build_dyn_type_di_node(cx, t, unique_type_id),
471        ty::Foreign(..) => build_foreign_type_di_node(cx, t, unique_type_id),
472        ty::RawPtr(pointee_type, _) | ty::Ref(_, pointee_type, _) => {
473            build_pointer_or_reference_di_node(cx, t, pointee_type, unique_type_id, span)
474        }
475        // Some `Box` are newtyped pointers, make debuginfo aware of that.
476        // Only works if the allocator argument is a 1-ZST and hence irrelevant for layout
477        // (or if there is no allocator argument).
478        ty::Adt(def, args)
479            if def.is_box()
480                && args.get(1).is_none_or(|arg| cx.layout_of(arg.expect_ty()).is_1zst()) =>
481        {
482            build_pointer_or_reference_di_node(cx, t, t.expect_boxed_ty(), unique_type_id, span)
483        }
484        ty::FnDef(..) | ty::FnPtr(..) => build_subroutine_type_di_node(cx, unique_type_id),
485        ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id),
486        ty::CoroutineClosure(..) => build_closure_env_di_node(cx, unique_type_id),
487        ty::Coroutine(..) => enums::build_coroutine_di_node(cx, unique_type_id),
488        ty::Adt(def, ..) => match def.adt_kind() {
489            AdtKind::Struct => build_struct_type_di_node(cx, unique_type_id, span),
490            AdtKind::Union => build_union_type_di_node(cx, unique_type_id, span),
491            AdtKind::Enum => enums::build_enum_type_di_node(cx, unique_type_id, span),
492        },
493        ty::Tuple(_) => build_tuple_type_di_node(cx, unique_type_id),
494        ty::Pat(base, _) => return type_di_node(cx, base),
495        ty::UnsafeBinder(_) => build_unsafe_binder_type_di_node(cx, t, unique_type_id),
496        ty::Alias(..)
497        | ty::Param(_)
498        | ty::Bound(..)
499        | ty::Infer(_)
500        | ty::Placeholder(_)
501        | ty::CoroutineWitness(..)
502        | ty::Error(_) => {
503            bug_impl(None,
    format_args!("debuginfo: unexpected type in type_di_node(): {0:?}", t),
    Location::caller())bug!("debuginfo: unexpected type in type_di_node(): {:?}", t)
504        }
505    };
506
507    {
508        if already_stored_in_typemap {
509            // Make sure that we really do have a `TypeMap` entry for the unique type ID.
510            let di_node_for_uid =
511                match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
512                    Some(di_node) => di_node,
513                    None => {
514                        bug_impl(None,
    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), Location::caller());bug!(
515                            "expected type debuginfo node for unique \
516                               type ID '{:?}' to already be in \
517                               the `debuginfo::TypeMap` but it \
518                               was not.",
519                            unique_type_id,
520                        );
521                    }
522                };
523
524            {
    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 _);
525        } else {
526            debug_context(cx).type_map.insert(unique_type_id, di_node);
527        }
528    }
529
530    di_node
531}
532
533// FIXME(mw): Cache this via a regular UniqueTypeId instead of an extra field in the debug context.
534fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
535    *debug_context(cx).recursion_marker_type.get_or_init(move || {
536        // The choice of type here is pretty arbitrary -
537        // anything reading the debuginfo for a recursive
538        // type is going to see *something* weird - the only
539        // question is what exactly it will see.
540        //
541        // FIXME: the name `<recur_type>` does not fit the naming scheme
542        //        of other types.
543        //
544        // FIXME: it might make sense to use an actual pointer type here
545        //        so that debuggers can show the address.
546        create_basic_type(
547            cx,
548            "<recur_type>",
549            cx.tcx.data_layout.pointer_size(),
550            dwarf_const::DW_ATE_unsigned,
551        )
552    })
553}
554
555fn hex_encode(data: &[u8]) -> String {
556    let mut hex_string = String::with_capacity(data.len() * 2);
557    for byte in data.iter() {
558        (&mut hex_string).write_fmt(format_args!("{0:02x}", byte))write!(&mut hex_string, "{byte:02x}").unwrap();
559    }
560    hex_string
561}
562
563pub(crate) fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
564    let cache_key = Some((source_file.stable_id, source_file.src_hash));
565    return debug_context(cx)
566        .created_files
567        .borrow_mut()
568        .entry(cache_key)
569        .or_insert_with(|| alloc_new_file_metadata(cx, source_file));
570
571    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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(&[],
                                        ::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_all(&[]) })
                } 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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:576",
                                    "rustc_codegen_llvm::debuginfo::metadata",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                    ::tracing_core::__macro_support::Option::Some(576u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_file.name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_file.name");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_file.name)
                                                        as &dyn ::tracing::field::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:583",
                                                "rustc_codegen_llvm::debuginfo::metadata",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                                ::tracing_core::__macro_support::Option::Some(583u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("working_directory")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("working_directory");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("embeddable_name")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("embeddable_name");
                                                                    NAME.as_str()
                                                                }], ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&working_directory)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&embeddable_name)
                                                                    as &dyn ::tracing::field::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:608",
                                                "rustc_codegen_llvm::debuginfo::metadata",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                                ::tracing_core::__macro_support::Option::Some(608u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("other")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("other");
                                                                    NAME.as_str()
                                                                }], ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&other)
                                                                    as &dyn ::tracing::field::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 mut source = None;
            let external_src;
            if cx.sess().opts.unstable_opts.embed_source {
                source = source_file.src.as_deref().map(String::as_str);
                if source.is_none() {
                    cx.tcx.sess.source_map().ensure_source_file_source_present(source_file);
                    external_src = source_file.external_src.read();
                    source = external_src.get_source();
                }
            }
            create_file(DIB(cx), &file_name, &directory, &hash_value,
                hash_kind, source)
        }
    }
}#[instrument(skip(cx, source_file), level = "debug")]
572    fn alloc_new_file_metadata<'ll>(
573        cx: &CodegenCx<'ll, '_>,
574        source_file: &SourceFile,
575    ) -> &'ll DIFile {
576        debug!(?source_file.name);
577
578        let (directory, file_name) = match &source_file.name {
579            FileName::Real(filename) => {
580                let (working_directory, embeddable_name) =
581                    filename.embeddable_name(RemapPathScopeComponents::DEBUGINFO);
582
583                debug!(?working_directory, ?embeddable_name);
584
585                if let Ok(rel_path) = embeddable_name.strip_prefix(working_directory) {
586                    // If the compiler's working directory (which also is the DW_AT_comp_dir of
587                    // the compilation unit) is a prefix of the path we are about to emit, then
588                    // only emit the part relative to the working directory. Because of path
589                    // remapping we sometimes see strange things here: `abs_path` might
590                    // actually look like a relative path (e.g.
591                    // `<crate-name-and-version>/src/lib.rs`), so if we emit it without taking
592                    // the working directory into account, downstream tooling will interpret it
593                    // as `<working-directory>/<crate-name-and-version>/src/lib.rs`, which
594                    // makes no sense. Usually in such cases the working directory will also be
595                    // remapped to `<crate-name-and-version>` or some other prefix of the path
596                    // we are remapping, so we end up with
597                    // `<crate-name-and-version>/<crate-name-and-version>/src/lib.rs`.
598                    //
599                    // By moving the working directory portion into the `directory` part of the
600                    // DIFile, we allow LLVM to emit just the relative path for DWARF, while
601                    // still emitting the correct absolute path for CodeView.
602                    (working_directory.to_string_lossy(), rel_path.to_string_lossy().into_owned())
603                } else {
604                    ("".into(), embeddable_name.to_string_lossy().into_owned())
605                }
606            }
607            other => {
608                debug!(?other);
609                ("".into(), other.display(RemapPathScopeComponents::DEBUGINFO).to_string())
610            }
611        };
612
613        let hash_kind = match source_file.src_hash.kind {
614            rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
615            rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
616            rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
617            rustc_span::SourceFileHashAlgorithm::Blake3 => llvm::ChecksumKind::None,
618        };
619        let hash_value = hex_encode(source_file.src_hash.hash_bytes());
620
621        let mut source = None;
622        let external_src;
623        if cx.sess().opts.unstable_opts.embed_source {
624            source = source_file.src.as_deref().map(String::as_str);
625            if source.is_none() {
626                cx.tcx.sess.source_map().ensure_source_file_source_present(source_file);
627                external_src = source_file.external_src.read();
628                source = external_src.get_source();
629            }
630        }
631
632        create_file(DIB(cx), &file_name, &directory, &hash_value, hash_kind, source)
633    }
634}
635
636fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
637    debug_context(cx).created_files.borrow_mut().entry(None).or_insert_with(|| {
638        create_file(DIB(cx), "<unknown>", "", "", llvm::ChecksumKind::None, None)
639    })
640}
641
642fn create_file<'ll>(
643    builder: &DIBuilder<'ll>,
644    file_name: &str,
645    directory: &str,
646    hash_value: &str,
647    hash_kind: llvm::ChecksumKind,
648    source: Option<&str>,
649) -> &'ll DIFile {
650    unsafe {
651        llvm::LLVMRustDIBuilderCreateFile(
652            builder,
653            file_name.as_c_char_ptr(),
654            file_name.len(),
655            directory.as_c_char_ptr(),
656            directory.len(),
657            hash_kind,
658            hash_value.as_c_char_ptr(),
659            hash_value.len(),
660            source.map_or(ptr::null(), |x| x.as_c_char_ptr()),
661            source.map_or(0, |x| x.len()),
662        )
663    }
664}
665
666trait MsvcBasicName {
667    fn msvc_basic_name(self) -> &'static str;
668}
669
670impl MsvcBasicName for ty::IntTy {
671    fn msvc_basic_name(self) -> &'static str {
672        match self {
673            ty::IntTy::Isize => "ptrdiff_t",
674            ty::IntTy::I8 => "__int8",
675            ty::IntTy::I16 => "__int16",
676            ty::IntTy::I32 => "__int32",
677            ty::IntTy::I64 => "__int64",
678            ty::IntTy::I128 => "__int128",
679        }
680    }
681}
682
683impl MsvcBasicName for ty::UintTy {
684    fn msvc_basic_name(self) -> &'static str {
685        match self {
686            ty::UintTy::Usize => "size_t",
687            ty::UintTy::U8 => "unsigned __int8",
688            ty::UintTy::U16 => "unsigned __int16",
689            ty::UintTy::U32 => "unsigned __int32",
690            ty::UintTy::U64 => "unsigned __int64",
691            ty::UintTy::U128 => "unsigned __int128",
692        }
693    }
694}
695
696impl MsvcBasicName for ty::FloatTy {
697    fn msvc_basic_name(self) -> &'static str {
698        // FIXME(f128): `f128` has no MSVC representation. We could improve the debuginfo.
699        // See: <https://github.com/rust-lang/rust/issues/121837>
700        match self {
701            ty::FloatTy::F16 => {
702                bug_impl(None,
    format_args!("`f16` should have been handled in `build_basic_type_di_node`"),
    Location::caller())bug!("`f16` should have been handled in `build_basic_type_di_node`")
703            }
704            ty::FloatTy::F32 => "float",
705            ty::FloatTy::F64 => "double",
706            ty::FloatTy::F128 => "fp128",
707        }
708    }
709}
710
711fn build_cpp_f16_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> DINodeCreationResult<'ll> {
712    // MSVC has no native support for `f16`. Instead, emit `struct f16 { bits: u16 }` to allow the
713    // `f16`'s value to be displayed using a Natvis visualiser in `intrinsic.natvis`.
714    let float_ty = cx.tcx.types.f16;
715    let bits_ty = cx.tcx.types.u16;
716    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
717        match float_ty.kind() {
718            ty::Adt(def, _) => Some(file_metadata_from_def_id(cx, Some(def.did()))),
719            _ => None,
720        }
721    } else {
722        None
723    };
724    type_map::build_type_with_children(
725        cx,
726        type_map::stub(
727            cx,
728            Stub::Struct,
729            UniqueTypeId::for_ty(cx.tcx, float_ty),
730            "f16",
731            def_location,
732            cx.size_and_align_of(float_ty),
733            NO_SCOPE_METADATA,
734            DIFlags::FlagZero,
735        ),
736        // Fields:
737        |cx, float_di_node| {
738            let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
739                match bits_ty.kind() {
740                    ty::Adt(def, _) => Some(def.did()),
741                    _ => None,
742                }
743            } else {
744                None
745            };
746            {
    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(
747                cx,
748                float_di_node,
749                "bits",
750                cx.layout_of(bits_ty),
751                Size::ZERO,
752                DIFlags::FlagZero,
753                type_di_node(cx, bits_ty),
754                def_id,
755            )]
756        },
757        NO_GENERICS,
758    )
759}
760
761fn build_basic_type_di_node<'ll, 'tcx>(
762    cx: &CodegenCx<'ll, 'tcx>,
763    t: Ty<'tcx>,
764) -> DINodeCreationResult<'ll> {
765    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:765",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(765u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_basic_type_di_node: {0:?}",
                                                    t) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_basic_type_di_node: {:?}", t);
766
767    // When targeting MSVC, emit MSVC style type names for compatibility with
768    // .natvis visualizers (and perhaps other existing native debuggers?)
769    let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
770
771    use dwarf_const::{DW_ATE_UTF, DW_ATE_boolean, DW_ATE_float, DW_ATE_signed, DW_ATE_unsigned};
772
773    let (name, encoding) = match t.kind() {
774        ty::Never => ("!", DW_ATE_unsigned),
775        ty::Tuple(elements) if elements.is_empty() => {
776            if cpp_like_debuginfo {
777                return build_tuple_type_di_node(cx, UniqueTypeId::for_ty(cx.tcx, t));
778            } else {
779                ("()", DW_ATE_unsigned)
780            }
781        }
782        ty::Bool => ("bool", DW_ATE_boolean),
783        ty::Char => ("char", DW_ATE_UTF),
784        ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
785        ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
786        ty::Float(ty::FloatTy::F16) if cpp_like_debuginfo => {
787            return build_cpp_f16_di_node(cx);
788        }
789        ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
790        ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
791        ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
792        ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
793        _ => bug_impl(None,
    format_args!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
    Location::caller())bug!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
794    };
795
796    let ty_di_node = create_basic_type(cx, name, cx.size_of(t), encoding);
797
798    if !cpp_like_debuginfo {
799        return DINodeCreationResult::new(ty_di_node, false);
800    }
801
802    let typedef_name = match t.kind() {
803        ty::Int(int_ty) => int_ty.name_str(),
804        ty::Uint(uint_ty) => uint_ty.name_str(),
805        ty::Float(float_ty) => float_ty.name_str(),
806        _ => return DINodeCreationResult::new(ty_di_node, false),
807    };
808
809    let typedef_di_node = unsafe {
810        llvm::LLVMDIBuilderCreateTypedef(
811            DIB(cx),
812            ty_di_node,
813            typedef_name.as_ptr(),
814            typedef_name.len(),
815            unknown_file_metadata(cx),
816            0,    // (no line number)
817            None, // (no scope)
818            0u32, // (no alignment specified)
819        )
820    };
821
822    DINodeCreationResult::new(typedef_di_node, false)
823}
824
825fn create_basic_type<'ll, 'tcx>(
826    cx: &CodegenCx<'ll, 'tcx>,
827    name: &str,
828    size: Size,
829    encoding: u32,
830) -> &'ll DIBasicType {
831    unsafe {
832        llvm::LLVMDIBuilderCreateBasicType(
833            DIB(cx),
834            name.as_ptr(),
835            name.len(),
836            size.bits(),
837            encoding,
838            DIFlags::FlagZero,
839        )
840    }
841}
842
843fn build_foreign_type_di_node<'ll, 'tcx>(
844    cx: &CodegenCx<'ll, 'tcx>,
845    t: Ty<'tcx>,
846    unique_type_id: UniqueTypeId<'tcx>,
847) -> DINodeCreationResult<'ll> {
848    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:848",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(848u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_foreign_type_di_node: {0:?}",
                                                    t) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_foreign_type_di_node: {:?}", t);
849
850    let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else {
851        bug_impl(None,
    format_args!("build_foreign_type_di_node() called with unexpected type: {0:?}",
        unique_type_id.expect_ty()), Location::caller());bug!(
852            "build_foreign_type_di_node() called with unexpected type: {:?}",
853            unique_type_id.expect_ty()
854        );
855    };
856
857    build_type_with_children(
858        cx,
859        type_map::stub(
860            cx,
861            Stub::Struct,
862            unique_type_id,
863            &compute_debuginfo_type_name(cx.tcx, t, false),
864            None,
865            cx.size_and_align_of(t),
866            Some(get_namespace_for_item(cx, def_id)),
867            DIFlags::FlagZero,
868        ),
869        |_, _| ::smallvec::SmallVec::new()smallvec![],
870        NO_GENERICS,
871    )
872}
873
874pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
875    tcx: TyCtxt<'tcx>,
876    codegen_unit_name: &str,
877    debug_context: &CodegenUnitDebugContext<'ll, 'tcx>,
878) -> &'ll DIDescriptor {
879    let mut name_in_debuginfo = tcx
880        .sess
881        .local_crate_source_file()
882        .map(|src| src.path(RemapPathScopeComponents::DEBUGINFO).to_path_buf())
883        .unwrap_or_else(|| PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()));
884
885    // To avoid breaking split DWARF, we need to ensure that each codegen unit
886    // has a unique `DW_AT_name`. This is because there's a remote chance that
887    // different codegen units for the same module will have entirely
888    // identical DWARF entries for the purpose of the DWO ID, which would
889    // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
890    // specification. LLVM uses the algorithm specified in section 7.32 "Type
891    // Signature Computation" to compute the DWO ID, which does not include
892    // any fields that would distinguish compilation units. So we must embed
893    // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
894    //
895    // Additionally, the OSX linker has an idiosyncrasy where it will ignore
896    // some debuginfo if multiple object files with the same `DW_AT_name` are
897    // linked together.
898    //
899    // As a workaround for these two issues, we generate unique names for each
900    // object file. Those do not correspond to an actual source file but that
901    // is harmless.
902    name_in_debuginfo.push("@");
903    name_in_debuginfo.push(codegen_unit_name);
904
905    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:905",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(905u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_compile_unit_di_node: {0:?}",
                                                    name_in_debuginfo) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
906    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);
907    // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
908    let producer = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("clang LLVM ({0})", rustc_producer))
    })format!("clang LLVM ({rustc_producer})");
909
910    let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
911    let work_dir = tcx.sess.psess.source_map().working_dir();
912    let output_filenames = tcx.output_filenames(());
913    let split_name = if tcx.sess.target_can_use_split_dwarf()
914        && let Some(f) = output_filenames.split_dwarf_path(
915            tcx.sess.split_debuginfo(),
916            tcx.sess.opts.unstable_opts.split_dwarf_kind,
917            codegen_unit_name,
918        ) {
919        // We get a path relative to the working directory from split_dwarf_path
920        Some(tcx.sess.source_map().path_mapping().to_real_filename(work_dir, f))
921    } else {
922        None
923    };
924    let split_name = split_name
925        .as_ref()
926        .map(|f| f.path(RemapPathScopeComponents::DEBUGINFO).to_string_lossy())
927        .unwrap_or_default();
928    let work_dir = work_dir.path(RemapPathScopeComponents::DEBUGINFO).to_string_lossy();
929    let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
930
931    let dwarf_version = tcx.sess.dwarf_version();
932    let is_dwarf_kind =
933        #[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);
934    // Don't emit `.debug_pubnames` and `.debug_pubtypes` on DWARFv4 or lower.
935    let debug_name_table_kind = if is_dwarf_kind && dwarf_version <= 4 {
936        DebugNameTableKind::None
937    } else {
938        DebugNameTableKind::Default
939    };
940
941    unsafe {
942        let compile_unit_file = create_file(
943            debug_context.builder.as_ref(),
944            &name_in_debuginfo,
945            &work_dir,
946            "",
947            llvm::ChecksumKind::None,
948            None,
949        );
950
951        let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
952            debug_context.builder.as_ref(),
953            dwarf_const::DW_LANG_Rust,
954            compile_unit_file,
955            producer.as_c_char_ptr(),
956            producer.len(),
957            tcx.sess.opts.optimize != config::OptLevel::No,
958            c"".as_ptr(),
959            0,
960            // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
961            // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
962            // output(s).
963            split_name.as_c_char_ptr(),
964            split_name.len(),
965            kind,
966            0,
967            tcx.sess.opts.unstable_opts.split_dwarf_inlining,
968            debug_name_table_kind,
969        );
970
971        return unit_metadata;
972    };
973}
974
975/// Creates a `DW_TAG_member` entry inside the DIE represented by the given `type_di_node`.
976fn build_field_di_node<'ll, 'tcx>(
977    cx: &CodegenCx<'ll, 'tcx>,
978    owner: &'ll DIScope,
979    name: &str,
980    layout: TyAndLayout<'tcx>,
981    offset: Size,
982    flags: DIFlags,
983    type_di_node: &'ll DIType,
984    def_id: Option<DefId>,
985) -> &'ll DIType {
986    let (file_metadata, line_number) = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers
987    {
988        file_metadata_from_def_id(cx, def_id)
989    } else {
990        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
991    };
992    create_member_type(
993        cx,
994        owner,
995        name,
996        file_metadata,
997        line_number,
998        layout,
999        offset,
1000        flags,
1001        type_di_node,
1002    )
1003}
1004
1005fn create_member_type<'ll, 'tcx>(
1006    cx: &CodegenCx<'ll, 'tcx>,
1007    owner: &'ll DIScope,
1008    name: &str,
1009    file_metadata: &'ll DIType,
1010    line_number: u32,
1011    layout: TyAndLayout<'tcx>,
1012    offset: Size,
1013    flags: DIFlags,
1014    type_di_node: &'ll DIType,
1015) -> &'ll DIType {
1016    unsafe {
1017        llvm::LLVMDIBuilderCreateMemberType(
1018            DIB(cx),
1019            owner,
1020            name.as_ptr(),
1021            name.len(),
1022            file_metadata,
1023            line_number,
1024            layout.size.bits(),
1025            layout.align.bits() as u32,
1026            offset.bits(),
1027            flags,
1028            type_di_node,
1029        )
1030    }
1031}
1032
1033/// Returns the `DIFlags` corresponding to the visibility of the item identified by `did`.
1034///
1035/// `DIFlags::Flag{Public,Protected,Private}` correspond to `DW_AT_accessibility`
1036/// (public/protected/private) aren't exactly right for Rust, but neither is `DW_AT_visibility`
1037/// (local/exported/qualified), and there's no way to set `DW_AT_visibility` in LLVM's API.
1038fn visibility_di_flags<'ll, 'tcx>(
1039    cx: &CodegenCx<'ll, 'tcx>,
1040    did: DefId,
1041    type_did: DefId,
1042) -> DIFlags {
1043    let parent_did = cx.tcx.parent(type_did);
1044    let visibility = cx.tcx.visibility(did);
1045    match visibility {
1046        Visibility::Public => DIFlags::FlagPublic,
1047        // Private fields have a restricted visibility of the module containing the type.
1048        Visibility::Restricted(did) if did.to_def_id() == parent_did => DIFlags::FlagPrivate,
1049        // `pub(crate)`/`pub(super)` visibilities are any other restricted visibility.
1050        Visibility::Restricted(..) => DIFlags::FlagProtected,
1051    }
1052}
1053
1054/// Creates the debuginfo node for a Rust struct type. Maybe be a regular struct or a tuple-struct.
1055fn build_struct_type_di_node<'ll, 'tcx>(
1056    cx: &CodegenCx<'ll, 'tcx>,
1057    unique_type_id: UniqueTypeId<'tcx>,
1058    span: Span,
1059) -> DINodeCreationResult<'ll> {
1060    let struct_type = unique_type_id.expect_ty();
1061
1062    let ty::Adt(adt_def, _) = struct_type.kind() else {
1063        bug_impl(None,
    format_args!("build_struct_type_di_node() called with non-struct-type: {0:?}",
        struct_type), Location::caller());bug!("build_struct_type_di_node() called with non-struct-type: {:?}", struct_type);
1064    };
1065    if !adt_def.is_struct() {
    ::core::panicking::panic("assertion failed: adt_def.is_struct()")
};assert!(adt_def.is_struct());
1066    let containing_scope = get_namespace_for_item(cx, adt_def.did());
1067    let struct_type_and_layout = cx.spanned_layout_of(struct_type, span);
1068    let variant_def = adt_def.non_enum_variant();
1069    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1070        Some(file_metadata_from_def_id(cx, Some(adt_def.did())))
1071    } else {
1072        None
1073    };
1074    let name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1075
1076    if struct_type.is_scalable_vector() {
1077        let parts = struct_type.scalable_vector_parts(cx.tcx).unwrap();
1078        return build_scalable_vector_di_node(
1079            cx,
1080            unique_type_id,
1081            name,
1082            *adt_def,
1083            parts,
1084            struct_type_and_layout.layout,
1085            def_location,
1086            containing_scope,
1087        );
1088    }
1089
1090    type_map::build_type_with_children(
1091        cx,
1092        type_map::stub(
1093            cx,
1094            Stub::Struct,
1095            unique_type_id,
1096            &name,
1097            def_location,
1098            size_and_align_of(struct_type_and_layout),
1099            Some(containing_scope),
1100            visibility_di_flags(cx, adt_def.did(), adt_def.did()),
1101        ),
1102        // Fields:
1103        |cx, owner| {
1104            variant_def
1105                .fields
1106                .iter()
1107                .enumerate()
1108                .map(|(i, f)| {
1109                    let field_name = if variant_def.ctor_kind() == Some(CtorKind::Fn) {
1110                        // This is a tuple struct
1111                        tuple_field_name(i)
1112                    } else {
1113                        // This is struct with named fields
1114                        Cow::Borrowed(f.name.as_str())
1115                    };
1116                    let field_layout = struct_type_and_layout.field(cx, i);
1117                    let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1118                        Some(f.did)
1119                    } else {
1120                        None
1121                    };
1122                    build_field_di_node(
1123                        cx,
1124                        owner,
1125                        &field_name[..],
1126                        field_layout,
1127                        struct_type_and_layout.fields.offset(i),
1128                        visibility_di_flags(cx, f.did, adt_def.did()),
1129                        type_di_node(cx, field_layout.ty),
1130                        def_id,
1131                    )
1132                })
1133                .collect()
1134        },
1135        |cx| build_generic_type_param_di_nodes(cx, struct_type),
1136    )
1137}
1138
1139/// Generate debuginfo for a `#[rustc_scalable_vector]` type.
1140///
1141/// Debuginfo for a scalable vector uses a derived type based on a composite type. The composite
1142/// type has the  `DIFlagVector` flag set and is based on the element type of the scalable vector.
1143/// The composite type has a subrange from 0 to an expression that calculates the number of
1144/// elements in the vector.
1145///
1146/// ```text,ignore
1147/// !1 = !DIDerivedType(tag: DW_TAG_typedef, name: "svint16_t", ..., baseType: !2, ...)
1148/// !2 = !DICompositeType(tag: DW_TAG_array_type, baseType: !3, ..., flags: DIFlagVector, elements: !4)
1149/// !3 = !DIBasicType(name: "i16", size: 16, encoding: DW_ATE_signed)
1150/// !4 = !{!5}
1151/// !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))
1152/// ```
1153///
1154/// See the `CodegenType::CreateType(const BuiltinType *BT)` implementation in Clang for how this
1155/// is generated for C and C++.
1156fn build_scalable_vector_di_node<'ll, 'tcx>(
1157    cx: &CodegenCx<'ll, 'tcx>,
1158    unique_type_id: UniqueTypeId<'tcx>,
1159    name: String,
1160    adt_def: AdtDef<'tcx>,
1161    (element_count, element_ty, number_of_vectors): (u16, Ty<'tcx>, NumScalableVectors),
1162    layout: Layout<'tcx>,
1163    def_location: Option<DefinitionLocation<'ll>>,
1164    containing_scope: &'ll DIScope,
1165) -> DINodeCreationResult<'ll> {
1166    use dwarf_const::{DW_OP_bregx, DW_OP_constu, DW_OP_minus, DW_OP_mul};
1167    if !adt_def.repr().scalable() {
    ::core::panicking::panic("assertion failed: adt_def.repr().scalable()")
};assert!(adt_def.repr().scalable());
1168    // This logic is specific to AArch64 for the moment, but can be extended for other architectures
1169    // later.
1170    {
    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);
1171
1172    let (file_metadata, line_number) = if let Some(def_location) = def_location {
1173        (def_location.0, def_location.1)
1174    } else {
1175        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1176    };
1177
1178    let (bitstride, element_di_node) = if element_ty.is_bool() {
1179        (Some(llvm::LLVMValueAsMetadata(cx.const_i64(1))), type_di_node(cx, cx.tcx.types.u8))
1180    } else {
1181        (None, type_di_node(cx, element_ty))
1182    };
1183
1184    let number_of_elements: u64 = (element_count as u64) * (number_of_vectors.0 as u64);
1185    let number_of_elements_per_vg = number_of_elements / 2;
1186    let mut expr = smallvec::SmallVec::<[u64; 9]>::new();
1187    // `($number_of_elements_per_vector_granule * (value_of_register(AArch64::VG) + 0)) - 1`
1188    expr.push(DW_OP_constu); // Push a constant onto the stack
1189    expr.push(number_of_elements_per_vg);
1190    expr.push(DW_OP_bregx); // Push the value of a register + offset on to the stack
1191    expr.push(/* AArch64::VG */ 46u64);
1192    expr.push(0u64);
1193    expr.push(DW_OP_mul); // Multiply top two values on stack
1194    expr.push(DW_OP_constu); // Push a constant onto the stack
1195    expr.push(1u64);
1196    expr.push(DW_OP_minus); // Subtract top two values on stack
1197
1198    let di_builder = DIB(cx);
1199    let metadata = unsafe {
1200        let upper = llvm::LLVMDIBuilderCreateExpression(di_builder, expr.as_ptr(), expr.len());
1201        let subrange = llvm::LLVMRustDIGetOrCreateSubrange(
1202            di_builder,
1203            /* CountNode */ None,
1204            llvm::LLVMValueAsMetadata(cx.const_i64(0)),
1205            upper,
1206            /* Stride */ None,
1207        );
1208        let subscripts = create_DIArray(di_builder, &[Some(subrange)]);
1209        let vector_ty = llvm::LLVMRustDICreateVectorType(
1210            di_builder,
1211            /* Size */ 0,
1212            layout.align.bits() as u32,
1213            element_di_node,
1214            subscripts,
1215            bitstride,
1216        );
1217        llvm::LLVMDIBuilderCreateTypedef(
1218            di_builder,
1219            vector_ty,
1220            name.as_ptr(),
1221            name.len(),
1222            file_metadata,
1223            line_number,
1224            Some(containing_scope),
1225            layout.align.bits() as u32,
1226        )
1227    };
1228
1229    debug_context(cx).type_map.insert(unique_type_id, metadata);
1230    DINodeCreationResult { di_node: metadata, already_stored_in_typemap: true }
1231}
1232
1233//=-----------------------------------------------------------------------------
1234// Tuples
1235//=-----------------------------------------------------------------------------
1236
1237/// Builds the DW_TAG_member debuginfo nodes for the upvars of a closure or coroutine.
1238/// For a coroutine, this will handle upvars shared by all states.
1239fn build_upvar_field_di_nodes<'ll, 'tcx>(
1240    cx: &CodegenCx<'ll, 'tcx>,
1241    closure_or_coroutine_ty: Ty<'tcx>,
1242    closure_or_coroutine_di_node: &'ll DIType,
1243) -> SmallVec<&'ll DIType> {
1244    let (&def_id, up_var_tys) = match closure_or_coroutine_ty.kind() {
1245        ty::Coroutine(def_id, args) => (def_id, args.as_coroutine().upvar_tys()),
1246        ty::Closure(def_id, args) => (def_id, args.as_closure().upvar_tys()),
1247        ty::CoroutineClosure(def_id, args) => (def_id, args.as_coroutine_closure().upvar_tys()),
1248        _ => {
1249            bug_impl(None,
    format_args!("build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {0:?}",
        closure_or_coroutine_ty), Location::caller())bug!(
1250                "build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {:?}",
1251                closure_or_coroutine_ty
1252            )
1253        }
1254    };
1255
1256    for ty in up_var_tys.iter() {
1257        cx.tcx.assert_fully_normalized(cx.typing_env(), ty);
1258    }
1259
1260    let capture_names = cx.tcx.closure_saved_names_of_captured_variables(def_id);
1261    let layout = cx.layout_of(closure_or_coroutine_ty);
1262
1263    up_var_tys
1264        .into_iter()
1265        .zip(capture_names.iter())
1266        .enumerate()
1267        .map(|(index, (up_var_ty, capture_name))| {
1268            build_field_di_node(
1269                cx,
1270                closure_or_coroutine_di_node,
1271                capture_name.as_str(),
1272                cx.layout_of(up_var_ty),
1273                layout.fields.offset(index),
1274                DIFlags::FlagZero,
1275                type_di_node(cx, up_var_ty),
1276                None,
1277            )
1278        })
1279        .collect()
1280}
1281
1282/// Builds the DW_TAG_structure_type debuginfo node for a Rust tuple type.
1283fn build_tuple_type_di_node<'ll, 'tcx>(
1284    cx: &CodegenCx<'ll, 'tcx>,
1285    unique_type_id: UniqueTypeId<'tcx>,
1286) -> DINodeCreationResult<'ll> {
1287    let tuple_type = unique_type_id.expect_ty();
1288    let &ty::Tuple(component_types) = tuple_type.kind() else {
1289        bug_impl(None,
    format_args!("build_tuple_type_di_node() called with non-tuple-type: {0:?}",
        tuple_type), Location::caller())bug!("build_tuple_type_di_node() called with non-tuple-type: {:?}", tuple_type)
1290    };
1291
1292    let tuple_type_and_layout = cx.layout_of(tuple_type);
1293    let type_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1294
1295    type_map::build_type_with_children(
1296        cx,
1297        type_map::stub(
1298            cx,
1299            Stub::Struct,
1300            unique_type_id,
1301            &type_name,
1302            None,
1303            size_and_align_of(tuple_type_and_layout),
1304            NO_SCOPE_METADATA,
1305            DIFlags::FlagZero,
1306        ),
1307        // Fields:
1308        |cx, tuple_di_node| {
1309            component_types
1310                .into_iter()
1311                .enumerate()
1312                .map(|(index, component_type)| {
1313                    build_field_di_node(
1314                        cx,
1315                        tuple_di_node,
1316                        &tuple_field_name(index),
1317                        cx.layout_of(component_type),
1318                        tuple_type_and_layout.fields.offset(index),
1319                        DIFlags::FlagZero,
1320                        type_di_node(cx, component_type),
1321                        None,
1322                    )
1323                })
1324                .collect()
1325        },
1326        NO_GENERICS,
1327    )
1328}
1329
1330/// Builds the debuginfo node for a closure environment.
1331fn build_closure_env_di_node<'ll, 'tcx>(
1332    cx: &CodegenCx<'ll, 'tcx>,
1333    unique_type_id: UniqueTypeId<'tcx>,
1334) -> DINodeCreationResult<'ll> {
1335    let closure_env_type = unique_type_id.expect_ty();
1336    let &(ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _)) = closure_env_type.kind()
1337    else {
1338        bug_impl(None,
    format_args!("build_closure_env_di_node() called with non-closure-type: {0:?}",
        closure_env_type), Location::caller())bug!("build_closure_env_di_node() called with non-closure-type: {:?}", closure_env_type)
1339    };
1340    let containing_scope = get_namespace_for_item(cx, def_id);
1341    let type_name = compute_debuginfo_type_name(cx.tcx, closure_env_type, false);
1342
1343    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1344        Some(file_metadata_from_def_id(cx, Some(def_id)))
1345    } else {
1346        None
1347    };
1348
1349    type_map::build_type_with_children(
1350        cx,
1351        type_map::stub(
1352            cx,
1353            Stub::Struct,
1354            unique_type_id,
1355            &type_name,
1356            def_location,
1357            cx.size_and_align_of(closure_env_type),
1358            Some(containing_scope),
1359            DIFlags::FlagZero,
1360        ),
1361        // Fields:
1362        |cx, owner| build_upvar_field_di_nodes(cx, closure_env_type, owner),
1363        NO_GENERICS,
1364    )
1365}
1366
1367/// Build the debuginfo node for a Rust `union` type.
1368fn build_union_type_di_node<'ll, 'tcx>(
1369    cx: &CodegenCx<'ll, 'tcx>,
1370    unique_type_id: UniqueTypeId<'tcx>,
1371    span: Span,
1372) -> DINodeCreationResult<'ll> {
1373    let union_type = unique_type_id.expect_ty();
1374    let (union_def_id, variant_def) = match union_type.kind() {
1375        ty::Adt(def, _) => (def.did(), def.non_enum_variant()),
1376        _ => bug_impl(None, format_args!("build_union_type_di_node on a non-ADT"),
    Location::caller())bug!("build_union_type_di_node on a non-ADT"),
1377    };
1378    let containing_scope = get_namespace_for_item(cx, union_def_id);
1379    let union_ty_and_layout = cx.spanned_layout_of(union_type, span);
1380    let type_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1381    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1382        Some(file_metadata_from_def_id(cx, Some(union_def_id)))
1383    } else {
1384        None
1385    };
1386
1387    type_map::build_type_with_children(
1388        cx,
1389        type_map::stub(
1390            cx,
1391            Stub::Union,
1392            unique_type_id,
1393            &type_name,
1394            def_location,
1395            size_and_align_of(union_ty_and_layout),
1396            Some(containing_scope),
1397            DIFlags::FlagZero,
1398        ),
1399        // Fields:
1400        |cx, owner| {
1401            variant_def
1402                .fields
1403                .iter()
1404                .enumerate()
1405                .map(|(i, f)| {
1406                    let field_layout = union_ty_and_layout.field(cx, i);
1407                    let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1408                        Some(f.did)
1409                    } else {
1410                        None
1411                    };
1412                    build_field_di_node(
1413                        cx,
1414                        owner,
1415                        f.name.as_str(),
1416                        field_layout,
1417                        Size::ZERO,
1418                        DIFlags::FlagZero,
1419                        type_di_node(cx, field_layout.ty),
1420                        def_id,
1421                    )
1422                })
1423                .collect()
1424        },
1425        // Generics:
1426        |cx| build_generic_type_param_di_nodes(cx, union_type),
1427    )
1428}
1429
1430/// Computes the type parameters for a type, if any, for the given metadata.
1431fn build_generic_type_param_di_nodes<'ll, 'tcx>(
1432    cx: &CodegenCx<'ll, 'tcx>,
1433    ty: Ty<'tcx>,
1434) -> SmallVec<Option<&'ll DIType>> {
1435    if let ty::Adt(def, args) = *ty.kind() {
1436        // FIXME: also do consts?
1437        if args.types().next().is_some() {
1438            let generics = cx.tcx.generics_of(def.did());
1439            let names = get_parameter_names(cx, generics);
1440            let template_params: SmallVec<_> = iter::zip(args, names)
1441                .filter_map(|(kind, name)| {
1442                    kind.as_type().map(|ty| {
1443                        let actual_type = cx
1444                            .tcx
1445                            .normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty));
1446                        let actual_type_di_node = type_di_node(cx, actual_type);
1447                        Some(cx.create_template_type_parameter(name.as_str(), actual_type_di_node))
1448                    })
1449                })
1450                .collect();
1451
1452            return template_params;
1453        }
1454    }
1455
1456    return ::smallvec::SmallVec::new()smallvec![];
1457
1458    fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
1459        let mut names = generics
1460            .parent
1461            .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
1462        names.extend(generics.own_params.iter().map(|param| param.name));
1463        names
1464    }
1465}
1466
1467/// Creates debug information for the given global variable.
1468///
1469/// Adds the created debuginfo nodes directly to the crate's IR.
1470pub(crate) fn build_global_var_di_node<'ll>(
1471    cx: &CodegenCx<'ll, '_>,
1472    def_id: DefId,
1473    global: &'ll Value,
1474) {
1475    if cx.dbg_cx.is_none() {
1476        return;
1477    }
1478
1479    // Only create type information if full debuginfo is enabled
1480    if cx.sess().opts.debuginfo != DebugInfo::Full {
1481        return;
1482    }
1483
1484    let tcx = cx.tcx;
1485
1486    // We may want to remove the namespace scope if we're in an extern block (see
1487    // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
1488    let var_scope = get_namespace_for_item(cx, def_id);
1489    let (file_metadata, line_number) = file_metadata_from_def_id(cx, Some(def_id));
1490
1491    let is_local_to_unit = is_node_local_to_unit(cx, def_id);
1492
1493    let DefKind::Static { nested, .. } = cx.tcx.def_kind(def_id) else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
1494    if nested {
1495        return;
1496    }
1497    let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, cx.typing_env());
1498    let type_di_node = type_di_node(cx, variable_type);
1499    let var_name = tcx.item_name(def_id);
1500    let var_name = var_name.as_str();
1501    let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
1502    // When empty, linkage_name field is omitted,
1503    // which is what we want for no_mangle statics
1504    let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
1505
1506    let global_align = cx.align_of(variable_type);
1507
1508    DIB(cx).create_static_variable(
1509        Some(var_scope),
1510        var_name,
1511        linkage_name,
1512        file_metadata,
1513        line_number,
1514        type_di_node,
1515        is_local_to_unit,
1516        global, // (value)
1517        None,   // (decl)
1518        Some(global_align),
1519    );
1520}
1521
1522/// Generates LLVM debuginfo for a vtable.
1523///
1524/// The vtable type looks like a struct with a field for each function pointer and super-trait
1525/// pointer it contains (plus the `size` and `align` fields).
1526///
1527/// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
1528/// the name of the method they implement. This can be implemented in the future once there
1529/// is a proper disambiguation scheme for dealing with methods from different traits that have
1530/// the same name.
1531fn build_vtable_type_di_node<'ll, 'tcx>(
1532    cx: &CodegenCx<'ll, 'tcx>,
1533    ty: Ty<'tcx>,
1534    poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1535) -> &'ll DIType {
1536    let tcx = cx.tcx;
1537
1538    let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
1539        let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
1540        let trait_ref = tcx.erase_and_anonymize_regions(trait_ref);
1541
1542        tcx.vtable_entries(trait_ref)
1543    } else {
1544        TyCtxt::COMMON_VTABLE_ENTRIES
1545    };
1546
1547    // All function pointers are described as opaque pointers. This could be improved in the future
1548    // by describing them as actual function pointers.
1549    let void_pointer_ty = Ty::new_imm_ptr(tcx, tcx.types.unit);
1550    let void_pointer_type_di_node = type_di_node(cx, void_pointer_ty);
1551    let usize_di_node = type_di_node(cx, tcx.types.usize);
1552    let pointer_layout = cx.layout_of(void_pointer_ty);
1553    let pointer_size = pointer_layout.size;
1554    let pointer_align = pointer_layout.align.abi;
1555    // If `usize` is not pointer-sized and -aligned then the size and alignment computations
1556    // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
1557    // platforms.
1558    {
    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));
1559
1560    let vtable_type_name =
1561        compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
1562    let unique_type_id = UniqueTypeId::for_vtable_ty(tcx, ty, poly_trait_ref);
1563    let size = pointer_size * vtable_entries.len() as u64;
1564
1565    // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
1566    // the vtable to the type it is for.
1567    let vtable_holder = type_di_node(cx, ty);
1568
1569    build_type_with_children(
1570        cx,
1571        type_map::stub(
1572            cx,
1573            Stub::VTableTy { vtable_holder },
1574            unique_type_id,
1575            &vtable_type_name,
1576            None,
1577            (size, pointer_align),
1578            NO_SCOPE_METADATA,
1579            DIFlags::FlagArtificial,
1580        ),
1581        |cx, vtable_type_di_node| {
1582            vtable_entries
1583                .iter()
1584                .enumerate()
1585                .filter_map(|(index, vtable_entry)| {
1586                    let (field_name, field_type_di_node) = match vtable_entry {
1587                        ty::VtblEntry::MetadataDropInPlace => {
1588                            ("drop_in_place".to_string(), void_pointer_type_di_node)
1589                        }
1590                        ty::VtblEntry::Method(_) => {
1591                            // Note: This code does not try to give a proper name to each method
1592                            //       because their might be multiple methods with the same name
1593                            //       (coming from different traits).
1594                            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__method{0}", index))
    })format!("__method{index}"), void_pointer_type_di_node)
1595                        }
1596                        ty::VtblEntry::TraitVPtr(_) => {
1597                            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__super_trait_ptr{0}", index))
    })format!("__super_trait_ptr{index}"), void_pointer_type_di_node)
1598                        }
1599                        ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node),
1600                        ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node),
1601                        ty::VtblEntry::Vacant => return None,
1602                    };
1603
1604                    let field_offset = pointer_size * index as u64;
1605
1606                    Some(build_field_di_node(
1607                        cx,
1608                        vtable_type_di_node,
1609                        &field_name,
1610                        pointer_layout,
1611                        field_offset,
1612                        DIFlags::FlagZero,
1613                        field_type_di_node,
1614                        None,
1615                    ))
1616                })
1617                .collect()
1618        },
1619        NO_GENERICS,
1620    )
1621    .di_node
1622}
1623
1624/// Creates the debuginfo node for `unsafe<'a> T` binder types.
1625///
1626/// We treat an unsafe binder like a struct with a single field named `inner`
1627/// rather than delegating to the inner type's DI node directly. This way the
1628/// debugger shows the binder's own type name, and the wrapped value is still
1629/// accessible through the `inner` field.
1630fn build_unsafe_binder_type_di_node<'ll, 'tcx>(
1631    cx: &CodegenCx<'ll, 'tcx>,
1632    binder_type: Ty<'tcx>,
1633    unique_type_id: UniqueTypeId<'tcx>,
1634) -> DINodeCreationResult<'ll> {
1635    let ty::UnsafeBinder(inner) = binder_type.kind() else {
1636        bug_impl(None,
    format_args!("Only ty::UnsafeBinder is valid for build_unsafe_binder_type_di_node. Found {0:?} instead.",
        binder_type), Location::caller())bug!(
1637            "Only ty::UnsafeBinder is valid for build_unsafe_binder_type_di_node. Found {:?} instead.",
1638            binder_type
1639        )
1640    };
1641    let inner_type = cx.tcx.instantiate_bound_regions_with_erased((*inner).into());
1642    let inner_type_di_node = type_di_node(cx, inner_type);
1643
1644    let type_name = compute_debuginfo_type_name(cx.tcx, binder_type, true);
1645    type_map::build_type_with_children(
1646        cx,
1647        type_map::stub(
1648            cx,
1649            Stub::Struct,
1650            unique_type_id,
1651            &type_name,
1652            None,
1653            cx.size_and_align_of(binder_type),
1654            NO_SCOPE_METADATA,
1655            DIFlags::FlagZero,
1656        ),
1657        |cx, unsafe_binder_type_di_node| {
1658            let inner_layout = cx.layout_of(inner_type);
1659            {
    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(
1660                cx,
1661                unsafe_binder_type_di_node,
1662                "inner",
1663                inner_layout,
1664                Size::ZERO,
1665                DIFlags::FlagZero,
1666                inner_type_di_node,
1667                None,
1668            )]
1669        },
1670        NO_GENERICS,
1671    )
1672}
1673
1674/// Get the global variable for the vtable.
1675///
1676/// When using global variables, we may have created an addrspacecast to get a pointer to the
1677/// default address space if global variables are created in a different address space.
1678/// For modifying the vtable, we need the real global variable. This function accepts either a
1679/// global variable (which is simply returned), or an addrspacecast constant expression.
1680/// If the given value is an addrspacecast, the cast is removed and the global variable behind
1681/// the cast is returned.
1682fn find_vtable_behind_cast<'ll>(vtable: &'ll Value) -> &'ll Value {
1683    // The vtable is a global variable, which may be behind an addrspacecast.
1684    unsafe {
1685        if let Some(c) = llvm::LLVMIsAConstantExpr(vtable) {
1686            if llvm::LLVMGetConstOpcode(c) == llvm::Opcode::AddrSpaceCast {
1687                return llvm::LLVMGetOperand(c, 0).unwrap();
1688            }
1689        }
1690    }
1691    vtable
1692}
1693
1694pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>(
1695    cx: &CodegenCx<'ll, 'tcx>,
1696    ty: Ty<'tcx>,
1697    trait_ref: Option<ExistentialTraitRef<'tcx>>,
1698    vtable: &'ll Value,
1699) {
1700    // FIXME(flip1995): The virtual function elimination optimization only works with full LTO in
1701    // LLVM at the moment.
1702    if !cx.sess().opts.unstable_opts.virtual_function_elimination || cx.sess().lto() != Lto::Fat {
1703        return;
1704    }
1705
1706    enum VCallVisibility {
1707        Public = 0,
1708        LinkageUnit = 1,
1709        TranslationUnit = 2,
1710    }
1711
1712    let Some(trait_ref) = trait_ref else { return };
1713
1714    // Unwrap potential addrspacecast
1715    let vtable = find_vtable_behind_cast(vtable);
1716    let trait_ref_self = trait_ref.with_self_ty(cx.tcx, ty);
1717    let trait_def_id = trait_ref_self.def_id;
1718    let trait_vis = cx.tcx.visibility(trait_def_id);
1719
1720    let cgus = cx.sess().codegen_units().as_usize();
1721    let single_cgu = cgus == 1;
1722
1723    let lto = cx.sess().lto();
1724
1725    // Since LLVM requires full LTO for the virtual function elimination optimization to apply,
1726    // only the `Lto::Fat` cases are relevant currently.
1727    let vcall_visibility = match (lto, trait_vis, single_cgu) {
1728        // If there is not LTO and the visibility in public, we have to assume that the vtable can
1729        // be seen from anywhere. With multiple CGUs, the vtable is quasi-public.
1730        (Lto::No | Lto::ThinLocal, Visibility::Public, _)
1731        | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public,
1732        // With LTO and a quasi-public visibility, the usages of the functions of the vtable are
1733        // all known by the `LinkageUnit`.
1734        // FIXME: LLVM only supports this optimization for `Lto::Fat` currently. Once it also
1735        // supports `Lto::Thin` the `VCallVisibility` may have to be adjusted for those.
1736        (Lto::Fat | Lto::Thin, Visibility::Public, _)
1737        | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => {
1738            VCallVisibility::LinkageUnit
1739        }
1740        // If there is only one CGU, private vtables can only be seen by that CGU/translation unit
1741        // and therefore we know of all usages of functions in the vtable.
1742        (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit,
1743    };
1744
1745    let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref);
1746    let typeid = cx.create_metadata(trait_ref_typeid.as_bytes());
1747
1748    let type_ = [llvm::LLVMValueAsMetadata(cx.const_usize(0)), typeid];
1749    cx.global_add_metadata_node(vtable, llvm::MD_type, &type_);
1750
1751    let vcall_visibility = [llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64))];
1752    cx.global_set_metadata_node(vtable, llvm::MD_vcall_visibility, &vcall_visibility);
1753}
1754
1755/// Creates debug information for the given vtable, which is for the
1756/// given type.
1757///
1758/// Adds the created metadata nodes directly to the crate's IR.
1759pub(crate) fn create_vtable_di_node<'ll, 'tcx>(
1760    cx: &CodegenCx<'ll, 'tcx>,
1761    ty: Ty<'tcx>,
1762    poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1763    vtable: &'ll Value,
1764) {
1765    if cx.dbg_cx.is_none() {
1766        return;
1767    }
1768
1769    // Only create type information if full debuginfo is enabled
1770    if cx.sess().opts.debuginfo != DebugInfo::Full {
1771        return;
1772    }
1773
1774    // Unwrap potential addrspacecast
1775    let vtable = find_vtable_behind_cast(vtable);
1776
1777    // When full debuginfo is enabled, we want to try and prevent vtables from being
1778    // merged. Otherwise debuggers will have a hard time mapping from dyn pointer
1779    // to concrete type.
1780    llvm::set_unnamed_address(vtable, llvm::UnnamedAddr::No);
1781
1782    let vtable_name =
1783        compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
1784    let vtable_type_di_node = build_vtable_type_di_node(cx, ty, poly_trait_ref);
1785
1786    DIB(cx).create_static_variable(
1787        NO_SCOPE_METADATA,
1788        &vtable_name,
1789        "", // (linkage_name)
1790        unknown_file_metadata(cx),
1791        UNKNOWN_LINE_NUMBER,
1792        vtable_type_di_node,
1793        true,   // (is_local_to_unit)
1794        vtable, // (value)
1795        None,   // (decl)
1796        None::<Align>,
1797    );
1798}
1799
1800/// Creates an "extension" of an existing `DIScope` into another file.
1801pub(crate) fn extend_scope_to_file<'ll>(
1802    cx: &CodegenCx<'ll, '_>,
1803    scope_metadata: &'ll DIScope,
1804    file: &SourceFile,
1805) -> &'ll DILexicalBlock {
1806    let file_metadata = file_metadata(cx, file);
1807    unsafe {
1808        llvm::LLVMDIBuilderCreateLexicalBlockFile(
1809            DIB(cx),
1810            scope_metadata,
1811            file_metadata,
1812            /* Discriminator (default) */ 0u32,
1813        )
1814    }
1815}
1816
1817fn tuple_field_name(field_index: usize) -> Cow<'static, str> {
1818    const TUPLE_FIELD_NAMES: [&'static str; 16] = [
1819        "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11",
1820        "__12", "__13", "__14", "__15",
1821    ];
1822    TUPLE_FIELD_NAMES
1823        .get(field_index)
1824        .map(|s| Cow::from(*s))
1825        .unwrap_or_else(|| Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__{0}", field_index))
    })format!("__{field_index}")))
1826}
1827
1828pub(crate) type DefinitionLocation<'ll> = (&'ll DIFile, c_uint);
1829
1830pub(crate) fn file_metadata_from_def_id<'ll>(
1831    cx: &CodegenCx<'ll, '_>,
1832    def_id: Option<DefId>,
1833) -> DefinitionLocation<'ll> {
1834    if let Some(def_id) = def_id
1835        && let span = hygiene::walk_chain_collapsed(cx.tcx.def_span(def_id), DUMMY_SP)
1836        && !span.is_dummy()
1837    {
1838        let loc = cx.lookup_debug_loc(span.lo());
1839        (file_metadata(cx, &loc.file), loc.line)
1840    } else {
1841        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1842    }
1843}