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;
7 create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
9 use super::CrateDebugContext;
12 use crate::common::CodegenCx;
14 use crate::llvm::debuginfo::{
15 DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
18 use crate::value::Value;
21 use rustc_codegen_ssa::traits::*;
22 use rustc_data_structures::fingerprint::Fingerprint;
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
25 use rustc_fs_util::path_to_c_string;
26 use rustc_hir::def::CtorKind;
27 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_middle::ich::NodeIdHashingMode;
30 use rustc_middle::mir::{self, GeneratorLayout};
31 use rustc_middle::ty::layout::{self, IntegerExt, PrimitiveExt, TyAndLayout};
32 use rustc_middle::ty::subst::GenericArgKind;
33 use rustc_middle::ty::Instance;
34 use rustc_middle::ty::{self, AdtKind, GeneratorSubsts, ParamEnv, Ty, TyCtxt};
35 use rustc_middle::{bug, span_bug};
36 use rustc_session::config::{self, DebugInfo};
37 use rustc_span::symbol::{Interner, Symbol};
38 use rustc_span::{self, SourceFile, SourceFileHash, Span};
39 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, LayoutOf, TagEncoding};
40 use rustc_target::abi::{Int, Pointer, F32, F64};
41 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
44 use libc::{c_longlong, c_uint};
45 use std::collections::hash_map::Entry;
46 use std::fmt::{self, Write};
47 use std::hash::{Hash, Hasher};
49 use std::path::{Path, PathBuf};
52 impl PartialEq for llvm::Metadata {
53 fn eq(&self, other: &Self) -> bool {
58 impl Eq for llvm::Metadata {}
60 impl Hash for llvm::Metadata {
61 fn hash<H: Hasher>(&self, hasher: &mut H) {
62 (self as *const Self).hash(hasher);
66 impl fmt::Debug for llvm::Metadata {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 (self as *const Self).fmt(f)
73 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
74 const DW_LANG_RUST: c_uint = 0x1c;
75 #[allow(non_upper_case_globals)]
76 const DW_ATE_boolean: c_uint = 0x02;
77 #[allow(non_upper_case_globals)]
78 const DW_ATE_float: c_uint = 0x04;
79 #[allow(non_upper_case_globals)]
80 const DW_ATE_signed: c_uint = 0x05;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_unsigned: c_uint = 0x07;
83 #[allow(non_upper_case_globals)]
84 const DW_ATE_unsigned_char: c_uint = 0x08;
86 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
87 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
89 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
91 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
92 pub struct UniqueTypeId(Symbol);
94 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
95 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
96 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
99 pub struct TypeMap<'ll, 'tcx> {
100 /// The `UniqueTypeId`s created so far.
101 unique_id_interner: Interner,
102 /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
103 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
104 /// A map from types to debuginfo metadata. This is an N:1 mapping.
105 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
106 /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
107 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
110 impl TypeMap<'ll, 'tcx> {
111 /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
112 /// the mapping already exists.
113 fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
114 if self.type_to_metadata.insert(type_, metadata).is_some() {
115 bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
119 /// Removes a `Ty`-to-metadata mapping.
120 /// This is useful when computing the metadata for a potentially
121 /// recursive type (e.g., a function pointer of the form:
123 /// fn foo() -> impl Copy { foo }
125 /// This kind of type cannot be properly represented
126 /// via LLVM debuginfo. As a workaround,
127 /// we register a temporary Ty to metadata mapping
128 /// for the function before we compute its actual metadata.
129 /// If the metadata computation ends up recursing back to the
130 /// original function, it will use the temporary mapping
131 /// for the inner self-reference, preventing us from
132 /// recursing forever.
134 /// This function is used to remove the temporary metadata
135 /// mapping after we've computed the actual metadata.
136 fn remove_type(&mut self, type_: Ty<'tcx>) {
137 if self.type_to_metadata.remove(type_).is_none() {
138 bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_);
142 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
143 /// fail if the mapping already exists.
144 fn register_unique_id_with_metadata(
146 unique_type_id: UniqueTypeId,
147 metadata: &'ll DIType,
149 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
151 "type metadata for unique ID '{}' is already in the `TypeMap`!",
152 self.get_unique_type_id_as_string(unique_type_id)
157 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
158 self.type_to_metadata.get(&type_).cloned()
161 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
162 self.unique_id_to_metadata.get(&unique_type_id).cloned()
165 /// Gets the string representation of a `UniqueTypeId`. This method will fail if
166 /// the ID is unknown.
167 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
168 let UniqueTypeId(interner_key) = unique_type_id;
169 self.unique_id_interner.get(interner_key)
172 /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
173 /// type has been requested before, this is just a table lookup. Otherwise, an
174 /// ID will be generated and stored for later lookup.
175 fn get_unique_type_id_of_type<'a>(
177 cx: &CodegenCx<'a, 'tcx>,
180 // Let's see if we already have something in the cache.
181 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
182 return unique_type_id;
184 // If not, generate one.
186 // The hasher we are using to generate the UniqueTypeId. We want
187 // something that provides more than the 64 bits of the DefaultHasher.
188 let mut hasher = StableHasher::new();
189 let mut hcx = cx.tcx.create_stable_hashing_context();
190 let type_ = cx.tcx.erase_regions(type_);
191 hcx.while_hashing_spans(false, |hcx| {
192 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
193 type_.hash_stable(hcx, &mut hasher);
196 let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
198 let key = self.unique_id_interner.intern(&unique_type_id);
199 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
204 /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
205 /// types of their own, so they need special handling. We still need a
206 /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
207 fn get_unique_type_id_of_enum_variant<'a>(
209 cx: &CodegenCx<'a, 'tcx>,
213 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
214 let enum_variant_type_id =
215 format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
216 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
217 UniqueTypeId(interner_key)
220 /// Gets the unique type ID string for an enum variant part.
221 /// Variant parts are not types and shouldn't really have their own ID,
222 /// but it makes `set_members_of_composite_type()` simpler.
223 fn get_unique_type_id_str_of_enum_variant_part(
225 enum_type_id: UniqueTypeId,
227 format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
231 /// A description of some recursive type. It can either be already finished (as
232 /// with `FinalMetadata`) or it is not yet finished, but contains all information
233 /// needed to generate the missing parts of the description. See the
234 /// documentation section on Recursive Types at the top of this file for more
236 enum RecursiveTypeDescription<'ll, 'tcx> {
238 unfinished_type: Ty<'tcx>,
239 unique_type_id: UniqueTypeId,
240 metadata_stub: &'ll DICompositeType,
241 member_holding_stub: &'ll DICompositeType,
242 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
244 FinalMetadata(&'ll DICompositeType),
247 fn create_and_register_recursive_type_forward_declaration(
248 cx: &CodegenCx<'ll, 'tcx>,
249 unfinished_type: Ty<'tcx>,
250 unique_type_id: UniqueTypeId,
251 metadata_stub: &'ll DICompositeType,
252 member_holding_stub: &'ll DICompositeType,
253 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
254 ) -> RecursiveTypeDescription<'ll, 'tcx> {
255 // Insert the stub into the `TypeMap` in order to allow for recursive references.
256 let mut type_map = debug_context(cx).type_map.borrow_mut();
257 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
258 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
265 member_description_factory,
269 impl RecursiveTypeDescription<'ll, 'tcx> {
270 /// Finishes up the description of the type in question (mostly by providing
271 /// descriptions of the fields of the given type) and returns the final type
273 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
275 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
281 ref member_description_factory,
283 // Make sure that we have a forward declaration of the type in
284 // the TypeMap so that recursive references are possible. This
285 // will always be the case if the RecursiveTypeDescription has
286 // been properly created through the
287 // `create_and_register_recursive_type_forward_declaration()`
290 let type_map = debug_context(cx).type_map.borrow();
291 if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
292 || type_map.find_metadata_for_type(unfinished_type).is_none()
295 "Forward declaration of potentially recursive type \
296 '{:?}' was not found in TypeMap!",
302 // ... then create the member descriptions ...
303 let member_descriptions = member_description_factory.create_member_descriptions(cx);
305 // ... and attach them to the stub to complete it.
306 set_members_of_composite_type(
313 MetadataCreationResult::new(metadata_stub, true)
319 /// Returns from the enclosing function if the type metadata with the given
320 /// unique ID can be found in the type map.
321 macro_rules! return_if_metadata_created_in_meantime {
322 ($cx: expr, $unique_type_id: expr) => {
323 if let Some(metadata) =
324 debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
326 return MetadataCreationResult::new(metadata, true);
331 fn fixed_vec_metadata(
332 cx: &CodegenCx<'ll, 'tcx>,
333 unique_type_id: UniqueTypeId,
334 array_or_slice_type: Ty<'tcx>,
335 element_type: Ty<'tcx>,
337 ) -> MetadataCreationResult<'ll> {
338 let element_type_metadata = type_metadata(cx, element_type, span);
340 return_if_metadata_created_in_meantime!(cx, unique_type_id);
342 let (size, align) = cx.size_and_align_of(array_or_slice_type);
344 let upper_bound = match array_or_slice_type.kind() {
345 ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong,
350 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
352 let subscripts = create_DIArray(DIB(cx), &[subrange]);
353 let metadata = unsafe {
354 llvm::LLVMRustDIBuilderCreateArrayType(
358 element_type_metadata,
363 MetadataCreationResult::new(metadata, false)
366 fn vec_slice_metadata(
367 cx: &CodegenCx<'ll, 'tcx>,
368 slice_ptr_type: Ty<'tcx>,
369 element_type: Ty<'tcx>,
370 unique_type_id: UniqueTypeId,
372 ) -> MetadataCreationResult<'ll> {
373 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
375 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
377 return_if_metadata_created_in_meantime!(cx, unique_type_id);
379 let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
381 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
382 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
384 let member_descriptions = vec![
386 name: "data_ptr".to_owned(),
387 type_metadata: data_ptr_metadata,
390 align: pointer_align,
391 flags: DIFlags::FlagZero,
396 name: "length".to_owned(),
397 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
398 offset: pointer_size,
401 flags: DIFlags::FlagZero,
407 let file_metadata = unknown_file_metadata(cx);
409 let metadata = composite_type_metadata(
412 &slice_type_name[..],
419 MetadataCreationResult::new(metadata, false)
422 fn subroutine_type_metadata(
423 cx: &CodegenCx<'ll, 'tcx>,
424 unique_type_id: UniqueTypeId,
425 signature: ty::PolyFnSig<'tcx>,
427 ) -> MetadataCreationResult<'ll> {
429 cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), signature);
431 let signature_metadata: Vec<_> = iter::once(
433 match signature.output().kind() {
434 ty::Tuple(ref tys) if tys.is_empty() => None,
435 _ => Some(type_metadata(cx, signature.output(), span)),
440 signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type, span))),
444 return_if_metadata_created_in_meantime!(cx, unique_type_id);
446 MetadataCreationResult::new(
448 llvm::LLVMRustDIBuilderCreateSubroutineType(
450 create_DIArray(DIB(cx), &signature_metadata[..]),
457 // FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill-
458 // defined concept. For the case of an actual trait pointer (i.e., `Box<Trait>`,
459 // `&Trait`), `trait_object_type` should be the whole thing (e.g, `Box<Trait>`) and
460 // `trait_type` should be the actual trait (e.g., `Trait`). Where the trait is part
461 // of a DST struct, there is no `trait_object_type` and the results of this
462 // function will be a little bit weird.
463 fn trait_pointer_metadata(
464 cx: &CodegenCx<'ll, 'tcx>,
465 trait_type: Ty<'tcx>,
466 trait_object_type: Option<Ty<'tcx>>,
467 unique_type_id: UniqueTypeId,
469 // The implementation provided here is a stub. It makes sure that the trait
470 // type is assigned the correct name, size, namespace, and source location.
471 // However, it does not describe the trait's methods.
473 let (containing_scope, trait_type_name) = match trait_object_type {
474 Some(trait_object_type) => match trait_object_type.kind() {
476 Some(get_namespace_for_item(cx, def.did)),
477 compute_debuginfo_type_name(cx.tcx, trait_object_type, false),
479 ty::RawPtr(_) | ty::Ref(..) => {
480 (NO_SCOPE_METADATA, compute_debuginfo_type_name(cx.tcx, trait_object_type, true))
484 "debuginfo: unexpected trait-object type in \
485 trait_pointer_metadata(): {:?}",
491 // No object type, use the trait type directly (no scope here since the type
492 // will be wrapped in the dyn$ synthetic type).
493 None => (NO_SCOPE_METADATA, compute_debuginfo_type_name(cx.tcx, trait_type, true)),
496 let file_metadata = unknown_file_metadata(cx);
498 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
500 assert_eq!(abi::FAT_PTR_ADDR, 0);
501 assert_eq!(abi::FAT_PTR_EXTRA, 1);
503 let data_ptr_field = layout.field(cx, 0);
504 let vtable_field = layout.field(cx, 1);
505 let member_descriptions = vec![
507 name: "pointer".to_owned(),
508 type_metadata: type_metadata(
510 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
511 rustc_span::DUMMY_SP,
513 offset: layout.fields.offset(0),
514 size: data_ptr_field.size,
515 align: data_ptr_field.align.abi,
516 flags: DIFlags::FlagArtificial,
521 name: "vtable".to_owned(),
522 type_metadata: type_metadata(cx, vtable_field.ty, rustc_span::DUMMY_SP),
523 offset: layout.fields.offset(1),
524 size: vtable_field.size,
525 align: vtable_field.align.abi,
526 flags: DIFlags::FlagArtificial,
532 composite_type_metadata(
534 trait_object_type.unwrap_or(trait_type),
535 &trait_type_name[..],
540 rustc_span::DUMMY_SP,
544 pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Span) -> &'ll DIType {
545 // Get the unique type ID of this type.
546 let unique_type_id = {
547 let mut type_map = debug_context(cx).type_map.borrow_mut();
548 // First, try to find the type in `TypeMap`. If we have seen it before, we
549 // can exit early here.
550 match type_map.find_metadata_for_type(t) {
555 // The Ty is not in the `TypeMap` but maybe we have already seen
556 // an equivalent type (e.g., only differing in region arguments).
557 // In order to find out, generate the unique type ID and look
559 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
560 match type_map.find_metadata_for_unique_id(unique_type_id) {
562 // There is already an equivalent type in the TypeMap.
563 // Register this Ty as an alias in the cache and
564 // return the cached metadata.
565 type_map.register_type_with_metadata(t, metadata);
569 // There really is no type metadata for this type, so
570 // proceed by creating it.
578 debug!("type_metadata: {:?}", t);
580 let ptr_metadata = |ty: Ty<'tcx>| match *ty.kind() {
581 ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
582 ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
583 ty::Dynamic(..) => Ok(MetadataCreationResult::new(
584 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
588 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
590 if let Some(metadata) =
591 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
593 return Err(metadata);
596 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false))
600 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
601 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
602 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
604 ty::Tuple(ref elements) if elements.is_empty() => {
605 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
607 ty::Array(typ, _) | ty::Slice(typ) => {
608 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
610 ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
612 MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
615 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
617 ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) {
619 Err(metadata) => return metadata,
621 ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) {
623 Err(metadata) => return metadata,
625 ty::FnDef(..) | ty::FnPtr(_) => {
626 if let Some(metadata) =
627 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
632 // It's possible to create a self-referential
633 // type in Rust by using 'impl trait':
635 // fn foo() -> impl Copy { foo }
637 // See `TypeMap::remove_type` for more detals
638 // about the workaround.
642 // The choice of type here is pretty arbitrary -
643 // anything reading the debuginfo for a recursive
644 // type is going to see *something* weird - the only
645 // question is what exactly it will see.
646 let name = "<recur_type>";
647 llvm::LLVMRustDIBuilderCreateBasicType(
649 name.as_ptr().cast(),
651 cx.size_of(t).bits(),
657 let type_map = &debug_context(cx).type_map;
658 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
661 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span)
664 type_map.borrow_mut().remove_type(t);
666 // This is actually a function pointer, so wrap it in pointer DI.
667 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
669 ty::Closure(def_id, substs) => {
670 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
671 let containing_scope = get_namespace_for_item(cx, def_id);
672 prepare_tuple_metadata(
678 Some(containing_scope),
682 ty::Generator(def_id, substs, _) => {
683 let upvar_tys: Vec<_> = substs
686 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
688 prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys)
691 ty::Adt(def, ..) => match def.adt_kind() {
693 prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
696 prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
699 prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![])
703 ty::Tuple(ref elements) => {
704 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
705 prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA)
708 // Type parameters from polymorphized functions.
709 ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
710 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
714 let mut type_map = debug_context(cx).type_map.borrow_mut();
716 if already_stored_in_typemap {
717 // Also make sure that we already have a `TypeMap` entry for the unique type ID.
718 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
719 Some(metadata) => metadata,
723 "expected type metadata for unique \
724 type ID '{}' to already be in \
725 the `debuginfo::TypeMap` but it \
727 type_map.get_unique_type_id_as_string(unique_type_id),
733 match type_map.find_metadata_for_type(t) {
735 if metadata != metadata_for_uid {
738 "mismatch between `Ty` and \
739 `UniqueTypeId` maps in \
740 `debuginfo::TypeMap`. \
741 UniqueTypeId={}, Ty={}",
742 type_map.get_unique_type_id_as_string(unique_type_id),
748 type_map.register_type_with_metadata(t, metadata);
752 type_map.register_type_with_metadata(t, metadata);
753 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
760 fn hex_encode(data: &[u8]) -> String {
761 let mut hex_string = String::with_capacity(data.len() * 2);
762 for byte in data.iter() {
763 write!(&mut hex_string, "{:02x}", byte).unwrap();
768 pub fn file_metadata(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
769 debug!("file_metadata: file_name: {:?}", source_file.name);
771 let hash = Some(&source_file.src_hash);
772 let file_name = Some(source_file.name.prefer_remapped().to_string());
773 let directory = if source_file.is_real_file() && !source_file.is_imported() {
774 Some(cx.sess().working_dir.to_string_lossy(false).to_string())
776 // If the path comes from an upstream crate we assume it has been made
777 // independent of the compiler's working directory one way or another.
780 file_metadata_raw(cx, file_name, directory, hash)
783 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
784 file_metadata_raw(cx, None, None, None)
787 fn file_metadata_raw(
788 cx: &CodegenCx<'ll, '_>,
789 file_name: Option<String>,
790 directory: Option<String>,
791 hash: Option<&SourceFileHash>,
793 let key = (file_name, directory);
795 match debug_context(cx).created_files.borrow_mut().entry(key) {
796 Entry::Occupied(o) => o.get(),
797 Entry::Vacant(v) => {
798 let (file_name, directory) = v.key();
799 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
801 let file_name = file_name.as_deref().unwrap_or("<unknown>");
802 let directory = directory.as_deref().unwrap_or("");
804 let (hash_kind, hash_value) = match hash {
806 let kind = match hash.kind {
807 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
808 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
809 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
811 (kind, hex_encode(hash.hash_bytes()))
813 None => (llvm::ChecksumKind::None, String::new()),
816 let file_metadata = unsafe {
817 llvm::LLVMRustDIBuilderCreateFile(
819 file_name.as_ptr().cast(),
821 directory.as_ptr().cast(),
824 hash_value.as_ptr().cast(),
829 v.insert(file_metadata);
835 trait MsvcBasicName {
836 fn msvc_basic_name(self) -> &'static str;
839 impl MsvcBasicName for ty::IntTy {
840 fn msvc_basic_name(self) -> &'static str {
842 ty::IntTy::Isize => "ptrdiff_t",
843 ty::IntTy::I8 => "__int8",
844 ty::IntTy::I16 => "__int16",
845 ty::IntTy::I32 => "__int32",
846 ty::IntTy::I64 => "__int64",
847 ty::IntTy::I128 => "__int128",
852 impl MsvcBasicName for ty::UintTy {
853 fn msvc_basic_name(self) -> &'static str {
855 ty::UintTy::Usize => "size_t",
856 ty::UintTy::U8 => "unsigned __int8",
857 ty::UintTy::U16 => "unsigned __int16",
858 ty::UintTy::U32 => "unsigned __int32",
859 ty::UintTy::U64 => "unsigned __int64",
860 ty::UintTy::U128 => "unsigned __int128",
865 impl MsvcBasicName for ty::FloatTy {
866 fn msvc_basic_name(self) -> &'static str {
868 ty::FloatTy::F32 => "float",
869 ty::FloatTy::F64 => "double",
874 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
875 debug!("basic_type_metadata: {:?}", t);
877 // When targeting MSVC, emit MSVC style type names for compatibility with
878 // .natvis visualizers (and perhaps other existing native debuggers?)
879 let msvc_like_names = cx.tcx.sess.target.is_like_msvc;
881 let (name, encoding) = match t.kind() {
882 ty::Never => ("!", DW_ATE_unsigned),
883 ty::Tuple(ref elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
884 ty::Bool => ("bool", DW_ATE_boolean),
885 ty::Char => ("char", DW_ATE_unsigned_char),
886 ty::Int(int_ty) if msvc_like_names => (int_ty.msvc_basic_name(), DW_ATE_signed),
887 ty::Uint(uint_ty) if msvc_like_names => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
888 ty::Float(float_ty) if msvc_like_names => (float_ty.msvc_basic_name(), DW_ATE_float),
889 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
890 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
891 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
892 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
895 let ty_metadata = unsafe {
896 llvm::LLVMRustDIBuilderCreateBasicType(
898 name.as_ptr().cast(),
900 cx.size_of(t).bits(),
905 if !msvc_like_names {
909 let typedef_name = match t.kind() {
910 ty::Int(int_ty) => int_ty.name_str(),
911 ty::Uint(uint_ty) => uint_ty.name_str(),
912 ty::Float(float_ty) => float_ty.name_str(),
913 _ => return ty_metadata,
916 let typedef_metadata = unsafe {
917 llvm::LLVMRustDIBuilderCreateTypedef(
920 typedef_name.as_ptr().cast(),
922 unknown_file_metadata(cx),
931 fn foreign_type_metadata(
932 cx: &CodegenCx<'ll, 'tcx>,
934 unique_type_id: UniqueTypeId,
936 debug!("foreign_type_metadata: {:?}", t);
938 let name = compute_debuginfo_type_name(cx.tcx, t, false);
939 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA, DIFlags::FlagZero)
942 fn pointer_type_metadata(
943 cx: &CodegenCx<'ll, 'tcx>,
944 pointer_type: Ty<'tcx>,
945 pointee_type_metadata: &'ll DIType,
947 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
948 let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
950 llvm::LLVMRustDIBuilderCreatePointerType(
952 pointee_type_metadata,
954 pointer_align.bits() as u32,
955 0, // Ignore DWARF address space.
956 name.as_ptr().cast(),
962 fn param_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
963 debug!("param_type_metadata: {:?}", t);
964 let name = format!("{:?}", t);
966 llvm::LLVMRustDIBuilderCreateBasicType(
968 name.as_ptr().cast(),
976 pub fn compile_unit_metadata(
978 codegen_unit_name: &str,
979 debug_context: &CrateDebugContext<'ll, '_>,
980 ) -> &'ll DIDescriptor {
981 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
982 Some(ref path) => path.clone(),
983 None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
986 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
987 // if multiple object files with the same `DW_AT_name` are linked together.
988 // As a workaround we generate unique names for each object file. Those do
989 // not correspond to an actual source file but that is harmless.
990 if tcx.sess.target.is_like_osx {
991 name_in_debuginfo.push("@");
992 name_in_debuginfo.push(codegen_unit_name);
995 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
997 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
998 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
999 let producer = format!("clang LLVM ({})", rustc_producer);
1001 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1002 let work_dir = tcx.sess.working_dir.to_string_lossy(false);
1004 let output_filenames = tcx.output_filenames(());
1005 let out_dir = &output_filenames.out_directory;
1006 let split_name = if tcx.sess.target_can_use_split_dwarf() {
1008 .split_dwarf_path(tcx.sess.split_debuginfo(), Some(codegen_unit_name))
1009 .map(|f| out_dir.join(f))
1013 .unwrap_or_default();
1014 let split_name = split_name.to_str().unwrap();
1018 // This should actually be
1020 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1022 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
1023 // we are compiling with "limited" debuginfo. However, some of the
1024 // existing tools relied on slightly more debuginfo being generated than
1025 // would be the case with `LineTablesOnly`, and we did not want to break
1026 // these tools in a "drive-by fix", without a good idea or plan about
1027 // what limited debuginfo should exactly look like. So for now we keep
1028 // the emission kind as `FullDebug`.
1030 // See https://github.com/rust-lang/rust/issues/60020 for details.
1031 let kind = DebugEmissionKind::FullDebug;
1032 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1035 let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1036 debug_context.builder,
1037 name_in_debuginfo.as_ptr().cast(),
1038 name_in_debuginfo.len(),
1039 work_dir.as_ptr().cast(),
1041 llvm::ChecksumKind::None,
1046 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1047 debug_context.builder,
1050 producer.as_ptr().cast(),
1052 tcx.sess.opts.optimize != config::OptLevel::No,
1053 flags.as_ptr().cast(),
1055 // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1056 // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1058 split_name.as_ptr().cast(),
1062 tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1065 if tcx.sess.opts.debugging_opts.profile {
1066 let cu_desc_metadata =
1067 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1068 let default_gcda_path = &output_filenames.with_extension("gcda");
1070 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1072 let gcov_cu_info = [
1073 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1074 path_to_mdstring(debug_context.llcontext, &gcda_path),
1077 let gcov_metadata = llvm::LLVMMDNodeInContext(
1078 debug_context.llcontext,
1079 gcov_cu_info.as_ptr(),
1080 gcov_cu_info.len() as c_uint,
1083 let llvm_gcov_ident = cstr!("llvm.gcov");
1084 llvm::LLVMAddNamedMetadataOperand(
1085 debug_context.llmod,
1086 llvm_gcov_ident.as_ptr(),
1091 // Insert `llvm.ident` metadata on the wasm targets since that will
1092 // get hooked up to the "producer" sections `processed-by` information.
1093 if tcx.sess.target.is_like_wasm {
1094 let name_metadata = llvm::LLVMMDStringInContext(
1095 debug_context.llcontext,
1096 rustc_producer.as_ptr().cast(),
1097 rustc_producer.as_bytes().len() as c_uint,
1099 llvm::LLVMAddNamedMetadataOperand(
1100 debug_context.llmod,
1101 cstr!("llvm.ident").as_ptr(),
1102 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1106 return unit_metadata;
1109 fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1110 let path_str = path_to_c_string(path);
1112 llvm::LLVMMDStringInContext(
1115 path_str.as_bytes().len() as c_uint,
1121 struct MetadataCreationResult<'ll> {
1122 metadata: &'ll DIType,
1123 already_stored_in_typemap: bool,
1126 impl MetadataCreationResult<'ll> {
1127 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1128 MetadataCreationResult { metadata, already_stored_in_typemap }
1133 struct SourceInfo<'ll> {
1138 /// Description of a type member, which can either be a regular field (as in
1139 /// structs or tuples) or an enum variant.
1141 struct MemberDescription<'ll> {
1143 type_metadata: &'ll DIType,
1148 discriminant: Option<u64>,
1149 source_info: Option<SourceInfo<'ll>>,
1152 impl<'ll> MemberDescription<'ll> {
1155 cx: &CodegenCx<'ll, '_>,
1156 composite_type_metadata: &'ll DIScope,
1158 let (file, line) = self
1160 .map(|info| (info.file, info.line))
1161 .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1163 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1165 composite_type_metadata,
1166 self.name.as_ptr().cast(),
1171 self.align.bits() as u32,
1173 self.discriminant.map(|v| cx.const_u64(v)),
1181 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1182 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1183 /// creation of type member descriptions in order to break cycles arising from
1184 /// recursive type definitions.
1185 enum MemberDescriptionFactory<'ll, 'tcx> {
1186 StructMDF(StructMemberDescriptionFactory<'tcx>),
1187 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1188 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1189 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1190 VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1193 impl MemberDescriptionFactory<'ll, 'tcx> {
1194 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1196 StructMDF(ref this) => this.create_member_descriptions(cx),
1197 TupleMDF(ref this) => this.create_member_descriptions(cx),
1198 EnumMDF(ref this) => this.create_member_descriptions(cx),
1199 UnionMDF(ref this) => this.create_member_descriptions(cx),
1200 VariantMDF(ref this) => this.create_member_descriptions(cx),
1205 //=-----------------------------------------------------------------------------
1207 //=-----------------------------------------------------------------------------
1209 /// Creates `MemberDescription`s for the fields of a struct.
1210 struct StructMemberDescriptionFactory<'tcx> {
1212 variant: &'tcx ty::VariantDef,
1216 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1217 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1218 let layout = cx.layout_of(self.ty);
1224 let name = if self.variant.ctor_kind == CtorKind::Fn {
1229 let field = layout.field(cx, i);
1232 type_metadata: type_metadata(cx, field.ty, self.span),
1233 offset: layout.fields.offset(i),
1235 align: field.align.abi,
1236 flags: DIFlags::FlagZero,
1245 fn prepare_struct_metadata(
1246 cx: &CodegenCx<'ll, 'tcx>,
1247 struct_type: Ty<'tcx>,
1248 unique_type_id: UniqueTypeId,
1250 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1251 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1253 let (struct_def_id, variant) = match struct_type.kind() {
1254 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1255 _ => bug!("prepare_struct_metadata on a non-ADT"),
1258 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1260 let struct_metadata_stub = create_struct_stub(
1265 Some(containing_scope),
1269 create_and_register_recursive_type_forward_declaration(
1273 struct_metadata_stub,
1274 struct_metadata_stub,
1275 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }),
1279 //=-----------------------------------------------------------------------------
1281 //=-----------------------------------------------------------------------------
1283 /// Returns names of captured upvars for closures and generators.
1285 /// Here are some examples:
1286 /// - `name__field1__field2` when the upvar is captured by value.
1287 /// - `_ref__name__field` when the upvar is captured by reference.
1288 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<String> {
1289 let body = tcx.optimized_mir(def_id);
1294 let is_ref = match var.value {
1295 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1296 // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1297 // implies whether the variable is captured by value or by reference.
1298 matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1302 let prefix = if is_ref { "_ref__" } else { "" };
1303 Some(prefix.to_owned() + &var.name.as_str())
1305 .collect::<Vec<_>>()
1308 /// Creates `MemberDescription`s for the fields of a tuple.
1309 struct TupleMemberDescriptionFactory<'tcx> {
1311 component_types: Vec<Ty<'tcx>>,
1315 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1316 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1317 let mut capture_names = match *self.ty.kind() {
1318 ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1319 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1323 let layout = cx.layout_of(self.ty);
1324 self.component_types
1327 .map(|(i, &component_type)| {
1328 let (size, align) = cx.size_and_align_of(component_type);
1329 let name = if let Some(names) = capture_names.as_mut() {
1330 names.next().unwrap()
1336 type_metadata: type_metadata(cx, component_type, self.span),
1337 offset: layout.fields.offset(i),
1340 flags: DIFlags::FlagZero,
1349 fn prepare_tuple_metadata(
1350 cx: &CodegenCx<'ll, 'tcx>,
1351 tuple_type: Ty<'tcx>,
1352 component_types: &[Ty<'tcx>],
1353 unique_type_id: UniqueTypeId,
1355 containing_scope: Option<&'ll DIScope>,
1356 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1357 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1359 let struct_stub = create_struct_stub(
1368 create_and_register_recursive_type_forward_declaration(
1374 TupleMDF(TupleMemberDescriptionFactory {
1376 component_types: component_types.to_vec(),
1382 //=-----------------------------------------------------------------------------
1384 //=-----------------------------------------------------------------------------
1386 struct UnionMemberDescriptionFactory<'tcx> {
1387 layout: TyAndLayout<'tcx>,
1388 variant: &'tcx ty::VariantDef,
1392 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1393 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1399 let field = self.layout.field(cx, i);
1401 name: f.ident.to_string(),
1402 type_metadata: type_metadata(cx, field.ty, self.span),
1405 align: field.align.abi,
1406 flags: DIFlags::FlagZero,
1415 fn prepare_union_metadata(
1416 cx: &CodegenCx<'ll, 'tcx>,
1417 union_type: Ty<'tcx>,
1418 unique_type_id: UniqueTypeId,
1420 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1421 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1423 let (union_def_id, variant) = match union_type.kind() {
1424 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1425 _ => bug!("prepare_union_metadata on a non-ADT"),
1428 let containing_scope = get_namespace_for_item(cx, union_def_id);
1430 let union_metadata_stub =
1431 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1433 create_and_register_recursive_type_forward_declaration(
1437 union_metadata_stub,
1438 union_metadata_stub,
1439 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }),
1443 //=-----------------------------------------------------------------------------
1445 //=-----------------------------------------------------------------------------
1447 /// DWARF variant support is only available starting in LLVM 8, but
1448 /// on MSVC we have to use the fallback mode, because LLVM doesn't
1449 /// lower variant parts to PDB.
1450 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1451 cx.sess().target.is_like_msvc
1454 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1455 // per generator monomorphization, but it doesn't depend on substs.
1456 fn generator_layout_and_saved_local_names(
1459 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1460 let body = tcx.optimized_mir(def_id);
1461 let generator_layout = body.generator_layout().unwrap();
1462 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1464 let state_arg = mir::Local::new(1);
1465 for var in &body.var_debug_info {
1466 let place = if let mir::VarDebugInfoContents::Place(p) = var.value { p } else { continue };
1467 if place.local != state_arg {
1470 match place.projection[..] {
1472 // Deref of the `Pin<&mut Self>` state argument.
1473 mir::ProjectionElem::Field(..),
1474 mir::ProjectionElem::Deref,
1476 // Field of a variant of the state.
1477 mir::ProjectionElem::Downcast(_, variant),
1478 mir::ProjectionElem::Field(field, _),
1480 let name = &mut generator_saved_local_names[
1481 generator_layout.variant_fields[variant][field]
1484 name.replace(var.name);
1490 (generator_layout, generator_saved_local_names)
1493 /// Describes the members of an enum value; an enum is described as a union of
1494 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1495 /// the members of this union; so for every variant of the given enum, this
1496 /// factory will produce one `MemberDescription` (all with no name and a fixed
1497 /// offset of zero bytes).
1498 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1499 enum_type: Ty<'tcx>,
1500 layout: TyAndLayout<'tcx>,
1501 tag_type_metadata: Option<&'ll DIType>,
1502 common_members: Vec<Option<&'ll DIType>>,
1506 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1507 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1508 let generator_variant_info_data = match *self.enum_type.kind() {
1509 ty::Generator(def_id, ..) => {
1510 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1515 let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1516 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1517 ty::Generator(def_id, _, _) => {
1518 let (generator_layout, generator_saved_local_names) =
1519 generator_variant_info_data.as_ref().unwrap();
1520 VariantInfo::Generator {
1522 generator_layout: *generator_layout,
1523 generator_saved_local_names,
1524 variant_index: index,
1530 let fallback = use_enum_fallback(cx);
1531 // This will always find the metadata in the type map.
1532 let self_metadata = type_metadata(cx, self.enum_type, self.span);
1534 match self.layout.variants {
1535 Variants::Single { index } => {
1536 if let ty::Adt(adt, _) = self.enum_type.kind() {
1537 if adt.variants.is_empty() {
1542 let variant_info = variant_info_for(index);
1543 let (variant_type_metadata, member_description_factory) =
1544 describe_enum_variant(cx, self.layout, variant_info, self_metadata, self.span);
1546 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1548 set_members_of_composite_type(
1551 variant_type_metadata,
1552 member_descriptions,
1553 Some(&self.common_members),
1555 vec![MemberDescription {
1556 name: variant_info.variant_name(),
1557 type_metadata: variant_type_metadata,
1559 size: self.layout.size,
1560 align: self.layout.align.abi,
1561 flags: DIFlags::FlagZero,
1563 source_info: variant_info.source_info(cx),
1566 Variants::Multiple {
1567 tag_encoding: TagEncoding::Direct,
1572 let fallback_discr_variant = if fallback {
1573 // For MSVC, we generate a union of structs for each variant and an
1574 // explicit discriminant field roughly equivalent to the following C:
1576 // union enum$<{name}> {
1577 // struct {variant 0 name} {
1578 // <variant 0 fields>
1580 // <other variant structs>
1581 // {name} discriminant;
1584 // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1585 // determine which variant is active and then displays it.
1586 let enum_layout = self.layout;
1587 let offset = enum_layout.fields.offset(tag_field);
1588 let discr_ty = enum_layout.field(cx, tag_field).ty;
1589 let (size, align) = cx.size_and_align_of(discr_ty);
1590 Some(MemberDescription {
1591 name: "discriminant".into(),
1592 type_metadata: self.tag_type_metadata.unwrap(),
1596 flags: DIFlags::FlagZero,
1607 let variant = self.layout.for_variant(cx, i);
1608 let variant_info = variant_info_for(i);
1609 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1617 let member_descriptions =
1618 member_desc_factory.create_member_descriptions(cx);
1620 set_members_of_composite_type(
1623 variant_type_metadata,
1624 member_descriptions,
1625 Some(&self.common_members),
1630 format!("variant{}", i.as_u32())
1632 variant_info.variant_name()
1634 type_metadata: variant_type_metadata,
1636 size: self.layout.size,
1637 align: self.layout.align.abi,
1638 flags: DIFlags::FlagZero,
1640 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1643 source_info: variant_info.source_info(cx),
1646 .chain(fallback_discr_variant.into_iter())
1649 Variants::Multiple {
1651 TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1656 let calculate_niche_value = |i: VariantIdx| {
1657 if i == dataful_variant {
1660 let value = (i.as_u32() as u128)
1661 .wrapping_sub(niche_variants.start().as_u32() as u128)
1662 .wrapping_add(niche_start);
1663 let value = tag.value.size(cx).truncate(value);
1664 // NOTE(eddyb) do *NOT* remove this assert, until
1665 // we pass the full 128-bit value to LLVM, otherwise
1666 // truncation will be silent and remain undetected.
1667 assert_eq!(value as u64 as u128, value);
1672 // For MSVC, we will generate a union of two fields, one for the dataful variant
1673 // and one that just points to the discriminant. We also create an enum that
1674 // contains tag values for the non-dataful variants and make the discriminant field
1675 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1676 // This will generate debuginfo roughly equivalent to the following C:
1678 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1679 // struct <dataful variant name> {
1680 // <fields in dataful variant>
1681 // } dataful_variant;
1682 // enum Discriminant$ {
1683 // <non-dataful variants>
1687 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1688 // and evaluates `this.discriminant`. If the value is between the min niche and max
1689 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1690 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1691 // case, we just need to render the name of the `this.discriminant` enum.
1693 let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1695 let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1696 // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1697 // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1698 // to just be `usize`.
1699 if let ty::RawPtr(_) = discr_enum_ty.kind() {
1700 discr_enum_ty = cx.tcx.types.usize;
1703 let tags: Vec<_> = variants
1705 .filter_map(|(variant_idx, _)| {
1706 calculate_niche_value(variant_idx).map(|tag| {
1707 let variant = variant_info_for(variant_idx);
1708 let name = variant.variant_name();
1711 llvm::LLVMRustDIBuilderCreateEnumerator(
1713 name.as_ptr().cast(),
1716 !discr_enum_ty.is_signed(),
1723 let discr_enum = unsafe {
1724 llvm::LLVMRustDIBuilderCreateEnumerationType(
1727 "Discriminant$".as_ptr().cast(),
1728 "Discriminant$".len(),
1729 unknown_file_metadata(cx),
1730 UNKNOWN_LINE_NUMBER,
1731 tag.value.size(cx).bits(),
1732 tag.value.align(cx).abi.bits() as u32,
1733 create_DIArray(DIB(cx), &tags),
1734 type_metadata(cx, discr_enum_ty, self.span),
1739 let variant_info = variant_info_for(dataful_variant);
1740 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1742 dataful_variant_layout,
1748 let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1750 set_members_of_composite_type(
1753 variant_type_metadata,
1754 member_descriptions,
1755 Some(&self.common_members),
1759 cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1763 // Name the dataful variant so that we can identify it for natvis
1764 name: "dataful_variant".to_string(),
1765 type_metadata: variant_type_metadata,
1767 size: self.layout.size,
1768 align: self.layout.align.abi,
1769 flags: DIFlags::FlagZero,
1771 source_info: variant_info.source_info(cx),
1774 name: "discriminant".into(),
1775 type_metadata: discr_enum,
1776 offset: dataful_variant_layout.fields.offset(tag_field),
1779 flags: DIFlags::FlagZero,
1788 let variant = self.layout.for_variant(cx, i);
1789 let variant_info = variant_info_for(i);
1790 let (variant_type_metadata, member_desc_factory) =
1791 describe_enum_variant(
1799 let member_descriptions =
1800 member_desc_factory.create_member_descriptions(cx);
1802 set_members_of_composite_type(
1805 variant_type_metadata,
1806 member_descriptions,
1807 Some(&self.common_members),
1810 let niche_value = calculate_niche_value(i);
1813 name: variant_info.variant_name(),
1814 type_metadata: variant_type_metadata,
1816 size: self.layout.size,
1817 align: self.layout.align.abi,
1818 flags: DIFlags::FlagZero,
1819 discriminant: niche_value,
1820 source_info: variant_info.source_info(cx),
1830 // Creates `MemberDescription`s for the fields of a single enum variant.
1831 struct VariantMemberDescriptionFactory<'tcx> {
1832 /// Cloned from the `layout::Struct` describing the variant.
1834 args: Vec<(String, Ty<'tcx>)>,
1838 impl VariantMemberDescriptionFactory<'tcx> {
1839 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1843 .map(|(i, &(ref name, ty))| {
1844 let (size, align) = cx.size_and_align_of(ty);
1846 name: name.to_string(),
1847 type_metadata: type_metadata(cx, ty, self.span),
1848 offset: self.offsets[i],
1851 flags: DIFlags::FlagZero,
1860 #[derive(Copy, Clone)]
1861 enum VariantInfo<'a, 'tcx> {
1862 Adt(&'tcx ty::VariantDef),
1865 generator_layout: &'tcx GeneratorLayout<'tcx>,
1866 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1867 variant_index: VariantIdx,
1871 impl<'tcx> VariantInfo<'_, 'tcx> {
1872 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1874 VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1875 VariantInfo::Generator { variant_index, .. } => {
1876 f(&GeneratorSubsts::variant_name(*variant_index))
1881 fn variant_name(&self) -> String {
1883 VariantInfo::Adt(variant) => variant.ident.to_string(),
1884 VariantInfo::Generator { variant_index, .. } => {
1885 // Since GDB currently prints out the raw discriminant along
1886 // with every variant, make each variant name be just the value
1887 // of the discriminant. The struct name for the variant includes
1888 // the actual variant description.
1889 format!("{}", variant_index.as_usize())
1894 fn field_name(&self, i: usize) -> String {
1895 let field_name = match *self {
1896 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1897 Some(variant.fields[i].ident.name)
1899 VariantInfo::Generator {
1901 generator_saved_local_names,
1905 generator_saved_local_names
1906 [generator_layout.variant_fields[variant_index][i.into()]]
1910 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1913 fn source_info(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1915 VariantInfo::Generator { def_id, variant_index, .. } => {
1916 let span = cx.tcx.generator_layout(*def_id).unwrap().variant_source_info
1919 if !span.is_dummy() {
1920 let loc = cx.lookup_debug_loc(span.lo());
1921 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1930 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1931 /// `MemberDescriptionFactory` for producing the descriptions of the
1932 /// fields of the variant. This is a rudimentary version of a full
1933 /// `RecursiveTypeDescription`.
1934 fn describe_enum_variant(
1935 cx: &CodegenCx<'ll, 'tcx>,
1936 layout: layout::TyAndLayout<'tcx>,
1937 variant: VariantInfo<'_, 'tcx>,
1938 containing_scope: &'ll DIScope,
1940 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1941 let metadata_stub = variant.map_struct_name(|variant_name| {
1942 let unique_type_id = debug_context(cx)
1945 .get_unique_type_id_of_enum_variant(cx, layout.ty, &variant_name);
1951 Some(containing_scope),
1956 let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
1957 let args = (0..layout.fields.count())
1958 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
1961 let member_description_factory =
1962 VariantMDF(VariantMemberDescriptionFactory { offsets, args, span });
1964 (metadata_stub, member_description_factory)
1967 fn prepare_enum_metadata(
1968 cx: &CodegenCx<'ll, 'tcx>,
1969 enum_type: Ty<'tcx>,
1971 unique_type_id: UniqueTypeId,
1973 outer_field_tys: Vec<Ty<'tcx>>,
1974 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1976 let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
1978 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1979 // FIXME: This should emit actual file metadata for the enum, but we
1980 // currently can't get the necessary information when it comes to types
1981 // imported from other crates. Formerly we violated the ODR when performing
1982 // LTO because we emitted debuginfo for the same type with varying file
1983 // metadata, so as a workaround we pretend that the type comes from
1985 let file_metadata = unknown_file_metadata(cx);
1987 let discriminant_type_metadata = |discr: Primitive| {
1988 let enumerators_metadata: Vec<_> = match enum_type.kind() {
1989 ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
1990 .map(|((_, discr), v)| {
1991 let name = v.ident.as_str();
1992 let is_unsigned = match discr.ty.kind() {
1993 ty::Int(_) => false,
1994 ty::Uint(_) => true,
1995 _ => bug!("non integer discriminant"),
1998 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2000 name.as_ptr().cast(),
2002 // FIXME: what if enumeration has i128 discriminant?
2009 ty::Generator(_, substs, _) => substs
2011 .variant_range(enum_def_id, tcx)
2012 .map(|variant_index| {
2013 debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2014 let name = GeneratorSubsts::variant_name(variant_index);
2016 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2018 name.as_ptr().cast(),
2020 // Generators use u32 as discriminant type, verified above.
2021 variant_index.as_u32().into(),
2030 let disr_type_key = (enum_def_id, discr);
2031 let cached_discriminant_type_metadata =
2032 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2033 match cached_discriminant_type_metadata {
2034 Some(discriminant_type_metadata) => discriminant_type_metadata,
2036 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2037 let discriminant_base_type_metadata =
2038 type_metadata(cx, discr.to_ty(tcx), rustc_span::DUMMY_SP);
2041 let discriminant_name = match enum_type.kind() {
2043 item_name = tcx.item_name(enum_def_id).as_str();
2046 ty::Generator(..) => enum_name.as_str(),
2050 let discriminant_type_metadata = unsafe {
2051 llvm::LLVMRustDIBuilderCreateEnumerationType(
2054 discriminant_name.as_ptr().cast(),
2055 discriminant_name.len(),
2057 UNKNOWN_LINE_NUMBER,
2058 discriminant_size.bits(),
2059 discriminant_align.abi.bits() as u32,
2060 create_DIArray(DIB(cx), &enumerators_metadata),
2061 discriminant_base_type_metadata,
2067 .created_enum_disr_types
2069 .insert(disr_type_key, discriminant_type_metadata);
2071 discriminant_type_metadata
2076 let layout = cx.layout_of(enum_type);
2080 &Variants::Multiple { tag_encoding: TagEncoding::Direct, ref tag, .. },
2081 ) = (&layout.abi, &layout.variants)
2083 return FinalMetadata(discriminant_type_metadata(tag.value));
2086 if use_enum_fallback(cx) {
2087 let discriminant_type_metadata = match layout.variants {
2088 Variants::Single { .. } => None,
2089 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, ref tag, .. }
2090 | Variants::Multiple { tag_encoding: TagEncoding::Direct, ref tag, .. } => {
2091 Some(discriminant_type_metadata(tag.value))
2095 let enum_metadata = {
2096 let type_map = debug_context(cx).type_map.borrow();
2097 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2100 llvm::LLVMRustDIBuilderCreateUnionType(
2103 enum_name.as_ptr().cast(),
2106 UNKNOWN_LINE_NUMBER,
2108 layout.align.abi.bits() as u32,
2112 unique_type_id_str.as_ptr().cast(),
2113 unique_type_id_str.len(),
2118 return create_and_register_recursive_type_forward_declaration(
2124 EnumMDF(EnumMemberDescriptionFactory {
2127 tag_type_metadata: discriminant_type_metadata,
2128 common_members: vec![],
2134 let discriminator_name = match enum_type.kind() {
2135 ty::Generator(..) => "__state",
2138 let discriminator_metadata = match layout.variants {
2139 // A single-variant enum has no discriminant.
2140 Variants::Single { .. } => None,
2142 Variants::Multiple {
2143 tag_encoding: TagEncoding::Niche { .. }, ref tag, tag_field, ..
2145 // Find the integer type of the correct size.
2146 let size = tag.value.size(cx);
2147 let align = tag.value.align(cx);
2149 let tag_type = match tag.value {
2151 F32 => Integer::I32,
2152 F64 => Integer::I64,
2153 Pointer => cx.data_layout().ptr_sized_integer(),
2155 .to_ty(cx.tcx, false);
2157 let tag_metadata = basic_type_metadata(cx, tag_type);
2159 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2162 discriminator_name.as_ptr().cast(),
2163 discriminator_name.len(),
2165 UNKNOWN_LINE_NUMBER,
2167 align.abi.bits() as u32,
2168 layout.fields.offset(tag_field).bits(),
2169 DIFlags::FlagArtificial,
2175 Variants::Multiple { tag_encoding: TagEncoding::Direct, ref tag, tag_field, .. } => {
2176 let discr_type = tag.value.to_ty(cx.tcx);
2177 let (size, align) = cx.size_and_align_of(discr_type);
2179 let discr_metadata = basic_type_metadata(cx, discr_type);
2181 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2184 discriminator_name.as_ptr().cast(),
2185 discriminator_name.len(),
2187 UNKNOWN_LINE_NUMBER,
2189 align.bits() as u32,
2190 layout.fields.offset(tag_field).bits(),
2191 DIFlags::FlagArtificial,
2198 let outer_fields = match layout.variants {
2199 Variants::Single { .. } => vec![],
2200 Variants::Multiple { .. } => {
2201 let tuple_mdf = TupleMemberDescriptionFactory {
2203 component_types: outer_field_tys,
2207 .create_member_descriptions(cx)
2209 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2214 let variant_part_unique_type_id_str = debug_context(cx)
2217 .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2218 let empty_array = create_DIArray(DIB(cx), &[]);
2220 let variant_part = unsafe {
2221 llvm::LLVMRustDIBuilderCreateVariantPart(
2224 name.as_ptr().cast(),
2227 UNKNOWN_LINE_NUMBER,
2229 layout.align.abi.bits() as u32,
2231 discriminator_metadata,
2233 variant_part_unique_type_id_str.as_ptr().cast(),
2234 variant_part_unique_type_id_str.len(),
2238 let struct_wrapper = {
2239 // The variant part must be wrapped in a struct according to DWARF.
2240 // All fields except the discriminant (including `outer_fields`)
2241 // should be put into structures inside the variant part, which gives
2242 // an equivalent layout but offers us much better integration with
2244 let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2246 let type_map = debug_context(cx).type_map.borrow();
2247 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2250 llvm::LLVMRustDIBuilderCreateStructType(
2252 Some(containing_scope),
2253 enum_name.as_ptr().cast(),
2256 UNKNOWN_LINE_NUMBER,
2258 layout.align.abi.bits() as u32,
2264 unique_type_id_str.as_ptr().cast(),
2265 unique_type_id_str.len(),
2270 create_and_register_recursive_type_forward_declaration(
2276 EnumMDF(EnumMemberDescriptionFactory {
2279 tag_type_metadata: None,
2280 common_members: outer_fields,
2286 /// Creates debug information for a composite type, that is, anything that
2287 /// results in a LLVM struct.
2289 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2290 fn composite_type_metadata(
2291 cx: &CodegenCx<'ll, 'tcx>,
2292 composite_type: Ty<'tcx>,
2293 composite_type_name: &str,
2294 composite_type_unique_id: UniqueTypeId,
2295 member_descriptions: Vec<MemberDescription<'ll>>,
2296 containing_scope: Option<&'ll DIScope>,
2298 // Ignore source location information as long as it
2299 // can't be reconstructed for non-local crates.
2300 _file_metadata: &'ll DIFile,
2301 _definition_span: Span,
2302 ) -> &'ll DICompositeType {
2303 // Create the (empty) struct metadata node ...
2304 let composite_type_metadata = create_struct_stub(
2307 composite_type_name,
2308 composite_type_unique_id,
2312 // ... and immediately create and add the member descriptions.
2313 set_members_of_composite_type(
2316 composite_type_metadata,
2317 member_descriptions,
2321 composite_type_metadata
2324 fn set_members_of_composite_type(
2325 cx: &CodegenCx<'ll, 'tcx>,
2326 composite_type: Ty<'tcx>,
2327 composite_type_metadata: &'ll DICompositeType,
2328 member_descriptions: Vec<MemberDescription<'ll>>,
2329 common_members: Option<&Vec<Option<&'ll DIType>>>,
2331 // In some rare cases LLVM metadata uniquing would lead to an existing type
2332 // description being used instead of a new one created in
2333 // create_struct_stub. This would cause a hard to trace assertion in
2334 // DICompositeType::SetTypeArray(). The following check makes sure that we
2335 // get a better error message if this should happen again due to some
2338 let mut composite_types_completed =
2339 debug_context(cx).composite_types_completed.borrow_mut();
2340 if !composite_types_completed.insert(&composite_type_metadata) {
2342 "debuginfo::set_members_of_composite_type() - \
2343 Already completed forward declaration re-encountered."
2348 let mut member_metadata: Vec<_> = member_descriptions
2350 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2352 if let Some(other_members) = common_members {
2353 member_metadata.extend(other_members.iter());
2356 let type_params = compute_type_parameters(cx, composite_type);
2358 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
2359 llvm::LLVMRustDICompositeTypeReplaceArrays(
2361 composite_type_metadata,
2368 /// Computes the type parameters for a type, if any, for the given metadata.
2369 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2370 if let ty::Adt(def, substs) = *ty.kind() {
2371 if substs.types().next().is_some() {
2372 let generics = cx.tcx.generics_of(def.did);
2373 let names = get_parameter_names(cx, generics);
2374 let template_params: Vec<_> = iter::zip(substs, names)
2375 .filter_map(|(kind, name)| {
2376 if let GenericArgKind::Type(ty) = kind.unpack() {
2378 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2379 let actual_type_metadata =
2380 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
2381 let name = &name.as_str();
2383 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2386 name.as_ptr().cast(),
2388 actual_type_metadata,
2397 return create_DIArray(DIB(cx), &template_params[..]);
2400 return create_DIArray(DIB(cx), &[]);
2402 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2403 let mut names = generics
2405 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2406 names.extend(generics.params.iter().map(|param| param.name));
2411 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2412 /// any caching, does not add any fields to the struct. This can be done later
2413 /// with `set_members_of_composite_type()`.
2414 fn create_struct_stub(
2415 cx: &CodegenCx<'ll, 'tcx>,
2416 struct_type: Ty<'tcx>,
2417 struct_type_name: &str,
2418 unique_type_id: UniqueTypeId,
2419 containing_scope: Option<&'ll DIScope>,
2421 ) -> &'ll DICompositeType {
2422 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2424 let type_map = debug_context(cx).type_map.borrow();
2425 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2427 let metadata_stub = unsafe {
2428 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2429 // pointer will lead to hard to trace and debug LLVM assertions
2430 // later on in `llvm/lib/IR/Value.cpp`.
2431 let empty_array = create_DIArray(DIB(cx), &[]);
2433 llvm::LLVMRustDIBuilderCreateStructType(
2436 struct_type_name.as_ptr().cast(),
2437 struct_type_name.len(),
2438 unknown_file_metadata(cx),
2439 UNKNOWN_LINE_NUMBER,
2441 struct_align.bits() as u32,
2447 unique_type_id.as_ptr().cast(),
2448 unique_type_id.len(),
2455 fn create_union_stub(
2456 cx: &CodegenCx<'ll, 'tcx>,
2457 union_type: Ty<'tcx>,
2458 union_type_name: &str,
2459 unique_type_id: UniqueTypeId,
2460 containing_scope: &'ll DIScope,
2461 ) -> &'ll DICompositeType {
2462 let (union_size, union_align) = cx.size_and_align_of(union_type);
2464 let type_map = debug_context(cx).type_map.borrow();
2465 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2467 let metadata_stub = unsafe {
2468 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2469 // pointer will lead to hard to trace and debug LLVM assertions
2470 // later on in `llvm/lib/IR/Value.cpp`.
2471 let empty_array = create_DIArray(DIB(cx), &[]);
2473 llvm::LLVMRustDIBuilderCreateUnionType(
2475 Some(containing_scope),
2476 union_type_name.as_ptr().cast(),
2477 union_type_name.len(),
2478 unknown_file_metadata(cx),
2479 UNKNOWN_LINE_NUMBER,
2481 union_align.bits() as u32,
2485 unique_type_id.as_ptr().cast(),
2486 unique_type_id.len(),
2493 /// Creates debug information for the given global variable.
2495 /// Adds the created metadata nodes directly to the crate's IR.
2496 pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2497 if cx.dbg_cx.is_none() {
2501 // Only create type information if full debuginfo is enabled
2502 if cx.sess().opts.debuginfo != DebugInfo::Full {
2508 // We may want to remove the namespace scope if we're in an extern block (see
2509 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2510 let var_scope = get_namespace_for_item(cx, def_id);
2511 let span = tcx.def_span(def_id);
2513 let (file_metadata, line_number) = if !span.is_dummy() {
2514 let loc = cx.lookup_debug_loc(span.lo());
2515 (file_metadata(cx, &loc.file), loc.line)
2517 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2520 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2521 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2522 let type_metadata = type_metadata(cx, variable_type, span);
2523 let var_name = tcx.item_name(def_id).as_str();
2524 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2525 // When empty, linkage_name field is omitted,
2526 // which is what we want for no_mangle statics
2527 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2529 let global_align = cx.align_of(variable_type);
2532 llvm::LLVMRustDIBuilderCreateStaticVariable(
2535 var_name.as_ptr().cast(),
2537 linkage_name.as_ptr().cast(),
2545 global_align.bytes() as u32,
2550 /// Creates debug information for the given vtable, which is for the
2553 /// Adds the created metadata nodes directly to the crate's IR.
2554 pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: &'ll Value) {
2555 if cx.dbg_cx.is_none() {
2559 // Only create type information if full debuginfo is enabled
2560 if cx.sess().opts.debuginfo != DebugInfo::Full {
2564 let type_metadata = type_metadata(cx, ty, rustc_span::DUMMY_SP);
2567 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2568 // pointer will lead to hard to trace and debug LLVM assertions
2569 // later on in `llvm/lib/IR/Value.cpp`.
2570 let empty_array = create_DIArray(DIB(cx), &[]);
2571 let name = "vtable";
2573 // Create a new one each time. We don't want metadata caching
2574 // here, because each vtable will refer to a unique containing
2576 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
2579 name.as_ptr().cast(),
2581 unknown_file_metadata(cx),
2582 UNKNOWN_LINE_NUMBER,
2584 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
2585 DIFlags::FlagArtificial,
2589 Some(type_metadata),
2590 name.as_ptr().cast(),
2594 let linkage_name = "";
2595 llvm::LLVMRustDIBuilderCreateStaticVariable(
2598 name.as_ptr().cast(),
2600 linkage_name.as_ptr().cast(),
2602 unknown_file_metadata(cx),
2603 UNKNOWN_LINE_NUMBER,
2613 /// Creates an "extension" of an existing `DIScope` into another file.
2614 pub fn extend_scope_to_file(
2615 cx: &CodegenCx<'ll, '_>,
2616 scope_metadata: &'ll DIScope,
2618 ) -> &'ll DILexicalBlock {
2619 let file_metadata = file_metadata(cx, file);
2620 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }