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::fingerprint::Fingerprint;
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_fs_util::path_to_c_string;
30 use rustc_hir::def::CtorKind;
31 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
32 use rustc_index::vec::{Idx, IndexVec};
33 use rustc_middle::bug;
34 use rustc_middle::mir::{self, GeneratorLayout};
35 use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout};
36 use rustc_middle::ty::subst::GenericArgKind;
37 use rustc_middle::ty::{
38 self, AdtKind, GeneratorSubsts, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES,
40 use rustc_query_system::ich::NodeIdHashingMode;
41 use rustc_session::config::{self, DebugInfo};
42 use rustc_span::symbol::Symbol;
43 use rustc_span::FileNameDisplayPreference;
44 use rustc_span::{self, SourceFile, SourceFileHash};
45 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, TagEncoding};
46 use rustc_target::abi::{Int, Pointer, F32, F64};
47 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
50 use libc::{c_longlong, c_uint};
51 use std::collections::hash_map::Entry;
52 use std::fmt::{self, Write};
53 use std::hash::{Hash, Hasher};
55 use std::path::{Path, PathBuf};
58 impl PartialEq for llvm::Metadata {
59 fn eq(&self, other: &Self) -> bool {
64 impl Eq for llvm::Metadata {}
66 impl Hash for llvm::Metadata {
67 fn hash<H: Hasher>(&self, hasher: &mut H) {
68 (self as *const Self).hash(hasher);
72 impl fmt::Debug for llvm::Metadata {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 (self as *const Self).fmt(f)
79 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
80 const DW_LANG_RUST: c_uint = 0x1c;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_boolean: c_uint = 0x02;
83 #[allow(non_upper_case_globals)]
84 const DW_ATE_float: c_uint = 0x04;
85 #[allow(non_upper_case_globals)]
86 const DW_ATE_signed: c_uint = 0x05;
87 #[allow(non_upper_case_globals)]
88 const DW_ATE_unsigned: c_uint = 0x07;
89 #[allow(non_upper_case_globals)]
90 const DW_ATE_UTF: c_uint = 0x10;
92 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
93 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
95 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
99 use rustc_arena::DroplessArena;
101 #[derive(Copy, Hash, Eq, PartialEq, Clone)]
102 pub(super) struct UniqueTypeId(u32);
104 // The `&'static str`s in this type actually point into the arena.
106 // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
107 // found that to regress performance up to 2% in some cases. This might be
108 // revisited after further improvements to `indexmap`.
110 pub(super) struct TypeIdInterner {
111 arena: DroplessArena,
112 names: FxHashMap<&'static str, UniqueTypeId>,
113 strings: Vec<&'static str>,
116 impl TypeIdInterner {
118 pub(super) fn intern(&mut self, string: &str) -> UniqueTypeId {
119 if let Some(&name) = self.names.get(string) {
123 let name = UniqueTypeId(self.strings.len() as u32);
125 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
128 unsafe { std::str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
129 // It is safe to extend the arena allocation to `'static` because we only access
130 // these while the arena is still alive.
131 let string: &'static str = unsafe { &*(string as *const str) };
132 self.strings.push(string);
133 self.names.insert(string, name);
137 // Get the symbol as a string. `Symbol::as_str()` should be used in
138 // preference to this function.
139 pub(super) fn get(&self, symbol: UniqueTypeId) -> &str {
140 self.strings[symbol.0 as usize]
144 use unique_type_id::*;
146 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
147 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
148 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
151 pub struct TypeMap<'ll, 'tcx> {
152 /// The `UniqueTypeId`s created so far.
153 unique_id_interner: TypeIdInterner,
154 /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
155 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
156 /// A map from types to debuginfo metadata. This is an N:1 mapping.
157 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
158 /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
159 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
162 impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
163 /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
164 /// the mapping already exists.
165 fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
166 if self.type_to_metadata.insert(type_, metadata).is_some() {
167 bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
171 /// Removes a `Ty`-to-metadata mapping.
172 /// This is useful when computing the metadata for a potentially
173 /// recursive type (e.g., a function pointer of the form:
175 /// fn foo() -> impl Copy { foo }
177 /// This kind of type cannot be properly represented
178 /// via LLVM debuginfo. As a workaround,
179 /// we register a temporary Ty to metadata mapping
180 /// for the function before we compute its actual metadata.
181 /// If the metadata computation ends up recursing back to the
182 /// original function, it will use the temporary mapping
183 /// for the inner self-reference, preventing us from
184 /// recursing forever.
186 /// This function is used to remove the temporary metadata
187 /// mapping after we've computed the actual metadata.
188 fn remove_type(&mut self, ty: Ty<'tcx>) {
189 if self.type_to_metadata.remove(&ty).is_none() {
190 bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", ty);
194 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
195 /// fail if the mapping already exists.
196 fn register_unique_id_with_metadata(
198 unique_type_id: UniqueTypeId,
199 metadata: &'ll DIType,
201 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
203 "type metadata for unique ID '{}' is already in the `TypeMap`!",
204 self.get_unique_type_id_as_string(unique_type_id)
209 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
210 self.type_to_metadata.get(&type_).cloned()
213 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
214 self.unique_id_to_metadata.get(&unique_type_id).cloned()
217 /// Gets the string representation of a `UniqueTypeId`. This method will fail if
218 /// the ID is unknown.
219 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
220 self.unique_id_interner.get(unique_type_id)
223 /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
224 /// type has been requested before, this is just a table lookup. Otherwise, an
225 /// ID will be generated and stored for later lookup.
226 fn get_unique_type_id_of_type<'a>(
228 cx: &CodegenCx<'a, 'tcx>,
231 // Let's see if we already have something in the cache.
232 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
233 return unique_type_id;
235 // If not, generate one.
237 // The hasher we are using to generate the UniqueTypeId. We want
238 // something that provides more than the 64 bits of the DefaultHasher.
239 let mut hasher = StableHasher::new();
240 let mut hcx = cx.tcx.create_stable_hashing_context();
241 let type_ = cx.tcx.erase_regions(type_);
242 hcx.while_hashing_spans(false, |hcx| {
243 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
244 type_.hash_stable(hcx, &mut hasher);
247 let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
249 let key = self.unique_id_interner.intern(&unique_type_id);
250 self.type_to_unique_id.insert(type_, key);
255 /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
256 /// types of their own, so they need special handling. We still need a
257 /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
258 fn get_unique_type_id_of_enum_variant<'a>(
260 cx: &CodegenCx<'a, 'tcx>,
264 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
265 let enum_variant_type_id =
266 format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
267 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
271 /// Gets the unique type ID string for an enum variant part.
272 /// Variant parts are not types and shouldn't really have their own ID,
273 /// but it makes `set_members_of_composite_type()` simpler.
274 fn get_unique_type_id_str_of_enum_variant_part(
276 enum_type_id: UniqueTypeId,
278 format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
281 /// Gets the `UniqueTypeId` for the type of a vtable.
282 fn get_unique_type_id_of_vtable_type(&mut self, vtable_type_name: &str) -> UniqueTypeId {
283 let interner_key = self.unique_id_interner.intern(vtable_type_name);
288 /// A description of some recursive type. It can either be already finished (as
289 /// with `FinalMetadata`) or it is not yet finished, but contains all information
290 /// needed to generate the missing parts of the description. See the
291 /// documentation section on Recursive Types at the top of this file for more
293 enum RecursiveTypeDescription<'ll, 'tcx> {
295 unfinished_type: Ty<'tcx>,
296 unique_type_id: UniqueTypeId,
297 metadata_stub: &'ll DICompositeType,
298 member_holding_stub: &'ll DICompositeType,
299 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
301 FinalMetadata(&'ll DICompositeType),
304 fn create_and_register_recursive_type_forward_declaration<'ll, 'tcx>(
305 cx: &CodegenCx<'ll, 'tcx>,
306 unfinished_type: Ty<'tcx>,
307 unique_type_id: UniqueTypeId,
308 metadata_stub: &'ll DICompositeType,
309 member_holding_stub: &'ll DICompositeType,
310 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
311 ) -> RecursiveTypeDescription<'ll, 'tcx> {
312 // Insert the stub into the `TypeMap` in order to allow for recursive references.
313 let mut type_map = debug_context(cx).type_map.borrow_mut();
314 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
315 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
322 member_description_factory,
326 impl<'ll, 'tcx> RecursiveTypeDescription<'ll, 'tcx> {
327 /// Finishes up the description of the type in question (mostly by providing
328 /// descriptions of the fields of the given type) and returns the final type
330 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
332 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
338 ref member_description_factory,
340 // Make sure that we have a forward declaration of the type in
341 // the TypeMap so that recursive references are possible. This
342 // will always be the case if the RecursiveTypeDescription has
343 // been properly created through the
344 // `create_and_register_recursive_type_forward_declaration()`
347 let type_map = debug_context(cx).type_map.borrow();
348 if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
349 || type_map.find_metadata_for_type(unfinished_type).is_none()
352 "Forward declaration of potentially recursive type \
353 '{:?}' was not found in TypeMap!",
359 // ... then create the member descriptions ...
360 let member_descriptions = member_description_factory.create_member_descriptions(cx);
361 let type_params = compute_type_parameters(cx, unfinished_type);
363 // ... and attach them to the stub to complete it.
364 set_members_of_composite_type(
371 MetadataCreationResult::new(metadata_stub, true)
377 /// Returns from the enclosing function if the type metadata with the given
378 /// unique ID can be found in the type map.
379 macro_rules! return_if_metadata_created_in_meantime {
380 ($cx: expr, $unique_type_id: expr) => {
381 if let Some(metadata) =
382 debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
384 return MetadataCreationResult::new(metadata, true);
389 /// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
390 /// For slices (that is, "arrays" of unknown size) use [slice_type_metadata].
391 fn fixed_size_array_metadata<'ll, 'tcx>(
392 cx: &CodegenCx<'ll, 'tcx>,
393 unique_type_id: UniqueTypeId,
394 array_type: Ty<'tcx>,
395 ) -> MetadataCreationResult<'ll> {
396 let ty::Array(element_type, len) = array_type.kind() else {
397 bug!("fixed_size_array_metadata() called with non-ty::Array type `{:?}`", array_type)
400 let element_type_metadata = type_metadata(cx, *element_type);
402 return_if_metadata_created_in_meantime!(cx, unique_type_id);
404 let (size, align) = cx.size_and_align_of(array_type);
406 let upper_bound = len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong;
409 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
411 let subscripts = create_DIArray(DIB(cx), &[subrange]);
412 let metadata = unsafe {
413 llvm::LLVMRustDIBuilderCreateArrayType(
417 element_type_metadata,
422 MetadataCreationResult::new(metadata, false)
425 /// Creates debuginfo for built-in pointer-like things:
429 /// - ty::Adt in the case it's Box
431 /// At some point we might want to remove the special handling of Box
432 /// and treat it the same as other smart pointers (like Rc, Arc, ...).
433 fn pointer_or_reference_metadata<'ll, 'tcx>(
434 cx: &CodegenCx<'ll, 'tcx>,
436 pointee_type: Ty<'tcx>,
437 unique_type_id: UniqueTypeId,
438 ) -> MetadataCreationResult<'ll> {
439 let pointee_type_metadata = type_metadata(cx, pointee_type);
441 return_if_metadata_created_in_meantime!(cx, unique_type_id);
443 let (thin_pointer_size, thin_pointer_align) =
444 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.types.unit));
445 let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
447 let pointer_type_metadata = match fat_pointer_kind(cx, pointee_type) {
449 // This is a thin pointer. Create a regular pointer type and give it the correct name.
451 (thin_pointer_size, thin_pointer_align),
452 cx.size_and_align_of(ptr_type),
453 "ptr_type={}, pointee_type={}",
459 llvm::LLVMRustDIBuilderCreatePointerType(
461 pointee_type_metadata,
462 thin_pointer_size.bits(),
463 thin_pointer_align.bits() as u32,
464 0, // Ignore DWARF address space.
465 ptr_type_debuginfo_name.as_ptr().cast(),
466 ptr_type_debuginfo_name.len(),
470 Some(fat_pointer_kind) => {
471 let layout = cx.layout_of(ptr_type);
473 let addr_field = layout.field(cx, abi::FAT_PTR_ADDR);
474 let extra_field = layout.field(cx, abi::FAT_PTR_EXTRA);
476 let (addr_field_name, extra_field_name) = match fat_pointer_kind {
477 FatPtrKind::Dyn => ("pointer", "vtable"),
478 FatPtrKind::Slice => ("data_ptr", "length"),
481 debug_assert_eq!(abi::FAT_PTR_ADDR, 0);
482 debug_assert_eq!(abi::FAT_PTR_EXTRA, 1);
484 // The data pointer type is a regular, thin pointer, regardless of whether this is a slice
485 // or a trait object.
486 let data_ptr_type_metadata = unsafe {
487 llvm::LLVMRustDIBuilderCreatePointerType(
489 pointee_type_metadata,
490 addr_field.size.bits(),
491 addr_field.align.abi.bits() as u32,
492 0, // Ignore DWARF address space.
498 let member_descriptions = vec![
500 name: addr_field_name.into(),
501 type_metadata: data_ptr_type_metadata,
502 offset: layout.fields.offset(abi::FAT_PTR_ADDR),
503 size: addr_field.size,
504 align: addr_field.align.abi,
505 flags: DIFlags::FlagZero,
510 name: extra_field_name.into(),
511 type_metadata: type_metadata(cx, extra_field.ty),
512 offset: layout.fields.offset(abi::FAT_PTR_EXTRA),
513 size: extra_field.size,
514 align: extra_field.align.abi,
515 flags: DIFlags::FlagZero,
521 composite_type_metadata(
524 &ptr_type_debuginfo_name,
532 MetadataCreationResult { metadata: pointer_type_metadata, already_stored_in_typemap: false }
535 fn subroutine_type_metadata<'ll, 'tcx>(
536 cx: &CodegenCx<'ll, 'tcx>,
537 unique_type_id: UniqueTypeId,
538 signature: ty::PolyFnSig<'tcx>,
539 ) -> MetadataCreationResult<'ll> {
541 cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), signature);
543 let signature_metadata: Vec<_> = iter::once(
545 match signature.output().kind() {
546 ty::Tuple(tys) if tys.is_empty() => None,
547 _ => Some(type_metadata(cx, signature.output())),
552 signature.inputs().iter().map(|&argument_type| Some(type_metadata(cx, argument_type))),
556 return_if_metadata_created_in_meantime!(cx, unique_type_id);
558 MetadataCreationResult::new(
560 llvm::LLVMRustDIBuilderCreateSubroutineType(
562 create_DIArray(DIB(cx), &signature_metadata[..]),
569 /// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
570 /// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
571 fn dyn_type_metadata<'ll, 'tcx>(
572 cx: &CodegenCx<'ll, 'tcx>,
574 unique_type_id: UniqueTypeId,
576 if let ty::Dynamic(..) = dyn_type.kind() {
577 let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
578 composite_type_metadata(cx, dyn_type, &type_name, unique_type_id, vec![], NO_SCOPE_METADATA)
580 bug!("Only ty::Dynamic is valid for dyn_type_metadata(). Found {:?} instead.", dyn_type)
584 /// Create debuginfo for `[T]` and `str`. These are unsized.
586 /// NOTE: We currently emit just emit the debuginfo for the element type here
587 /// (i.e. `T` for slices and `u8` for `str`), so that we end up with
588 /// `*const T` for the `data_ptr` field of the corresponding fat-pointer
589 /// debuginfo of `&[T]`.
591 /// It would be preferable and more accurate if we emitted a DIArray of T
592 /// without an upper bound instead. That is, LLVM already supports emitting
593 /// debuginfo of arrays of unknown size. But GDB currently seems to end up
594 /// in an infinite loop when confronted with such a type.
596 /// As a side effect of the current encoding every instance of a type like
597 /// `struct Foo { unsized_field: [u8] }` will look like
598 /// `struct Foo { unsized_field: u8 }` in debuginfo. If the length of the
599 /// slice is zero, then accessing `unsized_field` in the debugger would
600 /// result in an out-of-bounds access.
601 fn slice_type_metadata<'ll, 'tcx>(
602 cx: &CodegenCx<'ll, 'tcx>,
603 slice_type: Ty<'tcx>,
604 unique_type_id: UniqueTypeId,
605 ) -> MetadataCreationResult<'ll> {
606 let element_type = match slice_type.kind() {
607 ty::Slice(element_type) => *element_type,
608 ty::Str => cx.tcx.types.u8,
611 "Only ty::Slice is valid for slice_type_metadata(). Found {:?} instead.",
617 let element_type_metadata = type_metadata(cx, element_type);
618 return_if_metadata_created_in_meantime!(cx, unique_type_id);
619 MetadataCreationResult { metadata: element_type_metadata, already_stored_in_typemap: false }
622 pub fn type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
623 // Get the unique type ID of this type.
624 let unique_type_id = {
625 let mut type_map = debug_context(cx).type_map.borrow_mut();
626 // First, try to find the type in `TypeMap`. If we have seen it before, we
627 // can exit early here.
628 match type_map.find_metadata_for_type(t) {
633 // The Ty is not in the `TypeMap` but maybe we have already seen
634 // an equivalent type (e.g., only differing in region arguments).
635 // In order to find out, generate the unique type ID and look
637 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
638 match type_map.find_metadata_for_unique_id(unique_type_id) {
640 // There is already an equivalent type in the TypeMap.
641 // Register this Ty as an alias in the cache and
642 // return the cached metadata.
643 type_map.register_type_with_metadata(t, metadata);
647 // There really is no type metadata for this type, so
648 // proceed by creating it.
656 debug!("type_metadata: {:?}", t);
658 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
659 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
660 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
662 ty::Tuple(elements) if elements.is_empty() => {
663 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
665 ty::Array(..) => fixed_size_array_metadata(cx, unique_type_id, t),
666 ty::Slice(_) | ty::Str => slice_type_metadata(cx, t, unique_type_id),
668 MetadataCreationResult::new(dyn_type_metadata(cx, t, unique_type_id), false)
671 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
673 ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => {
674 pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id)
676 ty::Adt(def, _) if def.is_box() => {
677 pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id)
679 ty::FnDef(..) | ty::FnPtr(_) => {
680 if let Some(metadata) =
681 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
686 // It's possible to create a self-referential
687 // type in Rust by using 'impl trait':
689 // fn foo() -> impl Copy { foo }
691 // See `TypeMap::remove_type` for more detals
692 // about the workaround.
696 // The choice of type here is pretty arbitrary -
697 // anything reading the debuginfo for a recursive
698 // type is going to see *something* weird - the only
699 // question is what exactly it will see.
700 let name = "<recur_type>";
701 llvm::LLVMRustDIBuilderCreateBasicType(
703 name.as_ptr().cast(),
705 cx.size_of(t).bits(),
711 let type_map = &debug_context(cx).type_map;
712 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
715 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx)).metadata;
717 type_map.borrow_mut().remove_type(t);
719 // This is actually a function pointer, so wrap it in pointer DI.
720 let (pointer_size, pointer_align) =
721 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.mk_unit()));
722 let name = compute_debuginfo_type_name(cx.tcx, t, false);
724 llvm::LLVMRustDIBuilderCreatePointerType(
728 pointer_align.bits() as u32,
729 0, // Ignore DWARF address space.
730 name.as_ptr().cast(),
735 MetadataCreationResult::new(md, false)
737 ty::Closure(def_id, substs) => {
738 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
739 let containing_scope = get_namespace_for_item(cx, def_id);
740 prepare_tuple_metadata(cx, t, &upvar_tys, unique_type_id, Some(containing_scope))
743 ty::Generator(def_id, substs, _) => {
744 let upvar_tys: Vec<_> = substs
747 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
749 prepare_enum_metadata(cx, t, def_id, unique_type_id, upvar_tys).finalize(cx)
751 ty::Adt(def, ..) => match def.adt_kind() {
752 AdtKind::Struct => prepare_struct_metadata(cx, t, unique_type_id).finalize(cx),
753 AdtKind::Union => prepare_union_metadata(cx, t, unique_type_id).finalize(cx),
755 prepare_enum_metadata(cx, t, def.did, unique_type_id, vec![]).finalize(cx)
759 prepare_tuple_metadata(cx, t, tys, unique_type_id, NO_SCOPE_METADATA).finalize(cx)
761 // Type parameters from polymorphized functions.
762 ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
763 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
767 let mut type_map = debug_context(cx).type_map.borrow_mut();
769 if already_stored_in_typemap {
770 // Also make sure that we already have a `TypeMap` entry for the unique type ID.
771 let Some(metadata_for_uid) = type_map.find_metadata_for_unique_id(unique_type_id) else {
773 "expected type metadata for unique \
774 type ID '{}' to already be in \
775 the `debuginfo::TypeMap` but it \
777 type_map.get_unique_type_id_as_string(unique_type_id),
782 match type_map.find_metadata_for_type(t) {
784 if metadata != metadata_for_uid {
786 "mismatch between `Ty` and \
787 `UniqueTypeId` maps in \
788 `debuginfo::TypeMap`. \
789 UniqueTypeId={}, Ty={}",
790 type_map.get_unique_type_id_as_string(unique_type_id),
796 type_map.register_type_with_metadata(t, metadata);
800 type_map.register_type_with_metadata(t, metadata);
801 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
808 fn hex_encode(data: &[u8]) -> String {
809 let mut hex_string = String::with_capacity(data.len() * 2);
810 for byte in data.iter() {
811 write!(&mut hex_string, "{:02x}", byte).unwrap();
816 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
817 debug!("file_metadata: file_name: {:?}", source_file.name);
819 let hash = Some(&source_file.src_hash);
820 let file_name = Some(source_file.name.prefer_remapped().to_string());
821 let directory = if source_file.is_real_file() && !source_file.is_imported() {
826 .to_string_lossy(FileNameDisplayPreference::Remapped)
830 // If the path comes from an upstream crate we assume it has been made
831 // independent of the compiler's working directory one way or another.
834 file_metadata_raw(cx, file_name, directory, hash)
837 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
838 file_metadata_raw(cx, None, None, None)
841 fn file_metadata_raw<'ll>(
842 cx: &CodegenCx<'ll, '_>,
843 file_name: Option<String>,
844 directory: Option<String>,
845 hash: Option<&SourceFileHash>,
847 let key = (file_name, directory);
849 match debug_context(cx).created_files.borrow_mut().entry(key) {
850 Entry::Occupied(o) => o.get(),
851 Entry::Vacant(v) => {
852 let (file_name, directory) = v.key();
853 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
855 let file_name = file_name.as_deref().unwrap_or("<unknown>");
856 let directory = directory.as_deref().unwrap_or("");
858 let (hash_kind, hash_value) = match hash {
860 let kind = match hash.kind {
861 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
862 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
863 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
865 (kind, hex_encode(hash.hash_bytes()))
867 None => (llvm::ChecksumKind::None, String::new()),
870 let file_metadata = unsafe {
871 llvm::LLVMRustDIBuilderCreateFile(
873 file_name.as_ptr().cast(),
875 directory.as_ptr().cast(),
878 hash_value.as_ptr().cast(),
883 v.insert(file_metadata);
889 trait MsvcBasicName {
890 fn msvc_basic_name(self) -> &'static str;
893 impl MsvcBasicName for ty::IntTy {
894 fn msvc_basic_name(self) -> &'static str {
896 ty::IntTy::Isize => "ptrdiff_t",
897 ty::IntTy::I8 => "__int8",
898 ty::IntTy::I16 => "__int16",
899 ty::IntTy::I32 => "__int32",
900 ty::IntTy::I64 => "__int64",
901 ty::IntTy::I128 => "__int128",
906 impl MsvcBasicName for ty::UintTy {
907 fn msvc_basic_name(self) -> &'static str {
909 ty::UintTy::Usize => "size_t",
910 ty::UintTy::U8 => "unsigned __int8",
911 ty::UintTy::U16 => "unsigned __int16",
912 ty::UintTy::U32 => "unsigned __int32",
913 ty::UintTy::U64 => "unsigned __int64",
914 ty::UintTy::U128 => "unsigned __int128",
919 impl MsvcBasicName for ty::FloatTy {
920 fn msvc_basic_name(self) -> &'static str {
922 ty::FloatTy::F32 => "float",
923 ty::FloatTy::F64 => "double",
928 fn basic_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
929 debug!("basic_type_metadata: {:?}", t);
931 // When targeting MSVC, emit MSVC style type names for compatibility with
932 // .natvis visualizers (and perhaps other existing native debuggers?)
933 let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
935 let (name, encoding) = match t.kind() {
936 ty::Never => ("!", DW_ATE_unsigned),
937 ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
938 ty::Bool => ("bool", DW_ATE_boolean),
939 ty::Char => ("char", DW_ATE_UTF),
940 ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
941 ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
942 ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
943 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
944 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
945 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
946 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
949 let ty_metadata = unsafe {
950 llvm::LLVMRustDIBuilderCreateBasicType(
952 name.as_ptr().cast(),
954 cx.size_of(t).bits(),
959 if !cpp_like_debuginfo {
963 let typedef_name = match t.kind() {
964 ty::Int(int_ty) => int_ty.name_str(),
965 ty::Uint(uint_ty) => uint_ty.name_str(),
966 ty::Float(float_ty) => float_ty.name_str(),
967 _ => return ty_metadata,
970 let typedef_metadata = unsafe {
971 llvm::LLVMRustDIBuilderCreateTypedef(
974 typedef_name.as_ptr().cast(),
976 unknown_file_metadata(cx),
985 fn foreign_type_metadata<'ll, 'tcx>(
986 cx: &CodegenCx<'ll, 'tcx>,
988 unique_type_id: UniqueTypeId,
990 debug!("foreign_type_metadata: {:?}", t);
992 let name = compute_debuginfo_type_name(cx.tcx, t, false);
993 let (size, align) = cx.size_and_align_of(t);
1006 fn param_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
1007 debug!("param_type_metadata: {:?}", t);
1008 let name = format!("{:?}", t);
1010 llvm::LLVMRustDIBuilderCreateBasicType(
1012 name.as_ptr().cast(),
1020 pub fn compile_unit_metadata<'ll, 'tcx>(
1022 codegen_unit_name: &str,
1023 debug_context: &CrateDebugContext<'ll, 'tcx>,
1024 ) -> &'ll DIDescriptor {
1025 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
1026 Some(ref path) => path.clone(),
1027 None => PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()),
1030 // To avoid breaking split DWARF, we need to ensure that each codegen unit
1031 // has a unique `DW_AT_name`. This is because there's a remote chance that
1032 // different codegen units for the same module will have entirely
1033 // identical DWARF entries for the purpose of the DWO ID, which would
1034 // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
1035 // specification. LLVM uses the algorithm specified in section 7.32 "Type
1036 // Signature Computation" to compute the DWO ID, which does not include
1037 // any fields that would distinguish compilation units. So we must embed
1038 // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
1040 // Additionally, the OSX linker has an idiosyncrasy where it will ignore
1041 // some debuginfo if multiple object files with the same `DW_AT_name` are
1044 // As a workaround for these two issues, we generate unique names for each
1045 // object file. Those do not correspond to an actual source file but that
1047 name_in_debuginfo.push("@");
1048 name_in_debuginfo.push(codegen_unit_name);
1050 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
1051 let rustc_producer =
1052 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
1053 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
1054 let producer = format!("clang LLVM ({})", rustc_producer);
1056 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1057 let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
1059 let output_filenames = tcx.output_filenames(());
1060 let split_name = if tcx.sess.target_can_use_split_dwarf() {
1063 tcx.sess.split_debuginfo(),
1064 tcx.sess.opts.debugging_opts.split_dwarf_kind,
1065 Some(codegen_unit_name),
1067 // We get a path relative to the working directory from split_dwarf_path
1068 .map(|f| tcx.sess.source_map().path_mapping().map_prefix(f).0)
1072 .unwrap_or_default();
1073 let split_name = split_name.to_str().unwrap();
1077 // This should actually be
1079 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1081 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
1082 // we are compiling with "limited" debuginfo. However, some of the
1083 // existing tools relied on slightly more debuginfo being generated than
1084 // would be the case with `LineTablesOnly`, and we did not want to break
1085 // these tools in a "drive-by fix", without a good idea or plan about
1086 // what limited debuginfo should exactly look like. So for now we keep
1087 // the emission kind as `FullDebug`.
1089 // See https://github.com/rust-lang/rust/issues/60020 for details.
1090 let kind = DebugEmissionKind::FullDebug;
1091 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1094 let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1095 debug_context.builder,
1096 name_in_debuginfo.as_ptr().cast(),
1097 name_in_debuginfo.len(),
1098 work_dir.as_ptr().cast(),
1100 llvm::ChecksumKind::None,
1105 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1106 debug_context.builder,
1109 producer.as_ptr().cast(),
1111 tcx.sess.opts.optimize != config::OptLevel::No,
1112 flags.as_ptr().cast(),
1114 // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1115 // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1117 split_name.as_ptr().cast(),
1121 tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1124 if tcx.sess.opts.debugging_opts.profile {
1125 let cu_desc_metadata =
1126 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1127 let default_gcda_path = &output_filenames.with_extension("gcda");
1129 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1131 let gcov_cu_info = [
1132 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1133 path_to_mdstring(debug_context.llcontext, gcda_path),
1136 let gcov_metadata = llvm::LLVMMDNodeInContext(
1137 debug_context.llcontext,
1138 gcov_cu_info.as_ptr(),
1139 gcov_cu_info.len() as c_uint,
1142 let llvm_gcov_ident = cstr!("llvm.gcov");
1143 llvm::LLVMAddNamedMetadataOperand(
1144 debug_context.llmod,
1145 llvm_gcov_ident.as_ptr(),
1150 // Insert `llvm.ident` metadata on the wasm targets since that will
1151 // get hooked up to the "producer" sections `processed-by` information.
1152 if tcx.sess.target.is_like_wasm {
1153 let name_metadata = llvm::LLVMMDStringInContext(
1154 debug_context.llcontext,
1155 rustc_producer.as_ptr().cast(),
1156 rustc_producer.as_bytes().len() as c_uint,
1158 llvm::LLVMAddNamedMetadataOperand(
1159 debug_context.llmod,
1160 cstr!("llvm.ident").as_ptr(),
1161 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1165 return unit_metadata;
1168 fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1169 let path_str = path_to_c_string(path);
1171 llvm::LLVMMDStringInContext(
1174 path_str.as_bytes().len() as c_uint,
1180 struct MetadataCreationResult<'ll> {
1181 metadata: &'ll DIType,
1182 already_stored_in_typemap: bool,
1185 impl<'ll> MetadataCreationResult<'ll> {
1186 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1187 MetadataCreationResult { metadata, already_stored_in_typemap }
1192 struct SourceInfo<'ll> {
1197 /// Description of a type member, which can either be a regular field (as in
1198 /// structs or tuples) or an enum variant.
1200 struct MemberDescription<'ll> {
1202 type_metadata: &'ll DIType,
1207 discriminant: Option<u64>,
1208 source_info: Option<SourceInfo<'ll>>,
1211 impl<'ll> MemberDescription<'ll> {
1214 cx: &CodegenCx<'ll, '_>,
1215 composite_type_metadata: &'ll DIScope,
1217 let (file, line) = self
1219 .map(|info| (info.file, info.line))
1220 .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1222 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1224 composite_type_metadata,
1225 self.name.as_ptr().cast(),
1230 self.align.bits() as u32,
1232 self.discriminant.map(|v| cx.const_u64(v)),
1240 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1241 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1242 /// creation of type member descriptions in order to break cycles arising from
1243 /// recursive type definitions.
1244 enum MemberDescriptionFactory<'ll, 'tcx> {
1245 StructMDF(StructMemberDescriptionFactory<'tcx>),
1246 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1247 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1248 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1249 VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1252 impl<'ll, 'tcx> MemberDescriptionFactory<'ll, 'tcx> {
1253 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1255 StructMDF(ref this) => this.create_member_descriptions(cx),
1256 TupleMDF(ref this) => this.create_member_descriptions(cx),
1257 EnumMDF(ref this) => this.create_member_descriptions(cx),
1258 UnionMDF(ref this) => this.create_member_descriptions(cx),
1259 VariantMDF(ref this) => this.create_member_descriptions(cx),
1264 //=-----------------------------------------------------------------------------
1266 //=-----------------------------------------------------------------------------
1268 /// Creates `MemberDescription`s for the fields of a struct.
1269 struct StructMemberDescriptionFactory<'tcx> {
1271 variant: &'tcx ty::VariantDef,
1274 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1275 fn create_member_descriptions<'ll>(
1277 cx: &CodegenCx<'ll, 'tcx>,
1278 ) -> Vec<MemberDescription<'ll>> {
1279 let layout = cx.layout_of(self.ty);
1285 let name = if self.variant.ctor_kind == CtorKind::Fn {
1290 let field = layout.field(cx, i);
1293 type_metadata: type_metadata(cx, field.ty),
1294 offset: layout.fields.offset(i),
1296 align: field.align.abi,
1297 flags: DIFlags::FlagZero,
1306 fn prepare_struct_metadata<'ll, 'tcx>(
1307 cx: &CodegenCx<'ll, 'tcx>,
1308 struct_type: Ty<'tcx>,
1309 unique_type_id: UniqueTypeId,
1310 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1311 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1313 let (struct_def_id, variant) = match struct_type.kind() {
1314 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1315 _ => bug!("prepare_struct_metadata on a non-ADT"),
1318 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1319 let (size, align) = cx.size_and_align_of(struct_type);
1321 let struct_metadata_stub = create_struct_stub(
1327 Some(containing_scope),
1332 create_and_register_recursive_type_forward_declaration(
1336 struct_metadata_stub,
1337 struct_metadata_stub,
1338 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant }),
1342 //=-----------------------------------------------------------------------------
1344 //=-----------------------------------------------------------------------------
1346 /// Returns names of captured upvars for closures and generators.
1348 /// Here are some examples:
1349 /// - `name__field1__field2` when the upvar is captured by value.
1350 /// - `_ref__name__field` when the upvar is captured by reference.
1351 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<String> {
1352 let body = tcx.optimized_mir(def_id);
1357 let is_ref = match var.value {
1358 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1359 // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1360 // implies whether the variable is captured by value or by reference.
1361 matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1365 let prefix = if is_ref { "_ref__" } else { "" };
1366 Some(prefix.to_owned() + var.name.as_str())
1368 .collect::<Vec<_>>()
1371 /// Creates `MemberDescription`s for the fields of a tuple.
1372 struct TupleMemberDescriptionFactory<'tcx> {
1374 component_types: Vec<Ty<'tcx>>,
1377 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1378 fn create_member_descriptions<'ll>(
1380 cx: &CodegenCx<'ll, 'tcx>,
1381 ) -> Vec<MemberDescription<'ll>> {
1382 let mut capture_names = match *self.ty.kind() {
1383 ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1384 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1388 let layout = cx.layout_of(self.ty);
1389 self.component_types
1392 .map(|(i, &component_type)| {
1393 let (size, align) = cx.size_and_align_of(component_type);
1394 let name = if let Some(names) = capture_names.as_mut() {
1395 names.next().unwrap()
1401 type_metadata: type_metadata(cx, component_type),
1402 offset: layout.fields.offset(i),
1405 flags: DIFlags::FlagZero,
1414 fn prepare_tuple_metadata<'ll, 'tcx>(
1415 cx: &CodegenCx<'ll, 'tcx>,
1416 tuple_type: Ty<'tcx>,
1417 component_types: &[Ty<'tcx>],
1418 unique_type_id: UniqueTypeId,
1419 containing_scope: Option<&'ll DIScope>,
1420 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1421 let (size, align) = cx.size_and_align_of(tuple_type);
1422 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1424 let struct_stub = create_struct_stub(
1435 create_and_register_recursive_type_forward_declaration(
1441 TupleMDF(TupleMemberDescriptionFactory {
1443 component_types: component_types.to_vec(),
1448 //=-----------------------------------------------------------------------------
1450 //=-----------------------------------------------------------------------------
1452 struct UnionMemberDescriptionFactory<'tcx> {
1453 layout: TyAndLayout<'tcx>,
1454 variant: &'tcx ty::VariantDef,
1457 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1458 fn create_member_descriptions<'ll>(
1460 cx: &CodegenCx<'ll, 'tcx>,
1461 ) -> Vec<MemberDescription<'ll>> {
1467 let field = self.layout.field(cx, i);
1469 name: f.name.to_string(),
1470 type_metadata: type_metadata(cx, field.ty),
1473 align: field.align.abi,
1474 flags: DIFlags::FlagZero,
1483 fn prepare_union_metadata<'ll, 'tcx>(
1484 cx: &CodegenCx<'ll, 'tcx>,
1485 union_type: Ty<'tcx>,
1486 unique_type_id: UniqueTypeId,
1487 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1488 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1490 let (union_def_id, variant) = match union_type.kind() {
1491 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1492 _ => bug!("prepare_union_metadata on a non-ADT"),
1495 let containing_scope = get_namespace_for_item(cx, union_def_id);
1497 let union_metadata_stub =
1498 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1500 create_and_register_recursive_type_forward_declaration(
1504 union_metadata_stub,
1505 union_metadata_stub,
1506 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant }),
1510 //=-----------------------------------------------------------------------------
1512 //=-----------------------------------------------------------------------------
1514 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1515 // per generator monomorphization, but it doesn't depend on substs.
1516 fn generator_layout_and_saved_local_names<'tcx>(
1519 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1520 let body = tcx.optimized_mir(def_id);
1521 let generator_layout = body.generator_layout().unwrap();
1522 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1524 let state_arg = mir::Local::new(1);
1525 for var in &body.var_debug_info {
1526 let mir::VarDebugInfoContents::Place(place) = &var.value else { continue };
1527 if place.local != state_arg {
1530 match place.projection[..] {
1532 // Deref of the `Pin<&mut Self>` state argument.
1533 mir::ProjectionElem::Field(..),
1534 mir::ProjectionElem::Deref,
1535 // Field of a variant of the state.
1536 mir::ProjectionElem::Downcast(_, variant),
1537 mir::ProjectionElem::Field(field, _),
1539 let name = &mut generator_saved_local_names
1540 [generator_layout.variant_fields[variant][field]];
1542 name.replace(var.name);
1548 (generator_layout, generator_saved_local_names)
1551 /// Describes the members of an enum value; an enum is described as a union of
1552 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1553 /// the members of this union; so for every variant of the given enum, this
1554 /// factory will produce one `MemberDescription` (all with no name and a fixed
1555 /// offset of zero bytes).
1556 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1557 enum_type: Ty<'tcx>,
1558 layout: TyAndLayout<'tcx>,
1559 tag_type_metadata: Option<&'ll DIType>,
1560 common_members: Vec<Option<&'ll DIType>>,
1563 impl<'ll, 'tcx> EnumMemberDescriptionFactory<'ll, 'tcx> {
1564 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1565 let generator_variant_info_data = match *self.enum_type.kind() {
1566 ty::Generator(def_id, ..) => {
1567 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1572 let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1573 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1574 ty::Generator(def_id, _, _) => {
1575 let (generator_layout, generator_saved_local_names) =
1576 generator_variant_info_data.as_ref().unwrap();
1577 VariantInfo::Generator {
1579 generator_layout: *generator_layout,
1580 generator_saved_local_names,
1581 variant_index: index,
1587 // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
1588 // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
1589 // msvc, then we need to use a different, fallback encoding of the debuginfo.
1590 let fallback = cpp_like_debuginfo(cx.tcx);
1591 // This will always find the metadata in the type map.
1592 let self_metadata = type_metadata(cx, self.enum_type);
1594 match self.layout.variants {
1595 Variants::Single { index } => {
1596 if let ty::Adt(adt, _) = self.enum_type.kind() {
1597 if adt.variants.is_empty() {
1602 let variant_info = variant_info_for(index);
1603 let (variant_type_metadata, member_description_factory) =
1604 describe_enum_variant(cx, self.layout, variant_info, self_metadata);
1606 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1607 let type_params = compute_type_parameters(cx, self.enum_type);
1609 set_members_of_composite_type(
1611 variant_type_metadata,
1612 member_descriptions,
1613 Some(&self.common_members),
1616 vec![MemberDescription {
1617 name: variant_info.variant_name(),
1618 type_metadata: variant_type_metadata,
1620 size: self.layout.size,
1621 align: self.layout.align.abi,
1622 flags: DIFlags::FlagZero,
1624 source_info: variant_info.source_info(cx),
1627 Variants::Multiple {
1628 tag_encoding: TagEncoding::Direct,
1633 let fallback_discr_variant = if fallback {
1634 // For MSVC, we generate a union of structs for each variant and an
1635 // explicit discriminant field roughly equivalent to the following C:
1637 // union enum$<{name}> {
1638 // struct {variant 0 name} {
1639 // <variant 0 fields>
1641 // <other variant structs>
1642 // {name} discriminant;
1645 // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1646 // determine which variant is active and then displays it.
1647 let enum_layout = self.layout;
1648 let offset = enum_layout.fields.offset(tag_field);
1649 let discr_ty = enum_layout.field(cx, tag_field).ty;
1650 let (size, align) = cx.size_and_align_of(discr_ty);
1651 Some(MemberDescription {
1652 name: "discriminant".into(),
1653 type_metadata: self.tag_type_metadata.unwrap(),
1657 flags: DIFlags::FlagZero,
1668 let variant = self.layout.for_variant(cx, i);
1669 let variant_info = variant_info_for(i);
1670 let (variant_type_metadata, member_desc_factory) =
1671 describe_enum_variant(cx, variant, variant_info, self_metadata);
1673 let member_descriptions =
1674 member_desc_factory.create_member_descriptions(cx);
1675 let type_params = compute_type_parameters(cx, self.enum_type);
1677 set_members_of_composite_type(
1679 variant_type_metadata,
1680 member_descriptions,
1681 Some(&self.common_members),
1687 format!("variant{}", i.as_u32())
1689 variant_info.variant_name()
1691 type_metadata: variant_type_metadata,
1693 size: self.layout.size,
1694 align: self.layout.align.abi,
1695 flags: DIFlags::FlagZero,
1697 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1700 source_info: variant_info.source_info(cx),
1703 .chain(fallback_discr_variant.into_iter())
1706 Variants::Multiple {
1708 TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1713 let calculate_niche_value = |i: VariantIdx| {
1714 if i == dataful_variant {
1717 let value = (i.as_u32() as u128)
1718 .wrapping_sub(niche_variants.start().as_u32() as u128)
1719 .wrapping_add(niche_start);
1720 let value = tag.value.size(cx).truncate(value);
1721 // NOTE(eddyb) do *NOT* remove this assert, until
1722 // we pass the full 128-bit value to LLVM, otherwise
1723 // truncation will be silent and remain undetected.
1724 assert_eq!(value as u64 as u128, value);
1729 // For MSVC, we will generate a union of two fields, one for the dataful variant
1730 // and one that just points to the discriminant. We also create an enum that
1731 // contains tag values for the non-dataful variants and make the discriminant field
1732 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1733 // This will generate debuginfo roughly equivalent to the following C:
1735 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1736 // struct <dataful variant name> {
1737 // <fields in dataful variant>
1738 // } dataful_variant;
1739 // enum Discriminant$ {
1740 // <non-dataful variants>
1744 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1745 // and evaluates `this.discriminant`. If the value is between the min niche and max
1746 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1747 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1748 // case, we just need to render the name of the `this.discriminant` enum.
1750 let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1752 let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1753 // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1754 // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1755 // to just be `usize`.
1756 if let ty::RawPtr(_) = discr_enum_ty.kind() {
1757 discr_enum_ty = cx.tcx.types.usize;
1760 let tags: Vec<_> = variants
1762 .filter_map(|(variant_idx, _)| {
1763 calculate_niche_value(variant_idx).map(|tag| {
1764 let variant = variant_info_for(variant_idx);
1765 let name = variant.variant_name();
1768 llvm::LLVMRustDIBuilderCreateEnumerator(
1770 name.as_ptr().cast(),
1773 !discr_enum_ty.is_signed(),
1780 let discr_enum = unsafe {
1781 llvm::LLVMRustDIBuilderCreateEnumerationType(
1784 "Discriminant$".as_ptr().cast(),
1785 "Discriminant$".len(),
1786 unknown_file_metadata(cx),
1787 UNKNOWN_LINE_NUMBER,
1788 tag.value.size(cx).bits(),
1789 tag.value.align(cx).abi.bits() as u32,
1790 create_DIArray(DIB(cx), &tags),
1791 type_metadata(cx, discr_enum_ty),
1796 let variant_info = variant_info_for(dataful_variant);
1797 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1799 dataful_variant_layout,
1804 let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1805 let type_params = compute_type_parameters(cx, self.enum_type);
1807 set_members_of_composite_type(
1809 variant_type_metadata,
1810 member_descriptions,
1811 Some(&self.common_members),
1816 cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1820 // Name the dataful variant so that we can identify it for natvis
1821 name: "dataful_variant".to_string(),
1822 type_metadata: variant_type_metadata,
1824 size: self.layout.size,
1825 align: self.layout.align.abi,
1826 flags: DIFlags::FlagZero,
1828 source_info: variant_info.source_info(cx),
1831 name: "discriminant".into(),
1832 type_metadata: discr_enum,
1833 offset: dataful_variant_layout.fields.offset(tag_field),
1836 flags: DIFlags::FlagZero,
1845 let variant = self.layout.for_variant(cx, i);
1846 let variant_info = variant_info_for(i);
1847 let (variant_type_metadata, member_desc_factory) =
1848 describe_enum_variant(cx, variant, variant_info, self_metadata);
1850 let member_descriptions =
1851 member_desc_factory.create_member_descriptions(cx);
1852 let type_params = compute_type_parameters(cx, self.enum_type);
1854 set_members_of_composite_type(
1856 variant_type_metadata,
1857 member_descriptions,
1858 Some(&self.common_members),
1862 let niche_value = calculate_niche_value(i);
1865 name: variant_info.variant_name(),
1866 type_metadata: variant_type_metadata,
1868 size: self.layout.size,
1869 align: self.layout.align.abi,
1870 flags: DIFlags::FlagZero,
1871 discriminant: niche_value,
1872 source_info: variant_info.source_info(cx),
1882 // Creates `MemberDescription`s for the fields of a single enum variant.
1883 struct VariantMemberDescriptionFactory<'tcx> {
1884 /// Cloned from the `layout::Struct` describing the variant.
1886 args: Vec<(String, Ty<'tcx>)>,
1889 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1890 fn create_member_descriptions<'ll>(
1892 cx: &CodegenCx<'ll, 'tcx>,
1893 ) -> Vec<MemberDescription<'ll>> {
1897 .map(|(i, &(ref name, ty))| {
1898 let (size, align) = cx.size_and_align_of(ty);
1900 name: name.to_string(),
1901 type_metadata: type_metadata(cx, ty),
1902 offset: self.offsets[i],
1905 flags: DIFlags::FlagZero,
1914 #[derive(Copy, Clone)]
1915 enum VariantInfo<'a, 'tcx> {
1916 Adt(&'tcx ty::VariantDef),
1919 generator_layout: &'tcx GeneratorLayout<'tcx>,
1920 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1921 variant_index: VariantIdx,
1925 impl<'tcx> VariantInfo<'_, 'tcx> {
1926 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1928 VariantInfo::Adt(variant) => f(variant.name.as_str()),
1929 VariantInfo::Generator { variant_index, .. } => {
1930 f(&GeneratorSubsts::variant_name(*variant_index))
1935 fn variant_name(&self) -> String {
1937 VariantInfo::Adt(variant) => variant.name.to_string(),
1938 VariantInfo::Generator { variant_index, .. } => {
1939 // Since GDB currently prints out the raw discriminant along
1940 // with every variant, make each variant name be just the value
1941 // of the discriminant. The struct name for the variant includes
1942 // the actual variant description.
1943 format!("{}", variant_index.as_usize())
1948 fn field_name(&self, i: usize) -> String {
1949 let field_name = match *self {
1950 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1951 Some(variant.fields[i].name)
1953 VariantInfo::Generator {
1955 generator_saved_local_names,
1959 generator_saved_local_names
1960 [generator_layout.variant_fields[variant_index][i.into()]]
1964 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1967 fn source_info<'ll>(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1968 if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1970 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1971 if !span.is_dummy() {
1972 let loc = cx.lookup_debug_loc(span.lo());
1973 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1980 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1981 /// `MemberDescriptionFactory` for producing the descriptions of the
1982 /// fields of the variant. This is a rudimentary version of a full
1983 /// `RecursiveTypeDescription`.
1984 fn describe_enum_variant<'ll, 'tcx>(
1985 cx: &CodegenCx<'ll, 'tcx>,
1986 layout: layout::TyAndLayout<'tcx>,
1987 variant: VariantInfo<'_, 'tcx>,
1988 containing_scope: &'ll DIScope,
1989 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1990 let metadata_stub = variant.map_struct_name(|variant_name| {
1991 let unique_type_id = debug_context(cx)
1994 .get_unique_type_id_of_enum_variant(cx, layout.ty, variant_name);
1996 let (size, align) = cx.size_and_align_of(layout.ty);
2004 Some(containing_scope),
2010 let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
2011 let args = (0..layout.fields.count())
2012 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
2015 let member_description_factory = VariantMDF(VariantMemberDescriptionFactory { offsets, args });
2017 (metadata_stub, member_description_factory)
2020 fn prepare_enum_metadata<'ll, 'tcx>(
2021 cx: &CodegenCx<'ll, 'tcx>,
2022 enum_type: Ty<'tcx>,
2024 unique_type_id: UniqueTypeId,
2025 outer_field_tys: Vec<Ty<'tcx>>,
2026 ) -> RecursiveTypeDescription<'ll, 'tcx> {
2028 let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
2030 let containing_scope = get_namespace_for_item(cx, enum_def_id);
2031 // FIXME: This should emit actual file metadata for the enum, but we
2032 // currently can't get the necessary information when it comes to types
2033 // imported from other crates. Formerly we violated the ODR when performing
2034 // LTO because we emitted debuginfo for the same type with varying file
2035 // metadata, so as a workaround we pretend that the type comes from
2037 let file_metadata = unknown_file_metadata(cx);
2039 let discriminant_type_metadata = |discr: Primitive| {
2040 let enumerators_metadata: Vec<_> = match enum_type.kind() {
2041 ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
2042 .map(|((_, discr), v)| {
2043 let name = v.name.as_str();
2044 let is_unsigned = match discr.ty.kind() {
2045 ty::Int(_) => false,
2046 ty::Uint(_) => true,
2047 _ => bug!("non integer discriminant"),
2050 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2052 name.as_ptr().cast(),
2054 // FIXME: what if enumeration has i128 discriminant?
2061 ty::Generator(_, substs, _) => substs
2063 .variant_range(enum_def_id, tcx)
2064 .map(|variant_index| {
2065 debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2066 let name = GeneratorSubsts::variant_name(variant_index);
2068 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2070 name.as_ptr().cast(),
2072 // Generators use u32 as discriminant type, verified above.
2073 variant_index.as_u32().into(),
2082 let disr_type_key = (enum_def_id, discr);
2083 let cached_discriminant_type_metadata =
2084 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2085 match cached_discriminant_type_metadata {
2086 Some(discriminant_type_metadata) => discriminant_type_metadata,
2088 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2089 let discriminant_base_type_metadata = type_metadata(cx, discr.to_ty(tcx));
2092 let discriminant_name = match enum_type.kind() {
2094 item_name = tcx.item_name(enum_def_id);
2097 ty::Generator(..) => enum_name.as_str(),
2101 let discriminant_type_metadata = unsafe {
2102 llvm::LLVMRustDIBuilderCreateEnumerationType(
2105 discriminant_name.as_ptr().cast(),
2106 discriminant_name.len(),
2108 UNKNOWN_LINE_NUMBER,
2109 discriminant_size.bits(),
2110 discriminant_align.abi.bits() as u32,
2111 create_DIArray(DIB(cx), &enumerators_metadata),
2112 discriminant_base_type_metadata,
2118 .created_enum_disr_types
2120 .insert(disr_type_key, discriminant_type_metadata);
2122 discriminant_type_metadata
2127 let layout = cx.layout_of(enum_type);
2129 if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2130 (layout.abi, &layout.variants)
2132 return FinalMetadata(discriminant_type_metadata(tag.value));
2135 // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
2136 // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
2137 // msvc, then we need to use a different encoding of the debuginfo.
2138 if cpp_like_debuginfo(tcx) {
2139 let discriminant_type_metadata = match layout.variants {
2140 Variants::Single { .. } => None,
2141 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2142 | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2143 Some(discriminant_type_metadata(tag.value))
2147 let enum_metadata = {
2148 let type_map = debug_context(cx).type_map.borrow();
2149 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2152 llvm::LLVMRustDIBuilderCreateUnionType(
2155 enum_name.as_ptr().cast(),
2158 UNKNOWN_LINE_NUMBER,
2160 layout.align.abi.bits() as u32,
2164 unique_type_id_str.as_ptr().cast(),
2165 unique_type_id_str.len(),
2170 return create_and_register_recursive_type_forward_declaration(
2176 EnumMDF(EnumMemberDescriptionFactory {
2179 tag_type_metadata: discriminant_type_metadata,
2180 common_members: vec![],
2185 let discriminator_name = match enum_type.kind() {
2186 ty::Generator(..) => "__state",
2189 let discriminator_metadata = match layout.variants {
2190 // A single-variant enum has no discriminant.
2191 Variants::Single { .. } => None,
2193 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2194 // Find the integer type of the correct size.
2195 let size = tag.value.size(cx);
2196 let align = tag.value.align(cx);
2198 let tag_type = match tag.value {
2200 F32 => Integer::I32,
2201 F64 => Integer::I64,
2202 Pointer => cx.data_layout().ptr_sized_integer(),
2204 .to_ty(cx.tcx, false);
2206 let tag_metadata = basic_type_metadata(cx, tag_type);
2208 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2211 discriminator_name.as_ptr().cast(),
2212 discriminator_name.len(),
2214 UNKNOWN_LINE_NUMBER,
2216 align.abi.bits() as u32,
2217 layout.fields.offset(tag_field).bits(),
2218 DIFlags::FlagArtificial,
2224 Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2225 let discr_type = tag.value.to_ty(cx.tcx);
2226 let (size, align) = cx.size_and_align_of(discr_type);
2228 let discr_metadata = basic_type_metadata(cx, discr_type);
2230 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2233 discriminator_name.as_ptr().cast(),
2234 discriminator_name.len(),
2236 UNKNOWN_LINE_NUMBER,
2238 align.bits() as u32,
2239 layout.fields.offset(tag_field).bits(),
2240 DIFlags::FlagArtificial,
2247 let outer_fields = match layout.variants {
2248 Variants::Single { .. } => vec![],
2249 Variants::Multiple { .. } => {
2251 TupleMemberDescriptionFactory { ty: enum_type, component_types: outer_field_tys };
2253 .create_member_descriptions(cx)
2255 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2260 let variant_part_unique_type_id_str = debug_context(cx)
2263 .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2264 let empty_array = create_DIArray(DIB(cx), &[]);
2266 let variant_part = unsafe {
2267 llvm::LLVMRustDIBuilderCreateVariantPart(
2270 name.as_ptr().cast(),
2273 UNKNOWN_LINE_NUMBER,
2275 layout.align.abi.bits() as u32,
2277 discriminator_metadata,
2279 variant_part_unique_type_id_str.as_ptr().cast(),
2280 variant_part_unique_type_id_str.len(),
2284 let struct_wrapper = {
2285 // The variant part must be wrapped in a struct according to DWARF.
2286 // All fields except the discriminant (including `outer_fields`)
2287 // should be put into structures inside the variant part, which gives
2288 // an equivalent layout but offers us much better integration with
2290 let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2292 let type_map = debug_context(cx).type_map.borrow();
2293 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2296 llvm::LLVMRustDIBuilderCreateStructType(
2298 Some(containing_scope),
2299 enum_name.as_ptr().cast(),
2302 UNKNOWN_LINE_NUMBER,
2304 layout.align.abi.bits() as u32,
2310 unique_type_id_str.as_ptr().cast(),
2311 unique_type_id_str.len(),
2316 create_and_register_recursive_type_forward_declaration(
2322 EnumMDF(EnumMemberDescriptionFactory {
2325 tag_type_metadata: None,
2326 common_members: outer_fields,
2331 /// Creates debug information for a composite type, that is, anything that
2332 /// results in a LLVM struct.
2334 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2335 fn composite_type_metadata<'ll, 'tcx>(
2336 cx: &CodegenCx<'ll, 'tcx>,
2337 composite_type: Ty<'tcx>,
2338 composite_type_name: &str,
2339 composite_type_unique_id: UniqueTypeId,
2340 member_descriptions: Vec<MemberDescription<'ll>>,
2341 containing_scope: Option<&'ll DIScope>,
2342 ) -> &'ll DICompositeType {
2343 let (size, align) = cx.size_and_align_of(composite_type);
2345 // Create the (empty) struct metadata node ...
2346 let composite_type_metadata = create_struct_stub(
2350 composite_type_name,
2351 composite_type_unique_id,
2357 // ... and immediately create and add the member descriptions.
2358 set_members_of_composite_type(
2360 composite_type_metadata,
2361 member_descriptions,
2363 compute_type_parameters(cx, composite_type),
2366 composite_type_metadata
2369 fn set_members_of_composite_type<'ll, 'tcx>(
2370 cx: &CodegenCx<'ll, 'tcx>,
2371 composite_type_metadata: &'ll DICompositeType,
2372 member_descriptions: Vec<MemberDescription<'ll>>,
2373 common_members: Option<&Vec<Option<&'ll DIType>>>,
2374 type_params: &'ll DIArray,
2376 // In some rare cases LLVM metadata uniquing would lead to an existing type
2377 // description being used instead of a new one created in
2378 // create_struct_stub. This would cause a hard to trace assertion in
2379 // DICompositeType::SetTypeArray(). The following check makes sure that we
2380 // get a better error message if this should happen again due to some
2383 let mut composite_types_completed =
2384 debug_context(cx).composite_types_completed.borrow_mut();
2385 if !composite_types_completed.insert(composite_type_metadata) {
2387 "debuginfo::set_members_of_composite_type() - \
2388 Already completed forward declaration re-encountered."
2393 let mut member_metadata: Vec<_> = member_descriptions
2395 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2397 if let Some(other_members) = common_members {
2398 member_metadata.extend(other_members.iter());
2402 let field_array = create_DIArray(DIB(cx), &member_metadata);
2403 llvm::LLVMRustDICompositeTypeReplaceArrays(
2405 composite_type_metadata,
2412 /// Computes the type parameters for a type, if any, for the given metadata.
2413 fn compute_type_parameters<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2414 if let ty::Adt(def, substs) = *ty.kind() {
2415 if substs.types().next().is_some() {
2416 let generics = cx.tcx.generics_of(def.did);
2417 let names = get_parameter_names(cx, generics);
2418 let template_params: Vec<_> = iter::zip(substs, names)
2419 .filter_map(|(kind, name)| {
2420 if let GenericArgKind::Type(ty) = kind.unpack() {
2422 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2423 let actual_type_metadata = type_metadata(cx, actual_type);
2424 let name = name.as_str();
2426 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2429 name.as_ptr().cast(),
2431 actual_type_metadata,
2440 return create_DIArray(DIB(cx), &template_params);
2443 return create_DIArray(DIB(cx), &[]);
2445 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2446 let mut names = generics
2448 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2449 names.extend(generics.params.iter().map(|param| param.name));
2454 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2455 /// any caching, does not add any fields to the struct. This can be done later
2456 /// with `set_members_of_composite_type()`.
2457 fn create_struct_stub<'ll, 'tcx>(
2458 cx: &CodegenCx<'ll, 'tcx>,
2462 unique_type_id: UniqueTypeId,
2463 containing_scope: Option<&'ll DIScope>,
2465 vtable_holder: Option<&'ll DIType>,
2466 ) -> &'ll DICompositeType {
2467 let type_map = debug_context(cx).type_map.borrow();
2468 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2470 let metadata_stub = unsafe {
2471 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2472 // pointer will lead to hard to trace and debug LLVM assertions
2473 // later on in `llvm/lib/IR/Value.cpp`.
2474 let empty_array = create_DIArray(DIB(cx), &[]);
2476 llvm::LLVMRustDIBuilderCreateStructType(
2479 type_name.as_ptr().cast(),
2481 unknown_file_metadata(cx),
2482 UNKNOWN_LINE_NUMBER,
2484 align.bits() as u32,
2490 unique_type_id.as_ptr().cast(),
2491 unique_type_id.len(),
2498 fn create_union_stub<'ll, 'tcx>(
2499 cx: &CodegenCx<'ll, 'tcx>,
2500 union_type: Ty<'tcx>,
2501 union_type_name: &str,
2502 unique_type_id: UniqueTypeId,
2503 containing_scope: &'ll DIScope,
2504 ) -> &'ll DICompositeType {
2505 let (union_size, union_align) = cx.size_and_align_of(union_type);
2507 let type_map = debug_context(cx).type_map.borrow();
2508 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2510 let metadata_stub = unsafe {
2511 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2512 // pointer will lead to hard to trace and debug LLVM assertions
2513 // later on in `llvm/lib/IR/Value.cpp`.
2514 let empty_array = create_DIArray(DIB(cx), &[]);
2516 llvm::LLVMRustDIBuilderCreateUnionType(
2518 Some(containing_scope),
2519 union_type_name.as_ptr().cast(),
2520 union_type_name.len(),
2521 unknown_file_metadata(cx),
2522 UNKNOWN_LINE_NUMBER,
2524 union_align.bits() as u32,
2528 unique_type_id.as_ptr().cast(),
2529 unique_type_id.len(),
2536 /// Creates debug information for the given global variable.
2538 /// Adds the created metadata nodes directly to the crate's IR.
2539 pub fn create_global_var_metadata<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2540 if cx.dbg_cx.is_none() {
2544 // Only create type information if full debuginfo is enabled
2545 if cx.sess().opts.debuginfo != DebugInfo::Full {
2551 // We may want to remove the namespace scope if we're in an extern block (see
2552 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2553 let var_scope = get_namespace_for_item(cx, def_id);
2554 let span = tcx.def_span(def_id);
2556 let (file_metadata, line_number) = if !span.is_dummy() {
2557 let loc = cx.lookup_debug_loc(span.lo());
2558 (file_metadata(cx, &loc.file), loc.line)
2560 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2563 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2564 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2565 let type_metadata = type_metadata(cx, variable_type);
2566 let var_name = tcx.item_name(def_id);
2567 let var_name = var_name.as_str();
2568 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2569 // When empty, linkage_name field is omitted,
2570 // which is what we want for no_mangle statics
2571 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2573 let global_align = cx.align_of(variable_type);
2576 llvm::LLVMRustDIBuilderCreateStaticVariable(
2579 var_name.as_ptr().cast(),
2581 linkage_name.as_ptr().cast(),
2589 global_align.bytes() as u32,
2594 /// Generates LLVM debuginfo for a vtable.
2596 /// The vtable type looks like a struct with a field for each function pointer and super-trait
2597 /// pointer it contains (plus the `size` and `align` fields).
2599 /// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
2600 /// the name of the method they implement. This can be implemented in the future once there
2601 /// is a proper disambiguation scheme for dealing with methods from different traits that have
2603 fn vtable_type_metadata<'ll, 'tcx>(
2604 cx: &CodegenCx<'ll, 'tcx>,
2606 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2610 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2611 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2612 let trait_ref = tcx.erase_regions(trait_ref);
2614 tcx.vtable_entries(trait_ref)
2616 COMMON_VTABLE_ENTRIES
2619 // All function pointers are described as opaque pointers. This could be improved in the future
2620 // by describing them as actual function pointers.
2621 let void_pointer_ty = tcx.mk_imm_ptr(tcx.types.unit);
2622 let void_pointer_type_debuginfo = type_metadata(cx, void_pointer_ty);
2623 let usize_debuginfo = type_metadata(cx, tcx.types.usize);
2624 let (pointer_size, pointer_align) = cx.size_and_align_of(void_pointer_ty);
2625 // If `usize` is not pointer-sized and -aligned then the size and alignment computations
2626 // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
2628 assert_eq!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
2630 let vtable_type_name =
2631 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
2632 let unique_type_id = debug_context(cx)
2635 .get_unique_type_id_of_vtable_type(&vtable_type_name);
2636 let size = pointer_size * vtable_entries.len() as u64;
2638 // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
2639 // the vtable to the type it is for.
2640 let vtable_holder = type_metadata(cx, ty);
2642 let vtable_type_metadata = create_struct_stub(
2649 DIFlags::FlagArtificial,
2650 Some(vtable_holder),
2653 // Create a field for each entry in the vtable.
2654 let fields: Vec<_> = vtable_entries
2657 .filter_map(|(index, vtable_entry)| {
2658 let (field_name, field_type) = match vtable_entry {
2659 ty::VtblEntry::MetadataDropInPlace => {
2660 ("drop_in_place".to_string(), void_pointer_type_debuginfo)
2662 ty::VtblEntry::Method(_) => {
2663 // Note: This code does not try to give a proper name to each method
2664 // because there might be multiple methods with the same name
2665 // (coming from different traits).
2666 (format!("__method{}", index), void_pointer_type_debuginfo)
2668 ty::VtblEntry::TraitVPtr(_) => {
2669 // Note: In the future we could try to set the type of this pointer
2670 // to the type that we generate for the corresponding vtable.
2671 (format!("__super_trait_ptr{}", index), void_pointer_type_debuginfo)
2673 ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_debuginfo),
2674 ty::VtblEntry::MetadataSize => ("size".to_string(), usize_debuginfo),
2675 ty::VtblEntry::Vacant => return None,
2678 Some(MemberDescription {
2680 type_metadata: field_type,
2681 offset: pointer_size * index as u64,
2683 align: pointer_align,
2684 flags: DIFlags::FlagZero,
2691 let type_params = create_DIArray(DIB(cx), &[]);
2692 set_members_of_composite_type(cx, vtable_type_metadata, fields, None, type_params);
2693 vtable_type_metadata
2696 /// Creates debug information for the given vtable, which is for the
2699 /// Adds the created metadata nodes directly to the crate's IR.
2700 pub fn create_vtable_metadata<'ll, 'tcx>(
2701 cx: &CodegenCx<'ll, 'tcx>,
2703 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2706 if cx.dbg_cx.is_none() {
2710 // Only create type information if full debuginfo is enabled
2711 if cx.sess().opts.debuginfo != DebugInfo::Full {
2716 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
2717 let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2718 let linkage_name = "";
2721 llvm::LLVMRustDIBuilderCreateStaticVariable(
2724 vtable_name.as_ptr().cast(),
2726 linkage_name.as_ptr().cast(),
2728 unknown_file_metadata(cx),
2729 UNKNOWN_LINE_NUMBER,
2739 /// Creates an "extension" of an existing `DIScope` into another file.
2740 pub fn extend_scope_to_file<'ll>(
2741 cx: &CodegenCx<'ll, '_>,
2742 scope_metadata: &'ll DIScope,
2744 ) -> &'ll DILexicalBlock {
2745 let file_metadata = file_metadata(cx, file);
2746 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }