rustc_codegen_llvm/debuginfo/
metadata.rs

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