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