1 use self::MemberDescriptionFactory::*;
2 use self::RecursiveTypeDescription::*;
4 use super::namespace::mangled_name_of_instance;
5 use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
7 create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
9 use super::CrateDebugContext;
12 use crate::common::CodegenCx;
13 use crate::debuginfo::utils::fat_pointer_kind;
14 use crate::debuginfo::utils::FatPtrKind;
16 use crate::llvm::debuginfo::{
17 DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
20 use crate::value::Value;
23 use rustc_codegen_ssa::debuginfo::type_names::cpp_like_debuginfo;
24 use rustc_codegen_ssa::debuginfo::type_names::VTableNameKind;
25 use rustc_codegen_ssa::traits::*;
26 use rustc_data_structures::fx::FxHashMap;
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_index::vec::{Idx, IndexVec};
31 use rustc_middle::bug;
32 use rustc_middle::mir::{self, GeneratorLayout};
33 use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout};
34 use rustc_middle::ty::subst::GenericArgKind;
35 use rustc_middle::ty::{
36 self, AdtKind, GeneratorSubsts, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES,
38 use rustc_session::config::{self, DebugInfo};
39 use rustc_span::symbol::Symbol;
40 use rustc_span::FileNameDisplayPreference;
41 use rustc_span::{self, SourceFile, SourceFileHash};
42 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, TagEncoding};
43 use rustc_target::abi::{Int, Pointer, F32, F64};
44 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
45 use smallvec::SmallVec;
48 use libc::{c_longlong, c_uint};
49 use std::cell::RefCell;
50 use std::collections::hash_map::Entry;
51 use std::fmt::{self, Write};
52 use std::hash::{Hash, Hasher};
54 use std::path::{Path, PathBuf};
57 impl PartialEq for llvm::Metadata {
58 fn eq(&self, other: &Self) -> bool {
63 impl Eq for llvm::Metadata {}
65 impl Hash for llvm::Metadata {
66 fn hash<H: Hasher>(&self, hasher: &mut H) {
67 (self as *const Self).hash(hasher);
71 impl fmt::Debug for llvm::Metadata {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 (self as *const Self).fmt(f)
78 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
79 const DW_LANG_RUST: c_uint = 0x1c;
80 #[allow(non_upper_case_globals)]
81 const DW_ATE_boolean: c_uint = 0x02;
82 #[allow(non_upper_case_globals)]
83 const DW_ATE_float: c_uint = 0x04;
84 #[allow(non_upper_case_globals)]
85 const DW_ATE_signed: c_uint = 0x05;
86 #[allow(non_upper_case_globals)]
87 const DW_ATE_unsigned: c_uint = 0x07;
88 #[allow(non_upper_case_globals)]
89 const DW_ATE_UTF: c_uint = 0x10;
91 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
92 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
94 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
97 use rustc_data_structures::{
98 fingerprint::Fingerprint,
99 stable_hasher::{HashStable, NodeIdHashingMode, StableHasher},
101 use rustc_middle::ty::{ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt};
102 use rustc_target::abi::VariantIdx;
104 // This type cannot be constructed outside of this module because
105 // it has a private field. We make use of this in order to prevent
106 // `UniqueTypeId` from being constructed directly, without asserting
107 // the preconditions.
108 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, HashStable)]
109 pub struct HiddenZst {
113 /// A unique identifier for anything that we create a debuginfo node for.
114 /// The types it contains are expected to already be normalized (which
115 /// is debug_asserted in the constructors).
117 /// Note that there are some things that only show up in debuginfo, like
118 /// the separate type descriptions for each enum variant. These get an ID
119 /// too because they have their own debuginfo node in LLVM IR.
120 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, HashStable)]
121 pub(super) enum UniqueTypeId<'tcx> {
122 /// The ID of a regular type as it shows up at the language level.
123 Ty(Ty<'tcx>, HiddenZst),
124 /// The ID for the artificial struct type describing a single enum variant.
125 Variant(Ty<'tcx>, VariantIdx, HiddenZst),
126 /// The ID for the single DW_TAG_variant_part nested inside the top-level
127 /// DW_TAG_structure_type that describes enums and generators.
128 VariantPart(Ty<'tcx>, HiddenZst),
129 /// The ID of the artificial type we create for VTables.
130 VTableTy(Ty<'tcx>, Option<PolyExistentialTraitRef<'tcx>>, HiddenZst),
133 impl<'tcx> UniqueTypeId<'tcx> {
134 pub fn for_ty(tcx: TyCtxt<'tcx>, t: Ty<'tcx>) -> Self {
135 debug_assert_eq!(t, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t));
136 UniqueTypeId::Ty(t, HiddenZst { _inaccessible: () })
139 pub fn for_enum_variant(
142 variant_idx: VariantIdx,
146 tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)
148 UniqueTypeId::Variant(enum_ty, variant_idx, HiddenZst { _inaccessible: () })
151 pub fn for_enum_variant_part(tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>) -> Self {
154 tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)
156 UniqueTypeId::VariantPart(enum_ty, HiddenZst { _inaccessible: () })
159 pub fn for_vtable_ty(
162 implemented_trait: Option<PolyExistentialTraitRef<'tcx>>,
166 tcx.normalize_erasing_regions(ParamEnv::reveal_all(), self_type)
170 tcx.normalize_erasing_regions(ParamEnv::reveal_all(), implemented_trait)
172 UniqueTypeId::VTableTy(self_type, implemented_trait, HiddenZst { _inaccessible: () })
175 /// Generates a string version of this [UniqueTypeId], which can be used as the `UniqueId`
176 /// argument of the various `LLVMRustDIBuilderCreate*Type()` methods.
178 /// Right now this takes the form of a hex-encoded opaque hash value.
179 pub fn generate_unique_id_string(&self, tcx: TyCtxt<'tcx>) -> String {
180 let mut hasher = StableHasher::new();
181 let mut hcx = tcx.create_stable_hashing_context();
182 hcx.while_hashing_spans(false, |hcx| {
183 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
184 self.hash_stable(hcx, &mut hasher);
187 hasher.finish::<Fingerprint>().to_hex()
191 use unique_type_id::*;
193 /// The `TypeMap` is where the debug context holds the type metadata nodes
194 /// created so far. The metadata nodes are indexed by `UniqueTypeId`.
196 pub struct TypeMap<'ll, 'tcx> {
197 unique_id_to_metadata: RefCell<FxHashMap<UniqueTypeId<'tcx>, &'ll DIType>>,
200 impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
201 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
202 /// fail if the mapping already exists.
203 fn register_unique_id_with_metadata(
205 unique_type_id: UniqueTypeId<'tcx>,
206 metadata: &'ll DIType,
208 if self.unique_id_to_metadata.borrow_mut().insert(unique_type_id, metadata).is_some() {
209 bug!("type metadata for unique ID '{:?}' is already in the `TypeMap`!", unique_type_id);
213 fn find_metadata_for_unique_id(
215 unique_type_id: UniqueTypeId<'tcx>,
216 ) -> Option<&'ll DIType> {
217 self.unique_id_to_metadata.borrow().get(&unique_type_id).cloned()
221 /// A description of some recursive type. It can either be already finished (as
222 /// with `FinalMetadata`) or it is not yet finished, but contains all information
223 /// needed to generate the missing parts of the description. See the
224 /// documentation section on Recursive Types at the top of this file for more
226 enum RecursiveTypeDescription<'ll, 'tcx> {
228 unfinished_type: Ty<'tcx>,
229 unique_type_id: UniqueTypeId<'tcx>,
230 metadata_stub: &'ll DICompositeType,
231 member_holding_stub: &'ll DICompositeType,
232 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
234 FinalMetadata(&'ll DICompositeType),
237 fn create_and_register_recursive_type_forward_declaration<'ll, 'tcx>(
238 cx: &CodegenCx<'ll, 'tcx>,
239 unfinished_type: Ty<'tcx>,
240 unique_type_id: UniqueTypeId<'tcx>,
241 metadata_stub: &'ll DICompositeType,
242 member_holding_stub: &'ll DICompositeType,
243 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
244 ) -> RecursiveTypeDescription<'ll, 'tcx> {
245 // Insert the stub into the `TypeMap` in order to allow for recursive references.
246 debug_context(cx).type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
253 member_description_factory,
257 impl<'ll, 'tcx> RecursiveTypeDescription<'ll, 'tcx> {
258 /// Finishes up the description of the type in question (mostly by providing
259 /// descriptions of the fields of the given type) and returns the final type
261 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
263 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
269 ref member_description_factory,
271 // Make sure that we have a forward declaration of the type in
272 // the TypeMap so that recursive references are possible. This
273 // will always be the case if the RecursiveTypeDescription has
274 // been properly created through the
275 // `create_and_register_recursive_type_forward_declaration()`
280 .find_metadata_for_unique_id(unique_type_id)
284 "Forward declaration of potentially recursive type \
285 '{:?}' was not found in TypeMap!",
291 // ... then create the member descriptions ...
292 let member_descriptions = member_description_factory.create_member_descriptions(cx);
293 let type_params = compute_type_parameters(cx, unfinished_type);
295 // ... and attach them to the stub to complete it.
296 set_members_of_composite_type(
303 MetadataCreationResult::new(metadata_stub, true)
309 /// Returns from the enclosing function if the type metadata with the given
310 /// unique ID can be found in the type map.
311 macro_rules! return_if_metadata_created_in_meantime {
312 ($cx: expr, $unique_type_id: expr) => {
313 if let Some(metadata) =
314 debug_context($cx).type_map.find_metadata_for_unique_id($unique_type_id)
316 return MetadataCreationResult::new(metadata, true);
321 /// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
322 /// For slices (that is, "arrays" of unknown size) use [slice_type_metadata].
323 fn fixed_size_array_metadata<'ll, 'tcx>(
324 cx: &CodegenCx<'ll, 'tcx>,
325 unique_type_id: UniqueTypeId<'tcx>,
326 array_type: Ty<'tcx>,
327 ) -> MetadataCreationResult<'ll> {
328 let ty::Array(element_type, len) = array_type.kind() else {
329 bug!("fixed_size_array_metadata() called with non-ty::Array type `{:?}`", array_type)
332 let element_type_metadata = type_metadata(cx, *element_type);
334 return_if_metadata_created_in_meantime!(cx, unique_type_id);
336 let (size, align) = cx.size_and_align_of(array_type);
338 let upper_bound = len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong;
341 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
343 let subscripts = create_DIArray(DIB(cx), &[subrange]);
344 let metadata = unsafe {
345 llvm::LLVMRustDIBuilderCreateArrayType(
349 element_type_metadata,
354 MetadataCreationResult::new(metadata, false)
357 /// Creates debuginfo for built-in pointer-like things:
361 /// - ty::Adt in the case it's Box
363 /// At some point we might want to remove the special handling of Box
364 /// and treat it the same as other smart pointers (like Rc, Arc, ...).
365 fn pointer_or_reference_metadata<'ll, 'tcx>(
366 cx: &CodegenCx<'ll, 'tcx>,
368 pointee_type: Ty<'tcx>,
369 unique_type_id: UniqueTypeId<'tcx>,
370 ) -> MetadataCreationResult<'ll> {
371 let pointee_type_metadata = type_metadata(cx, pointee_type);
373 return_if_metadata_created_in_meantime!(cx, unique_type_id);
375 let (thin_pointer_size, thin_pointer_align) =
376 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.types.unit));
377 let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
379 let pointer_type_metadata = match fat_pointer_kind(cx, pointee_type) {
381 // This is a thin pointer. Create a regular pointer type and give it the correct name.
383 (thin_pointer_size, thin_pointer_align),
384 cx.size_and_align_of(ptr_type),
385 "ptr_type={}, pointee_type={}",
391 llvm::LLVMRustDIBuilderCreatePointerType(
393 pointee_type_metadata,
394 thin_pointer_size.bits(),
395 thin_pointer_align.bits() as u32,
396 0, // Ignore DWARF address space.
397 ptr_type_debuginfo_name.as_ptr().cast(),
398 ptr_type_debuginfo_name.len(),
402 Some(fat_pointer_kind) => {
403 let layout = cx.layout_of(ptr_type);
405 let addr_field = layout.field(cx, abi::FAT_PTR_ADDR);
406 let extra_field = layout.field(cx, abi::FAT_PTR_EXTRA);
408 let (addr_field_name, extra_field_name) = match fat_pointer_kind {
409 FatPtrKind::Dyn => ("pointer", "vtable"),
410 FatPtrKind::Slice => ("data_ptr", "length"),
413 debug_assert_eq!(abi::FAT_PTR_ADDR, 0);
414 debug_assert_eq!(abi::FAT_PTR_EXTRA, 1);
416 // The data pointer type is a regular, thin pointer, regardless of whether this is a slice
417 // or a trait object.
418 let data_ptr_type_metadata = unsafe {
419 llvm::LLVMRustDIBuilderCreatePointerType(
421 pointee_type_metadata,
422 addr_field.size.bits(),
423 addr_field.align.abi.bits() as u32,
424 0, // Ignore DWARF address space.
430 let member_descriptions = vec![
432 name: addr_field_name.into(),
433 type_metadata: data_ptr_type_metadata,
434 offset: layout.fields.offset(abi::FAT_PTR_ADDR),
435 size: addr_field.size,
436 align: addr_field.align.abi,
437 flags: DIFlags::FlagZero,
442 name: extra_field_name.into(),
443 type_metadata: type_metadata(cx, extra_field.ty),
444 offset: layout.fields.offset(abi::FAT_PTR_EXTRA),
445 size: extra_field.size,
446 align: extra_field.align.abi,
447 flags: DIFlags::FlagZero,
453 composite_type_metadata(
456 &ptr_type_debuginfo_name,
464 MetadataCreationResult { metadata: pointer_type_metadata, already_stored_in_typemap: false }
467 fn subroutine_type_metadata<'ll, 'tcx>(
468 cx: &CodegenCx<'ll, 'tcx>,
469 unique_type_id: UniqueTypeId<'tcx>,
470 ) -> MetadataCreationResult<'ll> {
471 // It's possible to create a self-referential
472 // type in Rust by using 'impl trait':
474 // fn foo() -> impl Copy { foo }
476 // Unfortunately LLVM's API does not allow us to create recursive subroutine types.
477 // In order to work around that restriction we place a marker type in the type map,
478 // before creating the actual type. If the actual type is recursive, it will hit the
479 // marker type. So we end up with a type that looks like
481 // fn foo() -> <recursive_type>
483 // Once that is created, we replace the marker in the typemap with the actual type.
486 .unique_id_to_metadata
488 .insert(unique_type_id, recursion_marker_type(cx));
490 let UniqueTypeId::Ty(fn_ty, _) = unique_type_id else {
491 bug!("subroutine_type_metadata() called with unexpected input type: {:?}", unique_type_id)
496 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), fn_ty.fn_sig(cx.tcx));
498 let signature_metadata: SmallVec<[_; 32]> = iter::once(
500 match signature.output().kind() {
501 ty::Tuple(tys) if tys.is_empty() => {
502 // this is a "void" function
505 _ => Some(type_metadata(cx, signature.output())),
510 signature.inputs().iter().map(|&argument_type| Some(type_metadata(cx, argument_type))),
514 debug_context(cx).type_map.unique_id_to_metadata.borrow_mut().remove(&unique_type_id);
516 let fn_metadata = unsafe {
517 llvm::LLVMRustDIBuilderCreateSubroutineType(
519 create_DIArray(DIB(cx), &signature_metadata[..]),
523 // This is actually a function pointer, so wrap it in pointer DI.
524 let name = compute_debuginfo_type_name(cx.tcx, fn_ty, false);
525 let metadata = unsafe {
526 llvm::LLVMRustDIBuilderCreatePointerType(
529 cx.tcx.data_layout.pointer_size.bits(),
530 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
531 0, // Ignore DWARF address space.
532 name.as_ptr().cast(),
537 MetadataCreationResult::new(metadata, false)
540 /// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
541 /// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
542 fn dyn_type_metadata<'ll, 'tcx>(
543 cx: &CodegenCx<'ll, 'tcx>,
545 unique_type_id: UniqueTypeId<'tcx>,
547 if let ty::Dynamic(..) = dyn_type.kind() {
548 let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
549 composite_type_metadata(cx, dyn_type, &type_name, unique_type_id, vec![], NO_SCOPE_METADATA)
551 bug!("Only ty::Dynamic is valid for dyn_type_metadata(). Found {:?} instead.", dyn_type)
555 /// Create debuginfo for `[T]` and `str`. These are unsized.
557 /// NOTE: We currently emit just emit the debuginfo for the element type here
558 /// (i.e. `T` for slices and `u8` for `str`), so that we end up with
559 /// `*const T` for the `data_ptr` field of the corresponding fat-pointer
560 /// debuginfo of `&[T]`.
562 /// It would be preferable and more accurate if we emitted a DIArray of T
563 /// without an upper bound instead. That is, LLVM already supports emitting
564 /// debuginfo of arrays of unknown size. But GDB currently seems to end up
565 /// in an infinite loop when confronted with such a type.
567 /// As a side effect of the current encoding every instance of a type like
568 /// `struct Foo { unsized_field: [u8] }` will look like
569 /// `struct Foo { unsized_field: u8 }` in debuginfo. If the length of the
570 /// slice is zero, then accessing `unsized_field` in the debugger would
571 /// result in an out-of-bounds access.
572 fn slice_type_metadata<'ll, 'tcx>(
573 cx: &CodegenCx<'ll, 'tcx>,
574 slice_type: Ty<'tcx>,
575 unique_type_id: UniqueTypeId<'tcx>,
576 ) -> MetadataCreationResult<'ll> {
577 let element_type = match slice_type.kind() {
578 ty::Slice(element_type) => *element_type,
579 ty::Str => cx.tcx.types.u8,
582 "Only ty::Slice is valid for slice_type_metadata(). Found {:?} instead.",
588 let element_type_metadata = type_metadata(cx, element_type);
589 return_if_metadata_created_in_meantime!(cx, unique_type_id);
590 MetadataCreationResult { metadata: element_type_metadata, already_stored_in_typemap: false }
593 pub fn type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
594 let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t);
596 if let Some(metadata) = debug_context(cx).type_map.find_metadata_for_unique_id(unique_type_id) {
600 debug!("type_metadata: {:?}", t);
602 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
603 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
604 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
606 ty::Tuple(elements) if elements.is_empty() => {
607 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
609 ty::Array(..) => fixed_size_array_metadata(cx, unique_type_id, t),
610 ty::Slice(_) | ty::Str => slice_type_metadata(cx, t, unique_type_id),
612 MetadataCreationResult::new(dyn_type_metadata(cx, t, unique_type_id), false)
615 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
617 ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => {
618 pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id)
620 ty::Adt(def, _) if def.is_box() => {
621 pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id)
623 ty::FnDef(..) | ty::FnPtr(_) => subroutine_type_metadata(cx, unique_type_id),
624 ty::Closure(def_id, substs) => {
625 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
626 let containing_scope = get_namespace_for_item(cx, def_id);
627 prepare_tuple_metadata(cx, t, &upvar_tys, unique_type_id, Some(containing_scope))
630 ty::Generator(def_id, substs, _) => {
631 let upvar_tys: Vec<_> = substs
634 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
636 prepare_enum_metadata(cx, t, def_id, unique_type_id, upvar_tys).finalize(cx)
638 ty::Adt(def, ..) => match def.adt_kind() {
639 AdtKind::Struct => prepare_struct_metadata(cx, t, unique_type_id).finalize(cx),
640 AdtKind::Union => prepare_union_metadata(cx, t, unique_type_id).finalize(cx),
642 prepare_enum_metadata(cx, t, def.did, unique_type_id, vec![]).finalize(cx)
646 prepare_tuple_metadata(cx, t, tys, unique_type_id, NO_SCOPE_METADATA).finalize(cx)
648 // Type parameters from polymorphized functions.
649 ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
650 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
654 if already_stored_in_typemap {
655 // Make sure that we really do have a `TypeMap` entry for the unique type ID.
656 let metadata_for_uid =
657 match debug_context(cx).type_map.find_metadata_for_unique_id(unique_type_id) {
658 Some(metadata) => metadata,
661 "expected type metadata for unique \
662 type ID '{:?}' to already be in \
663 the `debuginfo::TypeMap` but it \
670 debug_assert_eq!(metadata_for_uid as *const _, metadata as *const _);
672 debug_context(cx).type_map.register_unique_id_with_metadata(unique_type_id, metadata);
679 fn recursion_marker_type<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
680 *debug_context(cx).recursion_marker_type.get_or_init(move || {
682 // The choice of type here is pretty arbitrary -
683 // anything reading the debuginfo for a recursive
684 // type is going to see *something* weird - the only
685 // question is what exactly it will see.
687 // FIXME: the name `<recur_type>` does not fit the naming scheme
690 // FIXME: it might make sense to use an actual pointer type here
691 // so that debuggers can show the address.
692 let name = "<recur_type>";
693 llvm::LLVMRustDIBuilderCreateBasicType(
695 name.as_ptr().cast(),
697 cx.tcx.data_layout.pointer_size.bits(),
704 fn hex_encode(data: &[u8]) -> String {
705 let mut hex_string = String::with_capacity(data.len() * 2);
706 for byte in data.iter() {
707 write!(&mut hex_string, "{:02x}", byte).unwrap();
712 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
713 debug!("file_metadata: file_name: {:?}", source_file.name);
715 let hash = Some(&source_file.src_hash);
716 let file_name = Some(source_file.name.prefer_remapped().to_string());
717 let directory = if source_file.is_real_file() && !source_file.is_imported() {
722 .to_string_lossy(FileNameDisplayPreference::Remapped)
726 // If the path comes from an upstream crate we assume it has been made
727 // independent of the compiler's working directory one way or another.
730 file_metadata_raw(cx, file_name, directory, hash)
733 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
734 file_metadata_raw(cx, None, None, None)
737 fn file_metadata_raw<'ll>(
738 cx: &CodegenCx<'ll, '_>,
739 file_name: Option<String>,
740 directory: Option<String>,
741 hash: Option<&SourceFileHash>,
743 let key = (file_name, directory);
745 match debug_context(cx).created_files.borrow_mut().entry(key) {
746 Entry::Occupied(o) => o.get(),
747 Entry::Vacant(v) => {
748 let (file_name, directory) = v.key();
749 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
751 let file_name = file_name.as_deref().unwrap_or("<unknown>");
752 let directory = directory.as_deref().unwrap_or("");
754 let (hash_kind, hash_value) = match hash {
756 let kind = match hash.kind {
757 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
758 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
759 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
761 (kind, hex_encode(hash.hash_bytes()))
763 None => (llvm::ChecksumKind::None, String::new()),
766 let file_metadata = unsafe {
767 llvm::LLVMRustDIBuilderCreateFile(
769 file_name.as_ptr().cast(),
771 directory.as_ptr().cast(),
774 hash_value.as_ptr().cast(),
779 v.insert(file_metadata);
785 trait MsvcBasicName {
786 fn msvc_basic_name(self) -> &'static str;
789 impl MsvcBasicName for ty::IntTy {
790 fn msvc_basic_name(self) -> &'static str {
792 ty::IntTy::Isize => "ptrdiff_t",
793 ty::IntTy::I8 => "__int8",
794 ty::IntTy::I16 => "__int16",
795 ty::IntTy::I32 => "__int32",
796 ty::IntTy::I64 => "__int64",
797 ty::IntTy::I128 => "__int128",
802 impl MsvcBasicName for ty::UintTy {
803 fn msvc_basic_name(self) -> &'static str {
805 ty::UintTy::Usize => "size_t",
806 ty::UintTy::U8 => "unsigned __int8",
807 ty::UintTy::U16 => "unsigned __int16",
808 ty::UintTy::U32 => "unsigned __int32",
809 ty::UintTy::U64 => "unsigned __int64",
810 ty::UintTy::U128 => "unsigned __int128",
815 impl MsvcBasicName for ty::FloatTy {
816 fn msvc_basic_name(self) -> &'static str {
818 ty::FloatTy::F32 => "float",
819 ty::FloatTy::F64 => "double",
824 fn basic_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
825 debug!("basic_type_metadata: {:?}", t);
827 // When targeting MSVC, emit MSVC style type names for compatibility with
828 // .natvis visualizers (and perhaps other existing native debuggers?)
829 let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
831 let (name, encoding) = match t.kind() {
832 ty::Never => ("!", DW_ATE_unsigned),
833 ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
834 ty::Bool => ("bool", DW_ATE_boolean),
835 ty::Char => ("char", DW_ATE_UTF),
836 ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
837 ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
838 ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
839 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
840 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
841 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
842 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
845 let ty_metadata = unsafe {
846 llvm::LLVMRustDIBuilderCreateBasicType(
848 name.as_ptr().cast(),
850 cx.size_of(t).bits(),
855 if !cpp_like_debuginfo {
859 let typedef_name = match t.kind() {
860 ty::Int(int_ty) => int_ty.name_str(),
861 ty::Uint(uint_ty) => uint_ty.name_str(),
862 ty::Float(float_ty) => float_ty.name_str(),
863 _ => return ty_metadata,
866 let typedef_metadata = unsafe {
867 llvm::LLVMRustDIBuilderCreateTypedef(
870 typedef_name.as_ptr().cast(),
872 unknown_file_metadata(cx),
881 fn foreign_type_metadata<'ll, 'tcx>(
882 cx: &CodegenCx<'ll, 'tcx>,
884 unique_type_id: UniqueTypeId<'tcx>,
886 debug!("foreign_type_metadata: {:?}", t);
888 let name = compute_debuginfo_type_name(cx.tcx, t, false);
889 let (size, align) = cx.size_and_align_of(t);
902 fn param_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
903 debug!("param_type_metadata: {:?}", t);
904 let name = format!("{:?}", t);
906 llvm::LLVMRustDIBuilderCreateBasicType(
908 name.as_ptr().cast(),
916 pub fn compile_unit_metadata<'ll, 'tcx>(
918 codegen_unit_name: &str,
919 debug_context: &CrateDebugContext<'ll, 'tcx>,
920 ) -> &'ll DIDescriptor {
921 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
922 Some(ref path) => path.clone(),
923 None => PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()),
926 // To avoid breaking split DWARF, we need to ensure that each codegen unit
927 // has a unique `DW_AT_name`. This is because there's a remote chance that
928 // different codegen units for the same module will have entirely
929 // identical DWARF entries for the purpose of the DWO ID, which would
930 // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
931 // specification. LLVM uses the algorithm specified in section 7.32 "Type
932 // Signature Computation" to compute the DWO ID, which does not include
933 // any fields that would distinguish compilation units. So we must embed
934 // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
936 // Additionally, the OSX linker has an idiosyncrasy where it will ignore
937 // some debuginfo if multiple object files with the same `DW_AT_name` are
940 // As a workaround for these two issues, we generate unique names for each
941 // object file. Those do not correspond to an actual source file but that
943 name_in_debuginfo.push("@");
944 name_in_debuginfo.push(codegen_unit_name);
946 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
948 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
949 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
950 let producer = format!("clang LLVM ({})", rustc_producer);
952 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
953 let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
955 let output_filenames = tcx.output_filenames(());
956 let split_name = if tcx.sess.target_can_use_split_dwarf() {
959 tcx.sess.split_debuginfo(),
960 tcx.sess.opts.debugging_opts.split_dwarf_kind,
961 Some(codegen_unit_name),
963 // We get a path relative to the working directory from split_dwarf_path
964 .map(|f| tcx.sess.source_map().path_mapping().map_prefix(f).0)
968 .unwrap_or_default();
969 let split_name = split_name.to_str().unwrap();
973 // This should actually be
975 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
977 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
978 // we are compiling with "limited" debuginfo. However, some of the
979 // existing tools relied on slightly more debuginfo being generated than
980 // would be the case with `LineTablesOnly`, and we did not want to break
981 // these tools in a "drive-by fix", without a good idea or plan about
982 // what limited debuginfo should exactly look like. So for now we keep
983 // the emission kind as `FullDebug`.
985 // See https://github.com/rust-lang/rust/issues/60020 for details.
986 let kind = DebugEmissionKind::FullDebug;
987 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
990 let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
991 debug_context.builder,
992 name_in_debuginfo.as_ptr().cast(),
993 name_in_debuginfo.len(),
994 work_dir.as_ptr().cast(),
996 llvm::ChecksumKind::None,
1001 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1002 debug_context.builder,
1005 producer.as_ptr().cast(),
1007 tcx.sess.opts.optimize != config::OptLevel::No,
1008 flags.as_ptr().cast(),
1010 // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1011 // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1013 split_name.as_ptr().cast(),
1017 tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1020 if tcx.sess.opts.debugging_opts.profile {
1021 let cu_desc_metadata =
1022 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1023 let default_gcda_path = &output_filenames.with_extension("gcda");
1025 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1027 let gcov_cu_info = [
1028 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1029 path_to_mdstring(debug_context.llcontext, gcda_path),
1032 let gcov_metadata = llvm::LLVMMDNodeInContext(
1033 debug_context.llcontext,
1034 gcov_cu_info.as_ptr(),
1035 gcov_cu_info.len() as c_uint,
1038 let llvm_gcov_ident = cstr!("llvm.gcov");
1039 llvm::LLVMAddNamedMetadataOperand(
1040 debug_context.llmod,
1041 llvm_gcov_ident.as_ptr(),
1046 // Insert `llvm.ident` metadata on the wasm targets since that will
1047 // get hooked up to the "producer" sections `processed-by` information.
1048 if tcx.sess.target.is_like_wasm {
1049 let name_metadata = llvm::LLVMMDStringInContext(
1050 debug_context.llcontext,
1051 rustc_producer.as_ptr().cast(),
1052 rustc_producer.as_bytes().len() as c_uint,
1054 llvm::LLVMAddNamedMetadataOperand(
1055 debug_context.llmod,
1056 cstr!("llvm.ident").as_ptr(),
1057 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1061 return unit_metadata;
1064 fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1065 let path_str = path_to_c_string(path);
1067 llvm::LLVMMDStringInContext(
1070 path_str.as_bytes().len() as c_uint,
1076 struct MetadataCreationResult<'ll> {
1077 metadata: &'ll DIType,
1078 already_stored_in_typemap: bool,
1081 impl<'ll> MetadataCreationResult<'ll> {
1082 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1083 MetadataCreationResult { metadata, already_stored_in_typemap }
1088 struct SourceInfo<'ll> {
1093 /// Description of a type member, which can either be a regular field (as in
1094 /// structs or tuples) or an enum variant.
1096 struct MemberDescription<'ll> {
1098 type_metadata: &'ll DIType,
1103 discriminant: Option<u64>,
1104 source_info: Option<SourceInfo<'ll>>,
1107 impl<'ll> MemberDescription<'ll> {
1110 cx: &CodegenCx<'ll, '_>,
1111 composite_type_metadata: &'ll DIScope,
1113 let (file, line) = self
1115 .map(|info| (info.file, info.line))
1116 .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1118 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1120 composite_type_metadata,
1121 self.name.as_ptr().cast(),
1126 self.align.bits() as u32,
1128 self.discriminant.map(|v| cx.const_u64(v)),
1136 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1137 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1138 /// creation of type member descriptions in order to break cycles arising from
1139 /// recursive type definitions.
1140 enum MemberDescriptionFactory<'ll, 'tcx> {
1141 StructMDF(StructMemberDescriptionFactory<'tcx>),
1142 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1143 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1144 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1145 VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1148 impl<'ll, 'tcx> MemberDescriptionFactory<'ll, 'tcx> {
1149 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1151 StructMDF(ref this) => this.create_member_descriptions(cx),
1152 TupleMDF(ref this) => this.create_member_descriptions(cx),
1153 EnumMDF(ref this) => this.create_member_descriptions(cx),
1154 UnionMDF(ref this) => this.create_member_descriptions(cx),
1155 VariantMDF(ref this) => this.create_member_descriptions(cx),
1160 //=-----------------------------------------------------------------------------
1162 //=-----------------------------------------------------------------------------
1164 /// Creates `MemberDescription`s for the fields of a struct.
1165 struct StructMemberDescriptionFactory<'tcx> {
1167 variant: &'tcx ty::VariantDef,
1170 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1171 fn create_member_descriptions<'ll>(
1173 cx: &CodegenCx<'ll, 'tcx>,
1174 ) -> Vec<MemberDescription<'ll>> {
1175 let layout = cx.layout_of(self.ty);
1181 let name = if self.variant.ctor_kind == CtorKind::Fn {
1186 let field = layout.field(cx, i);
1189 type_metadata: type_metadata(cx, field.ty),
1190 offset: layout.fields.offset(i),
1192 align: field.align.abi,
1193 flags: DIFlags::FlagZero,
1202 fn prepare_struct_metadata<'ll, 'tcx>(
1203 cx: &CodegenCx<'ll, 'tcx>,
1204 struct_type: Ty<'tcx>,
1205 unique_type_id: UniqueTypeId<'tcx>,
1206 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1207 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1209 let (struct_def_id, variant) = match struct_type.kind() {
1210 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1211 _ => bug!("prepare_struct_metadata on a non-ADT"),
1214 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1215 let (size, align) = cx.size_and_align_of(struct_type);
1217 let struct_metadata_stub = create_struct_stub(
1223 Some(containing_scope),
1228 create_and_register_recursive_type_forward_declaration(
1232 struct_metadata_stub,
1233 struct_metadata_stub,
1234 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant }),
1238 //=-----------------------------------------------------------------------------
1240 //=-----------------------------------------------------------------------------
1242 /// Returns names of captured upvars for closures and generators.
1244 /// Here are some examples:
1245 /// - `name__field1__field2` when the upvar is captured by value.
1246 /// - `_ref__name__field` when the upvar is captured by reference.
1247 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<String> {
1248 let body = tcx.optimized_mir(def_id);
1253 let is_ref = match var.value {
1254 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1255 // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1256 // implies whether the variable is captured by value or by reference.
1257 matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1261 let prefix = if is_ref { "_ref__" } else { "" };
1262 Some(prefix.to_owned() + var.name.as_str())
1264 .collect::<Vec<_>>()
1267 /// Creates `MemberDescription`s for the fields of a tuple.
1268 struct TupleMemberDescriptionFactory<'tcx> {
1270 component_types: Vec<Ty<'tcx>>,
1273 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1274 fn create_member_descriptions<'ll>(
1276 cx: &CodegenCx<'ll, 'tcx>,
1277 ) -> Vec<MemberDescription<'ll>> {
1278 let mut capture_names = match *self.ty.kind() {
1279 ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1280 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1284 let layout = cx.layout_of(self.ty);
1285 self.component_types
1288 .map(|(i, &component_type)| {
1289 let (size, align) = cx.size_and_align_of(component_type);
1290 let name = if let Some(names) = capture_names.as_mut() {
1291 names.next().unwrap()
1297 type_metadata: type_metadata(cx, component_type),
1298 offset: layout.fields.offset(i),
1301 flags: DIFlags::FlagZero,
1310 fn prepare_tuple_metadata<'ll, 'tcx>(
1311 cx: &CodegenCx<'ll, 'tcx>,
1312 tuple_type: Ty<'tcx>,
1313 component_types: &[Ty<'tcx>],
1314 unique_type_id: UniqueTypeId<'tcx>,
1315 containing_scope: Option<&'ll DIScope>,
1316 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1317 let (size, align) = cx.size_and_align_of(tuple_type);
1318 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1320 let struct_stub = create_struct_stub(
1331 create_and_register_recursive_type_forward_declaration(
1337 TupleMDF(TupleMemberDescriptionFactory {
1339 component_types: component_types.to_vec(),
1344 //=-----------------------------------------------------------------------------
1346 //=-----------------------------------------------------------------------------
1348 struct UnionMemberDescriptionFactory<'tcx> {
1349 layout: TyAndLayout<'tcx>,
1350 variant: &'tcx ty::VariantDef,
1353 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1354 fn create_member_descriptions<'ll>(
1356 cx: &CodegenCx<'ll, 'tcx>,
1357 ) -> Vec<MemberDescription<'ll>> {
1363 let field = self.layout.field(cx, i);
1365 name: f.name.to_string(),
1366 type_metadata: type_metadata(cx, field.ty),
1369 align: field.align.abi,
1370 flags: DIFlags::FlagZero,
1379 fn prepare_union_metadata<'ll, 'tcx>(
1380 cx: &CodegenCx<'ll, 'tcx>,
1381 union_type: Ty<'tcx>,
1382 unique_type_id: UniqueTypeId<'tcx>,
1383 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1384 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1386 let (union_def_id, variant) = match union_type.kind() {
1387 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1388 _ => bug!("prepare_union_metadata on a non-ADT"),
1391 let containing_scope = get_namespace_for_item(cx, union_def_id);
1393 let union_metadata_stub =
1394 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1396 create_and_register_recursive_type_forward_declaration(
1400 union_metadata_stub,
1401 union_metadata_stub,
1402 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant }),
1406 //=-----------------------------------------------------------------------------
1408 //=-----------------------------------------------------------------------------
1410 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1411 // per generator monomorphization, but it doesn't depend on substs.
1412 fn generator_layout_and_saved_local_names<'tcx>(
1415 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1416 let body = tcx.optimized_mir(def_id);
1417 let generator_layout = body.generator_layout().unwrap();
1418 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1420 let state_arg = mir::Local::new(1);
1421 for var in &body.var_debug_info {
1422 let mir::VarDebugInfoContents::Place(place) = &var.value else { continue };
1423 if place.local != state_arg {
1426 match place.projection[..] {
1428 // Deref of the `Pin<&mut Self>` state argument.
1429 mir::ProjectionElem::Field(..),
1430 mir::ProjectionElem::Deref,
1431 // Field of a variant of the state.
1432 mir::ProjectionElem::Downcast(_, variant),
1433 mir::ProjectionElem::Field(field, _),
1435 let name = &mut generator_saved_local_names
1436 [generator_layout.variant_fields[variant][field]];
1438 name.replace(var.name);
1444 (generator_layout, generator_saved_local_names)
1447 /// Describes the members of an enum value; an enum is described as a union of
1448 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1449 /// the members of this union; so for every variant of the given enum, this
1450 /// factory will produce one `MemberDescription` (all with no name and a fixed
1451 /// offset of zero bytes).
1452 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1453 enum_type: Ty<'tcx>,
1454 layout: TyAndLayout<'tcx>,
1455 tag_type_metadata: Option<&'ll DIType>,
1456 common_members: Vec<Option<&'ll DIType>>,
1459 impl<'ll, 'tcx> EnumMemberDescriptionFactory<'ll, 'tcx> {
1460 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1461 let generator_variant_info_data = match *self.enum_type.kind() {
1462 ty::Generator(def_id, ..) => {
1463 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1468 let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1469 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index], index),
1470 ty::Generator(def_id, _, _) => {
1471 let (generator_layout, generator_saved_local_names) =
1472 generator_variant_info_data.as_ref().unwrap();
1473 VariantInfo::Generator {
1475 generator_layout: *generator_layout,
1476 generator_saved_local_names,
1477 variant_index: index,
1483 // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
1484 // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
1485 // msvc, then we need to use a different, fallback encoding of the debuginfo.
1486 let fallback = cpp_like_debuginfo(cx.tcx);
1487 // This will always find the metadata in the type map.
1488 let self_metadata = type_metadata(cx, self.enum_type);
1490 match self.layout.variants {
1491 Variants::Single { index } => {
1492 if let ty::Adt(adt, _) = self.enum_type.kind() {
1493 if adt.variants.is_empty() {
1498 let variant_info = variant_info_for(index);
1499 let (variant_type_metadata, member_description_factory) =
1500 describe_enum_variant(cx, self.layout, variant_info, self_metadata);
1502 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1503 let type_params = compute_type_parameters(cx, self.enum_type);
1505 set_members_of_composite_type(
1507 variant_type_metadata,
1508 member_descriptions,
1509 Some(&self.common_members),
1512 vec![MemberDescription {
1513 name: variant_info.variant_name(),
1514 type_metadata: variant_type_metadata,
1516 size: self.layout.size,
1517 align: self.layout.align.abi,
1518 flags: DIFlags::FlagZero,
1520 source_info: variant_info.source_info(cx),
1523 Variants::Multiple {
1524 tag_encoding: TagEncoding::Direct,
1529 let fallback_discr_variant = if fallback {
1530 // For MSVC, we generate a union of structs for each variant and an
1531 // explicit discriminant field roughly equivalent to the following C:
1533 // union enum$<{name}> {
1534 // struct {variant 0 name} {
1535 // <variant 0 fields>
1537 // <other variant structs>
1538 // {name} discriminant;
1541 // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1542 // determine which variant is active and then displays it.
1543 let enum_layout = self.layout;
1544 let offset = enum_layout.fields.offset(tag_field);
1545 let discr_ty = enum_layout.field(cx, tag_field).ty;
1546 let (size, align) = cx.size_and_align_of(discr_ty);
1547 Some(MemberDescription {
1548 name: "discriminant".into(),
1549 type_metadata: self.tag_type_metadata.unwrap(),
1553 flags: DIFlags::FlagZero,
1564 let variant = self.layout.for_variant(cx, i);
1565 let variant_info = variant_info_for(i);
1566 let (variant_type_metadata, member_desc_factory) =
1567 describe_enum_variant(cx, variant, variant_info, self_metadata);
1569 let member_descriptions =
1570 member_desc_factory.create_member_descriptions(cx);
1571 let type_params = compute_type_parameters(cx, self.enum_type);
1573 set_members_of_composite_type(
1575 variant_type_metadata,
1576 member_descriptions,
1577 Some(&self.common_members),
1583 format!("variant{}", i.as_u32())
1585 variant_info.variant_name()
1587 type_metadata: variant_type_metadata,
1589 size: self.layout.size,
1590 align: self.layout.align.abi,
1591 flags: DIFlags::FlagZero,
1593 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1596 source_info: variant_info.source_info(cx),
1599 .chain(fallback_discr_variant.into_iter())
1602 Variants::Multiple {
1604 TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1609 let calculate_niche_value = |i: VariantIdx| {
1610 if i == dataful_variant {
1613 let value = (i.as_u32() as u128)
1614 .wrapping_sub(niche_variants.start().as_u32() as u128)
1615 .wrapping_add(niche_start);
1616 let value = tag.value.size(cx).truncate(value);
1617 // NOTE(eddyb) do *NOT* remove this assert, until
1618 // we pass the full 128-bit value to LLVM, otherwise
1619 // truncation will be silent and remain undetected.
1620 assert_eq!(value as u64 as u128, value);
1625 // For MSVC, we will generate a union of two fields, one for the dataful variant
1626 // and one that just points to the discriminant. We also create an enum that
1627 // contains tag values for the non-dataful variants and make the discriminant field
1628 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1629 // This will generate debuginfo roughly equivalent to the following C:
1631 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1632 // struct <dataful variant name> {
1633 // <fields in dataful variant>
1634 // } dataful_variant;
1635 // enum Discriminant$ {
1636 // <non-dataful variants>
1640 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1641 // and evaluates `this.discriminant`. If the value is between the min niche and max
1642 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1643 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1644 // case, we just need to render the name of the `this.discriminant` enum.
1646 let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1648 let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1649 // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1650 // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1651 // to just be `usize`.
1652 if let ty::RawPtr(_) = discr_enum_ty.kind() {
1653 discr_enum_ty = cx.tcx.types.usize;
1656 let tags: Vec<_> = variants
1658 .filter_map(|(variant_idx, _)| {
1659 calculate_niche_value(variant_idx).map(|tag| {
1660 let variant = variant_info_for(variant_idx);
1661 let name = variant.variant_name();
1664 llvm::LLVMRustDIBuilderCreateEnumerator(
1666 name.as_ptr().cast(),
1669 !discr_enum_ty.is_signed(),
1676 let discr_enum = unsafe {
1677 llvm::LLVMRustDIBuilderCreateEnumerationType(
1680 "Discriminant$".as_ptr().cast(),
1681 "Discriminant$".len(),
1682 unknown_file_metadata(cx),
1683 UNKNOWN_LINE_NUMBER,
1684 tag.value.size(cx).bits(),
1685 tag.value.align(cx).abi.bits() as u32,
1686 create_DIArray(DIB(cx), &tags),
1687 type_metadata(cx, discr_enum_ty),
1692 let variant_info = variant_info_for(dataful_variant);
1693 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1695 dataful_variant_layout,
1700 let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1701 let type_params = compute_type_parameters(cx, self.enum_type);
1703 set_members_of_composite_type(
1705 variant_type_metadata,
1706 member_descriptions,
1707 Some(&self.common_members),
1712 cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1716 // Name the dataful variant so that we can identify it for natvis
1717 name: "dataful_variant".to_string(),
1718 type_metadata: variant_type_metadata,
1720 size: self.layout.size,
1721 align: self.layout.align.abi,
1722 flags: DIFlags::FlagZero,
1724 source_info: variant_info.source_info(cx),
1727 name: "discriminant".into(),
1728 type_metadata: discr_enum,
1729 offset: dataful_variant_layout.fields.offset(tag_field),
1732 flags: DIFlags::FlagZero,
1741 let variant = self.layout.for_variant(cx, i);
1742 let variant_info = variant_info_for(i);
1743 let (variant_type_metadata, member_desc_factory) =
1744 describe_enum_variant(cx, variant, variant_info, self_metadata);
1746 let member_descriptions =
1747 member_desc_factory.create_member_descriptions(cx);
1748 let type_params = compute_type_parameters(cx, self.enum_type);
1750 set_members_of_composite_type(
1752 variant_type_metadata,
1753 member_descriptions,
1754 Some(&self.common_members),
1758 let niche_value = calculate_niche_value(i);
1761 name: variant_info.variant_name(),
1762 type_metadata: variant_type_metadata,
1764 size: self.layout.size,
1765 align: self.layout.align.abi,
1766 flags: DIFlags::FlagZero,
1767 discriminant: niche_value,
1768 source_info: variant_info.source_info(cx),
1778 // Creates `MemberDescription`s for the fields of a single enum variant.
1779 struct VariantMemberDescriptionFactory<'tcx> {
1780 /// Cloned from the `layout::Struct` describing the variant.
1782 args: Vec<(String, Ty<'tcx>)>,
1785 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1786 fn create_member_descriptions<'ll>(
1788 cx: &CodegenCx<'ll, 'tcx>,
1789 ) -> Vec<MemberDescription<'ll>> {
1793 .map(|(i, &(ref name, ty))| {
1794 let (size, align) = cx.size_and_align_of(ty);
1796 name: name.to_string(),
1797 type_metadata: type_metadata(cx, ty),
1798 offset: self.offsets[i],
1801 flags: DIFlags::FlagZero,
1810 #[derive(Copy, Clone)]
1811 enum VariantInfo<'a, 'tcx> {
1812 Adt(&'tcx ty::VariantDef, VariantIdx),
1815 generator_layout: &'tcx GeneratorLayout<'tcx>,
1816 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1817 variant_index: VariantIdx,
1821 impl<'tcx> VariantInfo<'_, 'tcx> {
1822 fn variant_idx(&self) -> VariantIdx {
1824 VariantInfo::Adt(_, variant_index) | VariantInfo::Generator { variant_index, .. } => {
1830 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1832 VariantInfo::Adt(variant, _) => f(variant.name.as_str()),
1833 VariantInfo::Generator { variant_index, .. } => {
1834 f(&GeneratorSubsts::variant_name(*variant_index))
1839 fn variant_name(&self) -> String {
1841 VariantInfo::Adt(variant, _) => variant.name.to_string(),
1842 VariantInfo::Generator { variant_index, .. } => {
1843 // Since GDB currently prints out the raw discriminant along
1844 // with every variant, make each variant name be just the value
1845 // of the discriminant. The struct name for the variant includes
1846 // the actual variant description.
1847 format!("{}", variant_index.as_usize())
1852 fn field_name(&self, i: usize) -> String {
1853 let field_name = match *self {
1854 VariantInfo::Adt(variant, _) if variant.ctor_kind != CtorKind::Fn => {
1855 Some(variant.fields[i].name)
1857 VariantInfo::Generator {
1859 generator_saved_local_names,
1863 generator_saved_local_names
1864 [generator_layout.variant_fields[variant_index][i.into()]]
1868 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1871 fn source_info<'ll>(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1872 if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1874 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1875 if !span.is_dummy() {
1876 let loc = cx.lookup_debug_loc(span.lo());
1877 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1884 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1885 /// `MemberDescriptionFactory` for producing the descriptions of the
1886 /// fields of the variant. This is a rudimentary version of a full
1887 /// `RecursiveTypeDescription`.
1888 fn describe_enum_variant<'ll, 'tcx>(
1889 cx: &CodegenCx<'ll, 'tcx>,
1890 layout: layout::TyAndLayout<'tcx>,
1891 variant: VariantInfo<'_, 'tcx>,
1892 containing_scope: &'ll DIScope,
1893 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1894 let metadata_stub = variant.map_struct_name(|variant_name| {
1895 let unique_type_id =
1896 UniqueTypeId::for_enum_variant(cx.tcx, layout.ty, variant.variant_idx());
1898 let (size, align) = cx.size_and_align_of(layout.ty);
1906 Some(containing_scope),
1912 let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
1913 let args = (0..layout.fields.count())
1914 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
1917 let member_description_factory = VariantMDF(VariantMemberDescriptionFactory { offsets, args });
1919 (metadata_stub, member_description_factory)
1922 fn prepare_enum_metadata<'ll, 'tcx>(
1923 cx: &CodegenCx<'ll, 'tcx>,
1924 enum_type: Ty<'tcx>,
1926 unique_type_id: UniqueTypeId<'tcx>,
1927 outer_field_tys: Vec<Ty<'tcx>>,
1928 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1930 let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
1932 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1933 // FIXME: This should emit actual file metadata for the enum, but we
1934 // currently can't get the necessary information when it comes to types
1935 // imported from other crates. Formerly we violated the ODR when performing
1936 // LTO because we emitted debuginfo for the same type with varying file
1937 // metadata, so as a workaround we pretend that the type comes from
1939 let file_metadata = unknown_file_metadata(cx);
1941 let discriminant_type_metadata = |discr: Primitive| {
1942 let enumerators_metadata: Vec<_> = match enum_type.kind() {
1943 ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
1944 .map(|((_, discr), v)| {
1945 let name = v.name.as_str();
1946 let is_unsigned = match discr.ty.kind() {
1947 ty::Int(_) => false,
1948 ty::Uint(_) => true,
1949 _ => bug!("non integer discriminant"),
1952 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1954 name.as_ptr().cast(),
1956 // FIXME: what if enumeration has i128 discriminant?
1963 ty::Generator(_, substs, _) => substs
1965 .variant_range(enum_def_id, tcx)
1966 .map(|variant_index| {
1967 debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
1968 let name = GeneratorSubsts::variant_name(variant_index);
1970 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1972 name.as_ptr().cast(),
1974 // Generators use u32 as discriminant type, verified above.
1975 variant_index.as_u32().into(),
1984 let disr_type_key = (enum_def_id, discr);
1985 let cached_discriminant_type_metadata =
1986 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
1987 match cached_discriminant_type_metadata {
1988 Some(discriminant_type_metadata) => discriminant_type_metadata,
1990 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
1991 let discriminant_base_type_metadata = type_metadata(cx, discr.to_ty(tcx));
1994 let discriminant_name = match enum_type.kind() {
1996 item_name = tcx.item_name(enum_def_id);
1999 ty::Generator(..) => enum_name.as_str(),
2003 let discriminant_type_metadata = unsafe {
2004 llvm::LLVMRustDIBuilderCreateEnumerationType(
2007 discriminant_name.as_ptr().cast(),
2008 discriminant_name.len(),
2010 UNKNOWN_LINE_NUMBER,
2011 discriminant_size.bits(),
2012 discriminant_align.abi.bits() as u32,
2013 create_DIArray(DIB(cx), &enumerators_metadata),
2014 discriminant_base_type_metadata,
2020 .created_enum_disr_types
2022 .insert(disr_type_key, discriminant_type_metadata);
2024 discriminant_type_metadata
2029 let layout = cx.layout_of(enum_type);
2031 if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2032 (layout.abi, &layout.variants)
2034 return FinalMetadata(discriminant_type_metadata(tag.value));
2037 // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
2038 // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
2039 // msvc, then we need to use a different encoding of the debuginfo.
2040 if cpp_like_debuginfo(tcx) {
2041 let discriminant_type_metadata = match layout.variants {
2042 Variants::Single { .. } => None,
2043 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2044 | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2045 Some(discriminant_type_metadata(tag.value))
2049 let enum_metadata = {
2050 let unique_type_id_str = unique_type_id.generate_unique_id_string(tcx);
2053 llvm::LLVMRustDIBuilderCreateUnionType(
2056 enum_name.as_ptr().cast(),
2059 UNKNOWN_LINE_NUMBER,
2061 layout.align.abi.bits() as u32,
2065 unique_type_id_str.as_ptr().cast(),
2066 unique_type_id_str.len(),
2071 return create_and_register_recursive_type_forward_declaration(
2077 EnumMDF(EnumMemberDescriptionFactory {
2080 tag_type_metadata: discriminant_type_metadata,
2081 common_members: vec![],
2086 let discriminator_name = match enum_type.kind() {
2087 ty::Generator(..) => "__state",
2090 let discriminator_metadata = match layout.variants {
2091 // A single-variant enum has no discriminant.
2092 Variants::Single { .. } => None,
2094 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2095 // Find the integer type of the correct size.
2096 let size = tag.value.size(cx);
2097 let align = tag.value.align(cx);
2099 let tag_type = match tag.value {
2101 F32 => Integer::I32,
2102 F64 => Integer::I64,
2103 Pointer => cx.data_layout().ptr_sized_integer(),
2105 .to_ty(cx.tcx, false);
2107 let tag_metadata = basic_type_metadata(cx, tag_type);
2109 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2112 discriminator_name.as_ptr().cast(),
2113 discriminator_name.len(),
2115 UNKNOWN_LINE_NUMBER,
2117 align.abi.bits() as u32,
2118 layout.fields.offset(tag_field).bits(),
2119 DIFlags::FlagArtificial,
2125 Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2126 let discr_type = tag.value.to_ty(cx.tcx);
2127 let (size, align) = cx.size_and_align_of(discr_type);
2129 let discr_metadata = basic_type_metadata(cx, discr_type);
2131 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2134 discriminator_name.as_ptr().cast(),
2135 discriminator_name.len(),
2137 UNKNOWN_LINE_NUMBER,
2139 align.bits() as u32,
2140 layout.fields.offset(tag_field).bits(),
2141 DIFlags::FlagArtificial,
2148 let outer_fields = match layout.variants {
2149 Variants::Single { .. } => vec![],
2150 Variants::Multiple { .. } => {
2152 TupleMemberDescriptionFactory { ty: enum_type, component_types: outer_field_tys };
2154 .create_member_descriptions(cx)
2156 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2161 let variant_part_unique_type_id_str =
2162 UniqueTypeId::for_enum_variant_part(tcx, enum_type).generate_unique_id_string(tcx);
2164 let empty_array = create_DIArray(DIB(cx), &[]);
2166 let variant_part = unsafe {
2167 llvm::LLVMRustDIBuilderCreateVariantPart(
2170 name.as_ptr().cast(),
2173 UNKNOWN_LINE_NUMBER,
2175 layout.align.abi.bits() as u32,
2177 discriminator_metadata,
2179 variant_part_unique_type_id_str.as_ptr().cast(),
2180 variant_part_unique_type_id_str.len(),
2184 let struct_wrapper = {
2185 // The variant part must be wrapped in a struct according to DWARF.
2186 // All fields except the discriminant (including `outer_fields`)
2187 // should be put into structures inside the variant part, which gives
2188 // an equivalent layout but offers us much better integration with
2190 let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2191 let unique_type_id_str = unique_type_id.generate_unique_id_string(tcx);
2194 llvm::LLVMRustDIBuilderCreateStructType(
2196 Some(containing_scope),
2197 enum_name.as_ptr().cast(),
2200 UNKNOWN_LINE_NUMBER,
2202 layout.align.abi.bits() as u32,
2208 unique_type_id_str.as_ptr().cast(),
2209 unique_type_id_str.len(),
2214 create_and_register_recursive_type_forward_declaration(
2220 EnumMDF(EnumMemberDescriptionFactory {
2223 tag_type_metadata: None,
2224 common_members: outer_fields,
2229 /// Creates debug information for a composite type, that is, anything that
2230 /// results in a LLVM struct.
2232 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2233 fn composite_type_metadata<'ll, 'tcx>(
2234 cx: &CodegenCx<'ll, 'tcx>,
2235 composite_type: Ty<'tcx>,
2236 composite_type_name: &str,
2237 composite_type_unique_id: UniqueTypeId<'tcx>,
2238 member_descriptions: Vec<MemberDescription<'ll>>,
2239 containing_scope: Option<&'ll DIScope>,
2240 ) -> &'ll DICompositeType {
2241 let (size, align) = cx.size_and_align_of(composite_type);
2243 // Create the (empty) struct metadata node ...
2244 let composite_type_metadata = create_struct_stub(
2248 composite_type_name,
2249 composite_type_unique_id,
2255 // ... and immediately create and add the member descriptions.
2256 set_members_of_composite_type(
2258 composite_type_metadata,
2259 member_descriptions,
2261 compute_type_parameters(cx, composite_type),
2264 composite_type_metadata
2267 fn set_members_of_composite_type<'ll, 'tcx>(
2268 cx: &CodegenCx<'ll, 'tcx>,
2269 composite_type_metadata: &'ll DICompositeType,
2270 member_descriptions: Vec<MemberDescription<'ll>>,
2271 common_members: Option<&Vec<Option<&'ll DIType>>>,
2272 type_params: &'ll DIArray,
2274 // In some rare cases LLVM metadata uniquing would lead to an existing type
2275 // description being used instead of a new one created in
2276 // create_struct_stub. This would cause a hard to trace assertion in
2277 // DICompositeType::SetTypeArray(). The following check makes sure that we
2278 // get a better error message if this should happen again due to some
2281 let mut composite_types_completed =
2282 debug_context(cx).composite_types_completed.borrow_mut();
2283 if !composite_types_completed.insert(composite_type_metadata) {
2285 "debuginfo::set_members_of_composite_type() - \
2286 Already completed forward declaration re-encountered."
2291 let mut member_metadata: Vec<_> = member_descriptions
2293 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2295 if let Some(other_members) = common_members {
2296 member_metadata.extend(other_members.iter());
2300 let field_array = create_DIArray(DIB(cx), &member_metadata);
2301 llvm::LLVMRustDICompositeTypeReplaceArrays(
2303 composite_type_metadata,
2310 /// Computes the type parameters for a type, if any, for the given metadata.
2311 fn compute_type_parameters<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2312 if let ty::Adt(def, substs) = *ty.kind() {
2313 if substs.types().next().is_some() {
2314 let generics = cx.tcx.generics_of(def.did);
2315 let names = get_parameter_names(cx, generics);
2316 let template_params: Vec<_> = iter::zip(substs, names)
2317 .filter_map(|(kind, name)| {
2318 if let GenericArgKind::Type(ty) = kind.unpack() {
2320 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2321 let actual_type_metadata = type_metadata(cx, actual_type);
2322 let name = name.as_str();
2324 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2327 name.as_ptr().cast(),
2329 actual_type_metadata,
2338 return create_DIArray(DIB(cx), &template_params);
2341 return create_DIArray(DIB(cx), &[]);
2343 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2344 let mut names = generics
2346 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2347 names.extend(generics.params.iter().map(|param| param.name));
2352 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2353 /// any caching, does not add any fields to the struct. This can be done later
2354 /// with `set_members_of_composite_type()`.
2355 fn create_struct_stub<'ll, 'tcx>(
2356 cx: &CodegenCx<'ll, 'tcx>,
2360 unique_type_id: UniqueTypeId<'tcx>,
2361 containing_scope: Option<&'ll DIScope>,
2363 vtable_holder: Option<&'ll DIType>,
2364 ) -> &'ll DICompositeType {
2365 let unique_type_id = unique_type_id.generate_unique_id_string(cx.tcx);
2367 let metadata_stub = unsafe {
2368 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2369 // pointer will lead to hard to trace and debug LLVM assertions
2370 // later on in `llvm/lib/IR/Value.cpp`.
2371 let empty_array = create_DIArray(DIB(cx), &[]);
2373 llvm::LLVMRustDIBuilderCreateStructType(
2376 type_name.as_ptr().cast(),
2378 unknown_file_metadata(cx),
2379 UNKNOWN_LINE_NUMBER,
2381 align.bits() as u32,
2387 unique_type_id.as_ptr().cast(),
2388 unique_type_id.len(),
2395 fn create_union_stub<'ll, 'tcx>(
2396 cx: &CodegenCx<'ll, 'tcx>,
2397 union_type: Ty<'tcx>,
2398 union_type_name: &str,
2399 unique_type_id: UniqueTypeId<'tcx>,
2400 containing_scope: &'ll DIScope,
2401 ) -> &'ll DICompositeType {
2402 let (union_size, union_align) = cx.size_and_align_of(union_type);
2403 let unique_type_id = unique_type_id.generate_unique_id_string(cx.tcx);
2405 let metadata_stub = unsafe {
2406 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2407 // pointer will lead to hard to trace and debug LLVM assertions
2408 // later on in `llvm/lib/IR/Value.cpp`.
2409 let empty_array = create_DIArray(DIB(cx), &[]);
2411 llvm::LLVMRustDIBuilderCreateUnionType(
2413 Some(containing_scope),
2414 union_type_name.as_ptr().cast(),
2415 union_type_name.len(),
2416 unknown_file_metadata(cx),
2417 UNKNOWN_LINE_NUMBER,
2419 union_align.bits() as u32,
2423 unique_type_id.as_ptr().cast(),
2424 unique_type_id.len(),
2431 /// Creates debug information for the given global variable.
2433 /// Adds the created metadata nodes directly to the crate's IR.
2434 pub fn create_global_var_metadata<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2435 if cx.dbg_cx.is_none() {
2439 // Only create type information if full debuginfo is enabled
2440 if cx.sess().opts.debuginfo != DebugInfo::Full {
2446 // We may want to remove the namespace scope if we're in an extern block (see
2447 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2448 let var_scope = get_namespace_for_item(cx, def_id);
2449 let span = tcx.def_span(def_id);
2451 let (file_metadata, line_number) = if !span.is_dummy() {
2452 let loc = cx.lookup_debug_loc(span.lo());
2453 (file_metadata(cx, &loc.file), loc.line)
2455 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2458 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2459 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2460 let type_metadata = type_metadata(cx, variable_type);
2461 let var_name = tcx.item_name(def_id);
2462 let var_name = var_name.as_str();
2463 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2464 // When empty, linkage_name field is omitted,
2465 // which is what we want for no_mangle statics
2466 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2468 let global_align = cx.align_of(variable_type);
2471 llvm::LLVMRustDIBuilderCreateStaticVariable(
2474 var_name.as_ptr().cast(),
2476 linkage_name.as_ptr().cast(),
2484 global_align.bytes() as u32,
2489 /// Generates LLVM debuginfo for a vtable.
2491 /// The vtable type looks like a struct with a field for each function pointer and super-trait
2492 /// pointer it contains (plus the `size` and `align` fields).
2494 /// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
2495 /// the name of the method they implement. This can be implemented in the future once there
2496 /// is a proper disambiguation scheme for dealing with methods from different traits that have
2498 fn vtable_type_metadata<'ll, 'tcx>(
2499 cx: &CodegenCx<'ll, 'tcx>,
2501 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2505 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2506 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2507 let trait_ref = tcx.erase_regions(trait_ref);
2509 tcx.vtable_entries(trait_ref)
2511 COMMON_VTABLE_ENTRIES
2514 // All function pointers are described as opaque pointers. This could be improved in the future
2515 // by describing them as actual function pointers.
2516 let void_pointer_ty = tcx.mk_imm_ptr(tcx.types.unit);
2517 let void_pointer_type_debuginfo = type_metadata(cx, void_pointer_ty);
2518 let usize_debuginfo = type_metadata(cx, tcx.types.usize);
2519 let (pointer_size, pointer_align) = cx.size_and_align_of(void_pointer_ty);
2520 // If `usize` is not pointer-sized and -aligned then the size and alignment computations
2521 // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
2523 assert_eq!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
2525 let vtable_type_name =
2526 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
2527 let unique_type_id = UniqueTypeId::for_vtable_ty(tcx, ty, poly_trait_ref);
2528 let size = pointer_size * vtable_entries.len() as u64;
2530 // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
2531 // the vtable to the type it is for.
2532 let vtable_holder = type_metadata(cx, ty);
2534 let vtable_type_metadata = create_struct_stub(
2541 DIFlags::FlagArtificial,
2542 Some(vtable_holder),
2545 // Create a field for each entry in the vtable.
2546 let fields: Vec<_> = vtable_entries
2549 .filter_map(|(index, vtable_entry)| {
2550 let (field_name, field_type) = match vtable_entry {
2551 ty::VtblEntry::MetadataDropInPlace => {
2552 ("drop_in_place".to_string(), void_pointer_type_debuginfo)
2554 ty::VtblEntry::Method(_) => {
2555 // Note: This code does not try to give a proper name to each method
2556 // because there might be multiple methods with the same name
2557 // (coming from different traits).
2558 (format!("__method{}", index), void_pointer_type_debuginfo)
2560 ty::VtblEntry::TraitVPtr(_) => {
2561 // Note: In the future we could try to set the type of this pointer
2562 // to the type that we generate for the corresponding vtable.
2563 (format!("__super_trait_ptr{}", index), void_pointer_type_debuginfo)
2565 ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_debuginfo),
2566 ty::VtblEntry::MetadataSize => ("size".to_string(), usize_debuginfo),
2567 ty::VtblEntry::Vacant => return None,
2570 Some(MemberDescription {
2572 type_metadata: field_type,
2573 offset: pointer_size * index as u64,
2575 align: pointer_align,
2576 flags: DIFlags::FlagZero,
2583 let type_params = create_DIArray(DIB(cx), &[]);
2584 set_members_of_composite_type(cx, vtable_type_metadata, fields, None, type_params);
2585 vtable_type_metadata
2588 /// Creates debug information for the given vtable, which is for the
2591 /// Adds the created metadata nodes directly to the crate's IR.
2592 pub fn create_vtable_metadata<'ll, 'tcx>(
2593 cx: &CodegenCx<'ll, 'tcx>,
2595 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2598 if cx.dbg_cx.is_none() {
2602 // Only create type information if full debuginfo is enabled
2603 if cx.sess().opts.debuginfo != DebugInfo::Full {
2608 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
2609 let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2610 let linkage_name = "";
2613 llvm::LLVMRustDIBuilderCreateStaticVariable(
2616 vtable_name.as_ptr().cast(),
2618 linkage_name.as_ptr().cast(),
2620 unknown_file_metadata(cx),
2621 UNKNOWN_LINE_NUMBER,
2631 /// Creates an "extension" of an existing `DIScope` into another file.
2632 pub fn extend_scope_to_file<'ll>(
2633 cx: &CodegenCx<'ll, '_>,
2634 scope_metadata: &'ll DIScope,
2636 ) -> &'ll DILexicalBlock {
2637 let file_metadata = file_metadata(cx, file);
2638 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }