1 use self::EnumTagInfo::*;
2 use self::MemberDescriptionFactory::*;
3 use self::RecursiveTypeDescription::*;
5 use super::namespace::mangled_name_of_instance;
6 use super::type_names::compute_debuginfo_type_name;
8 create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
10 use super::CrateDebugContext;
13 use crate::common::CodegenCx;
15 use crate::llvm::debuginfo::{
16 DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
19 use crate::value::Value;
23 use rustc_codegen_ssa::traits::*;
24 use rustc_data_structures::const_cstr;
25 use rustc_data_structures::fingerprint::Fingerprint;
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
28 use rustc_fs_util::path_to_c_string;
29 use rustc_hir::def::CtorKind;
30 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
31 use rustc_index::vec::{Idx, IndexVec};
32 use rustc_middle::ich::NodeIdHashingMode;
33 use rustc_middle::mir::interpret::truncate;
34 use rustc_middle::mir::{self, Field, GeneratorLayout};
35 use rustc_middle::ty::layout::{self, IntegerExt, PrimitiveExt, TyAndLayout};
36 use rustc_middle::ty::subst::GenericArgKind;
37 use rustc_middle::ty::Instance;
38 use rustc_middle::ty::{self, AdtKind, GeneratorSubsts, ParamEnv, Ty, TyCtxt};
39 use rustc_middle::{bug, span_bug};
40 use rustc_session::config::{self, DebugInfo};
41 use rustc_span::symbol::{Interner, Symbol};
42 use rustc_span::{self, SourceFile, SourceFileHash, Span};
43 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, LayoutOf, TagEncoding};
44 use rustc_target::abi::{Int, Pointer, F32, F64};
45 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
47 use libc::{c_longlong, c_uint};
48 use std::collections::hash_map::Entry;
49 use std::fmt::{self, Write};
50 use std::hash::{Hash, Hasher};
52 use std::path::{Path, PathBuf};
55 impl PartialEq for llvm::Metadata {
56 fn eq(&self, other: &Self) -> bool {
61 impl Eq for llvm::Metadata {}
63 impl Hash for llvm::Metadata {
64 fn hash<H: Hasher>(&self, hasher: &mut H) {
65 (self as *const Self).hash(hasher);
69 impl fmt::Debug for llvm::Metadata {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 (self as *const Self).fmt(f)
76 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
77 const DW_LANG_RUST: c_uint = 0x1c;
78 #[allow(non_upper_case_globals)]
79 const DW_ATE_boolean: c_uint = 0x02;
80 #[allow(non_upper_case_globals)]
81 const DW_ATE_float: c_uint = 0x04;
82 #[allow(non_upper_case_globals)]
83 const DW_ATE_signed: c_uint = 0x05;
84 #[allow(non_upper_case_globals)]
85 const DW_ATE_unsigned: c_uint = 0x07;
86 #[allow(non_upper_case_globals)]
87 const DW_ATE_unsigned_char: c_uint = 0x08;
89 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
90 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
92 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
94 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
95 pub struct UniqueTypeId(Symbol);
97 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
98 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
99 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
102 pub struct TypeMap<'ll, 'tcx> {
103 /// The `UniqueTypeId`s created so far.
104 unique_id_interner: Interner,
105 /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
106 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
107 /// A map from types to debuginfo metadata. This is an N:1 mapping.
108 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
109 /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
110 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
113 impl TypeMap<'ll, 'tcx> {
114 /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
115 /// the mapping already exists.
116 fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
117 if self.type_to_metadata.insert(type_, metadata).is_some() {
118 bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
122 /// Removes a `Ty`-to-metadata mapping.
123 /// This is useful when computing the metadata for a potentially
124 /// recursive type (e.g., a function pointer of the form:
126 /// fn foo() -> impl Copy { foo }
128 /// This kind of type cannot be properly represented
129 /// via LLVM debuginfo. As a workaround,
130 /// we register a temporary Ty to metadata mapping
131 /// for the function before we compute its actual metadata.
132 /// If the metadata computation ends up recursing back to the
133 /// original function, it will use the temporary mapping
134 /// for the inner self-reference, preventing us from
135 /// recursing forever.
137 /// This function is used to remove the temporary metadata
138 /// mapping after we've computed the actual metadata.
139 fn remove_type(&mut self, type_: Ty<'tcx>) {
140 if self.type_to_metadata.remove(type_).is_none() {
141 bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_);
145 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
146 /// fail if the mapping already exists.
147 fn register_unique_id_with_metadata(
149 unique_type_id: UniqueTypeId,
150 metadata: &'ll DIType,
152 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
154 "type metadata for unique ID '{}' is already in the `TypeMap`!",
155 self.get_unique_type_id_as_string(unique_type_id)
160 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
161 self.type_to_metadata.get(&type_).cloned()
164 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
165 self.unique_id_to_metadata.get(&unique_type_id).cloned()
168 /// Gets the string representation of a `UniqueTypeId`. This method will fail if
169 /// the ID is unknown.
170 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
171 let UniqueTypeId(interner_key) = unique_type_id;
172 self.unique_id_interner.get(interner_key)
175 /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
176 /// type has been requested before, this is just a table lookup. Otherwise, an
177 /// ID will be generated and stored for later lookup.
178 fn get_unique_type_id_of_type<'a>(
180 cx: &CodegenCx<'a, 'tcx>,
183 // Let's see if we already have something in the cache.
184 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
185 return unique_type_id;
187 // If not, generate one.
189 // The hasher we are using to generate the UniqueTypeId. We want
190 // something that provides more than the 64 bits of the DefaultHasher.
191 let mut hasher = StableHasher::new();
192 let mut hcx = cx.tcx.create_stable_hashing_context();
193 let type_ = cx.tcx.erase_regions(&type_);
194 hcx.while_hashing_spans(false, |hcx| {
195 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
196 type_.hash_stable(hcx, &mut hasher);
199 let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
201 let key = self.unique_id_interner.intern(&unique_type_id);
202 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
207 /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
208 /// types of their own, so they need special handling. We still need a
209 /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
210 fn get_unique_type_id_of_enum_variant<'a>(
212 cx: &CodegenCx<'a, 'tcx>,
216 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
217 let enum_variant_type_id =
218 format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
219 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
220 UniqueTypeId(interner_key)
223 /// Gets the unique type ID string for an enum variant part.
224 /// Variant parts are not types and shouldn't really have their own ID,
225 /// but it makes `set_members_of_composite_type()` simpler.
226 fn get_unique_type_id_str_of_enum_variant_part(
228 enum_type_id: UniqueTypeId,
230 format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
234 /// A description of some recursive type. It can either be already finished (as
235 /// with `FinalMetadata`) or it is not yet finished, but contains all information
236 /// needed to generate the missing parts of the description. See the
237 /// documentation section on Recursive Types at the top of this file for more
239 enum RecursiveTypeDescription<'ll, 'tcx> {
241 unfinished_type: Ty<'tcx>,
242 unique_type_id: UniqueTypeId,
243 metadata_stub: &'ll DICompositeType,
244 member_holding_stub: &'ll DICompositeType,
245 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
247 FinalMetadata(&'ll DICompositeType),
250 fn create_and_register_recursive_type_forward_declaration(
251 cx: &CodegenCx<'ll, 'tcx>,
252 unfinished_type: Ty<'tcx>,
253 unique_type_id: UniqueTypeId,
254 metadata_stub: &'ll DICompositeType,
255 member_holding_stub: &'ll DICompositeType,
256 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
257 ) -> RecursiveTypeDescription<'ll, 'tcx> {
258 // Insert the stub into the `TypeMap` in order to allow for recursive references.
259 let mut type_map = debug_context(cx).type_map.borrow_mut();
260 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
261 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
268 member_description_factory,
272 impl RecursiveTypeDescription<'ll, 'tcx> {
273 /// Finishes up the description of the type in question (mostly by providing
274 /// descriptions of the fields of the given type) and returns the final type
276 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
278 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
284 ref member_description_factory,
286 // Make sure that we have a forward declaration of the type in
287 // the TypeMap so that recursive references are possible. This
288 // will always be the case if the RecursiveTypeDescription has
289 // been properly created through the
290 // `create_and_register_recursive_type_forward_declaration()`
293 let type_map = debug_context(cx).type_map.borrow();
294 if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
295 || type_map.find_metadata_for_type(unfinished_type).is_none()
298 "Forward declaration of potentially recursive type \
299 '{:?}' was not found in TypeMap!",
305 // ... then create the member descriptions ...
306 let member_descriptions = member_description_factory.create_member_descriptions(cx);
308 // ... and attach them to the stub to complete it.
309 set_members_of_composite_type(
315 MetadataCreationResult::new(metadata_stub, true)
321 /// Returns from the enclosing function if the type metadata with the given
322 /// unique ID can be found in the type map.
323 macro_rules! return_if_metadata_created_in_meantime {
324 ($cx: expr, $unique_type_id: expr) => {
325 if let Some(metadata) =
326 debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
328 return MetadataCreationResult::new(metadata, true);
333 fn fixed_vec_metadata(
334 cx: &CodegenCx<'ll, 'tcx>,
335 unique_type_id: UniqueTypeId,
336 array_or_slice_type: Ty<'tcx>,
337 element_type: Ty<'tcx>,
339 ) -> MetadataCreationResult<'ll> {
340 let element_type_metadata = type_metadata(cx, element_type, span);
342 return_if_metadata_created_in_meantime!(cx, unique_type_id);
344 let (size, align) = cx.size_and_align_of(array_or_slice_type);
346 let upper_bound = match array_or_slice_type.kind {
347 ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong,
352 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
354 let subscripts = create_DIArray(DIB(cx), &[subrange]);
355 let metadata = unsafe {
356 llvm::LLVMRustDIBuilderCreateArrayType(
360 element_type_metadata,
365 MetadataCreationResult::new(metadata, false)
368 fn vec_slice_metadata(
369 cx: &CodegenCx<'ll, 'tcx>,
370 slice_ptr_type: Ty<'tcx>,
371 element_type: Ty<'tcx>,
372 unique_type_id: UniqueTypeId,
374 ) -> MetadataCreationResult<'ll> {
375 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
377 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
379 return_if_metadata_created_in_meantime!(cx, unique_type_id);
381 let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
383 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
384 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
386 let member_descriptions = vec![
388 name: "data_ptr".to_owned(),
389 type_metadata: data_ptr_metadata,
392 align: pointer_align,
393 flags: DIFlags::FlagZero,
398 name: "length".to_owned(),
399 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
400 offset: pointer_size,
403 flags: DIFlags::FlagZero,
409 let file_metadata = unknown_file_metadata(cx);
411 let metadata = composite_type_metadata(
414 &slice_type_name[..],
421 MetadataCreationResult::new(metadata, false)
424 fn subroutine_type_metadata(
425 cx: &CodegenCx<'ll, 'tcx>,
426 unique_type_id: UniqueTypeId,
427 signature: ty::PolyFnSig<'tcx>,
429 ) -> MetadataCreationResult<'ll> {
431 cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &signature);
433 let signature_metadata: Vec<_> = iter::once(
435 match signature.output().kind {
436 ty::Tuple(ref tys) if tys.is_empty() => None,
437 _ => Some(type_metadata(cx, signature.output(), span)),
442 signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type, span))),
446 return_if_metadata_created_in_meantime!(cx, unique_type_id);
448 MetadataCreationResult::new(
450 llvm::LLVMRustDIBuilderCreateSubroutineType(
452 create_DIArray(DIB(cx), &signature_metadata[..]),
459 // FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill-
460 // defined concept. For the case of an actual trait pointer (i.e., `Box<Trait>`,
461 // `&Trait`), `trait_object_type` should be the whole thing (e.g, `Box<Trait>`) and
462 // `trait_type` should be the actual trait (e.g., `Trait`). Where the trait is part
463 // of a DST struct, there is no `trait_object_type` and the results of this
464 // function will be a little bit weird.
465 fn trait_pointer_metadata(
466 cx: &CodegenCx<'ll, 'tcx>,
467 trait_type: Ty<'tcx>,
468 trait_object_type: Option<Ty<'tcx>>,
469 unique_type_id: UniqueTypeId,
471 // The implementation provided here is a stub. It makes sure that the trait
472 // type is assigned the correct name, size, namespace, and source location.
473 // However, it does not describe the trait's methods.
475 let containing_scope = match trait_type.kind {
476 ty::Dynamic(ref data, ..) => {
477 data.principal_def_id().map(|did| get_namespace_for_item(cx, did))
481 "debuginfo: unexpected trait-object type in \
482 trait_pointer_metadata(): {:?}",
488 let trait_object_type = trait_object_type.unwrap_or(trait_type);
489 let trait_type_name = compute_debuginfo_type_name(cx.tcx, trait_object_type, false);
491 let file_metadata = unknown_file_metadata(cx);
493 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
495 assert_eq!(abi::FAT_PTR_ADDR, 0);
496 assert_eq!(abi::FAT_PTR_EXTRA, 1);
498 let data_ptr_field = layout.field(cx, 0);
499 let vtable_field = layout.field(cx, 1);
500 let member_descriptions = vec![
502 name: "pointer".to_owned(),
503 type_metadata: type_metadata(
505 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
506 rustc_span::DUMMY_SP,
508 offset: layout.fields.offset(0),
509 size: data_ptr_field.size,
510 align: data_ptr_field.align.abi,
511 flags: DIFlags::FlagArtificial,
516 name: "vtable".to_owned(),
517 type_metadata: type_metadata(cx, vtable_field.ty, rustc_span::DUMMY_SP),
518 offset: layout.fields.offset(1),
519 size: vtable_field.size,
520 align: vtable_field.align.abi,
521 flags: DIFlags::FlagArtificial,
527 composite_type_metadata(
530 &trait_type_name[..],
535 rustc_span::DUMMY_SP,
539 pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Span) -> &'ll DIType {
540 // Get the unique type ID of this type.
541 let unique_type_id = {
542 let mut type_map = debug_context(cx).type_map.borrow_mut();
543 // First, try to find the type in `TypeMap`. If we have seen it before, we
544 // can exit early here.
545 match type_map.find_metadata_for_type(t) {
550 // The Ty is not in the `TypeMap` but maybe we have already seen
551 // an equivalent type (e.g., only differing in region arguments).
552 // In order to find out, generate the unique type ID and look
554 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
555 match type_map.find_metadata_for_unique_id(unique_type_id) {
557 // There is already an equivalent type in the TypeMap.
558 // Register this Ty as an alias in the cache and
559 // return the cached metadata.
560 type_map.register_type_with_metadata(t, metadata);
564 // There really is no type metadata for this type, so
565 // proceed by creating it.
573 debug!("type_metadata: {:?}", t);
575 let ptr_metadata = |ty: Ty<'tcx>| match ty.kind {
576 ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
577 ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
578 ty::Dynamic(..) => Ok(MetadataCreationResult::new(
579 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
583 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
585 if let Some(metadata) =
586 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
588 return Err(metadata);
591 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false))
595 let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.kind {
596 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
597 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
599 ty::Tuple(ref elements) if elements.is_empty() => {
600 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
602 ty::Array(typ, _) | ty::Slice(typ) => {
603 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
605 ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
607 MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
610 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
612 ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) {
614 Err(metadata) => return metadata,
616 ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) {
618 Err(metadata) => return metadata,
620 ty::FnDef(..) | ty::FnPtr(_) => {
621 if let Some(metadata) =
622 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
627 // It's possible to create a self-referential
628 // type in Rust by using 'impl trait':
630 // fn foo() -> impl Copy { foo }
632 // See `TypeMap::remove_type` for more detals
633 // about the workaround.
637 // The choice of type here is pretty arbitrary -
638 // anything reading the debuginfo for a recursive
639 // type is going to see *something* weird - the only
640 // question is what exactly it will see.
641 let name = "<recur_type>";
642 llvm::LLVMRustDIBuilderCreateBasicType(
644 name.as_ptr().cast(),
646 cx.size_of(t).bits(),
652 let type_map = &debug_context(cx).type_map;
653 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
656 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span)
659 type_map.borrow_mut().remove_type(t);
661 // This is actually a function pointer, so wrap it in pointer DI.
662 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
664 ty::Closure(def_id, substs) => {
665 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
666 let containing_scope = get_namespace_for_item(cx, def_id);
667 prepare_tuple_metadata(
673 Some(containing_scope),
677 ty::Generator(def_id, substs, _) => {
678 let upvar_tys: Vec<_> = substs
681 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
683 prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys)
686 ty::Adt(def, ..) => match def.adt_kind() {
688 prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
691 prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
694 prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![])
698 ty::Tuple(ref elements) => {
699 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
700 prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA)
703 // Type parameters from polymorphized functions.
704 ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
705 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
709 let mut type_map = debug_context(cx).type_map.borrow_mut();
711 if already_stored_in_typemap {
712 // Also make sure that we already have a `TypeMap` entry for the unique type ID.
713 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
714 Some(metadata) => metadata,
718 "expected type metadata for unique \
719 type ID '{}' to already be in \
720 the `debuginfo::TypeMap` but it \
722 type_map.get_unique_type_id_as_string(unique_type_id),
728 match type_map.find_metadata_for_type(t) {
730 if metadata != metadata_for_uid {
733 "mismatch between `Ty` and \
734 `UniqueTypeId` maps in \
735 `debuginfo::TypeMap`. \
736 UniqueTypeId={}, Ty={}",
737 type_map.get_unique_type_id_as_string(unique_type_id),
743 type_map.register_type_with_metadata(t, metadata);
747 type_map.register_type_with_metadata(t, metadata);
748 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
755 fn hex_encode(data: &[u8]) -> String {
756 let mut hex_string = String::with_capacity(data.len() * 2);
757 for byte in data.iter() {
758 write!(&mut hex_string, "{:02x}", byte).unwrap();
763 pub fn file_metadata(
764 cx: &CodegenCx<'ll, '_>,
765 source_file: &SourceFile,
766 defining_crate: CrateNum,
768 debug!("file_metadata: file_name: {}, defining_crate: {}", source_file.name, defining_crate);
770 let hash = Some(&source_file.src_hash);
771 let file_name = Some(source_file.name.to_string());
772 let directory = if defining_crate == LOCAL_CRATE {
773 Some(cx.sess().working_dir.0.to_string_lossy().to_string())
775 // If the path comes from an upstream crate we assume it has been made
776 // independent of the compiler's working directory one way or another.
779 file_metadata_raw(cx, file_name, directory, hash)
782 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
783 file_metadata_raw(cx, None, None, None)
786 fn file_metadata_raw(
787 cx: &CodegenCx<'ll, '_>,
788 file_name: Option<String>,
789 directory: Option<String>,
790 hash: Option<&SourceFileHash>,
792 let key = (file_name, directory);
794 match debug_context(cx).created_files.borrow_mut().entry(key) {
795 Entry::Occupied(o) => o.get(),
796 Entry::Vacant(v) => {
797 let (file_name, directory) = v.key();
798 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
800 let file_name = file_name.as_deref().unwrap_or("<unknown>");
801 let directory = directory.as_deref().unwrap_or("");
803 let (hash_kind, hash_value) = match hash {
805 let kind = match hash.kind {
806 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
807 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
809 (kind, hex_encode(hash.hash_bytes()))
811 None => (llvm::ChecksumKind::None, String::new()),
814 let file_metadata = unsafe {
815 llvm::LLVMRustDIBuilderCreateFile(
817 file_name.as_ptr().cast(),
819 directory.as_ptr().cast(),
822 hash_value.as_ptr().cast(),
827 v.insert(file_metadata);
833 trait MsvcBasicName {
834 fn msvc_basic_name(self) -> &'static str;
837 impl MsvcBasicName for ast::IntTy {
838 fn msvc_basic_name(self) -> &'static str {
840 ast::IntTy::Isize => "ptrdiff_t",
841 ast::IntTy::I8 => "__int8",
842 ast::IntTy::I16 => "__int16",
843 ast::IntTy::I32 => "__int32",
844 ast::IntTy::I64 => "__int64",
845 ast::IntTy::I128 => "__int128",
850 impl MsvcBasicName for ast::UintTy {
851 fn msvc_basic_name(self) -> &'static str {
853 ast::UintTy::Usize => "size_t",
854 ast::UintTy::U8 => "unsigned __int8",
855 ast::UintTy::U16 => "unsigned __int16",
856 ast::UintTy::U32 => "unsigned __int32",
857 ast::UintTy::U64 => "unsigned __int64",
858 ast::UintTy::U128 => "unsigned __int128",
863 impl MsvcBasicName for ast::FloatTy {
864 fn msvc_basic_name(self) -> &'static str {
866 ast::FloatTy::F32 => "float",
867 ast::FloatTy::F64 => "double",
872 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
873 debug!("basic_type_metadata: {:?}", t);
875 // When targeting MSVC, emit MSVC style type names for compatibility with
876 // .natvis visualizers (and perhaps other existing native debuggers?)
877 let msvc_like_names = cx.tcx.sess.target.target.options.is_like_msvc;
879 let (name, encoding) = match t.kind {
880 ty::Never => ("!", DW_ATE_unsigned),
881 ty::Tuple(ref elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
882 ty::Bool => ("bool", DW_ATE_boolean),
883 ty::Char => ("char", DW_ATE_unsigned_char),
884 ty::Int(int_ty) if msvc_like_names => (int_ty.msvc_basic_name(), DW_ATE_signed),
885 ty::Uint(uint_ty) if msvc_like_names => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
886 ty::Float(float_ty) if msvc_like_names => (float_ty.msvc_basic_name(), DW_ATE_float),
887 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
888 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
889 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
890 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
893 let ty_metadata = unsafe {
894 llvm::LLVMRustDIBuilderCreateBasicType(
896 name.as_ptr().cast(),
898 cx.size_of(t).bits(),
903 if !msvc_like_names {
907 let typedef_name = match t.kind {
908 ty::Int(int_ty) => int_ty.name_str(),
909 ty::Uint(uint_ty) => uint_ty.name_str(),
910 ty::Float(float_ty) => float_ty.name_str(),
911 _ => return ty_metadata,
914 let typedef_metadata = unsafe {
915 llvm::LLVMRustDIBuilderCreateTypedef(
918 typedef_name.as_ptr().cast(),
920 unknown_file_metadata(cx),
929 fn foreign_type_metadata(
930 cx: &CodegenCx<'ll, 'tcx>,
932 unique_type_id: UniqueTypeId,
934 debug!("foreign_type_metadata: {:?}", t);
936 let name = compute_debuginfo_type_name(cx.tcx, t, false);
937 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA, DIFlags::FlagZero)
940 fn pointer_type_metadata(
941 cx: &CodegenCx<'ll, 'tcx>,
942 pointer_type: Ty<'tcx>,
943 pointee_type_metadata: &'ll DIType,
945 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
946 let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
948 llvm::LLVMRustDIBuilderCreatePointerType(
950 pointee_type_metadata,
952 pointer_align.bits() as u32,
953 0, // Ignore DWARF address space.
954 name.as_ptr().cast(),
960 fn param_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
961 debug!("param_type_metadata: {:?}", t);
962 let name = format!("{:?}", t);
964 llvm::LLVMRustDIBuilderCreateBasicType(
966 name.as_ptr().cast(),
974 pub fn compile_unit_metadata(
976 codegen_unit_name: &str,
977 debug_context: &CrateDebugContext<'ll, '_>,
978 ) -> &'ll DIDescriptor {
979 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
980 Some(ref path) => path.clone(),
981 None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
984 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
985 // if multiple object files with the same `DW_AT_name` are linked together.
986 // As a workaround we generate unique names for each object file. Those do
987 // not correspond to an actual source file but that should be harmless.
988 if tcx.sess.target.target.options.is_like_osx {
989 name_in_debuginfo.push("@");
990 name_in_debuginfo.push(codegen_unit_name);
993 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
995 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
996 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
997 let producer = format!("clang LLVM ({})", rustc_producer);
999 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1000 let work_dir = tcx.sess.working_dir.0.to_string_lossy();
1002 let split_name = "";
1006 // This should actually be
1008 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1010 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
1011 // we are compiling with "limited" debuginfo. However, some of the
1012 // existing tools relied on slightly more debuginfo being generated than
1013 // would be the case with `LineTablesOnly`, and we did not want to break
1014 // these tools in a "drive-by fix", without a good idea or plan about
1015 // what limited debuginfo should exactly look like. So for now we keep
1016 // the emission kind as `FullDebug`.
1018 // See https://github.com/rust-lang/rust/issues/60020 for details.
1019 let kind = DebugEmissionKind::FullDebug;
1020 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1023 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
1024 debug_context.builder,
1025 name_in_debuginfo.as_ptr().cast(),
1026 name_in_debuginfo.len(),
1027 work_dir.as_ptr().cast(),
1029 llvm::ChecksumKind::None,
1034 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1035 debug_context.builder,
1038 producer.as_ptr().cast(),
1040 tcx.sess.opts.optimize != config::OptLevel::No,
1041 flags.as_ptr().cast(),
1043 split_name.as_ptr().cast(),
1048 if tcx.sess.opts.debugging_opts.profile {
1049 let cu_desc_metadata =
1050 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1051 let default_gcda_path = &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda");
1053 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1055 let gcov_cu_info = [
1057 debug_context.llcontext,
1058 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno"),
1060 path_to_mdstring(debug_context.llcontext, &gcda_path),
1063 let gcov_metadata = llvm::LLVMMDNodeInContext(
1064 debug_context.llcontext,
1065 gcov_cu_info.as_ptr(),
1066 gcov_cu_info.len() as c_uint,
1069 let llvm_gcov_ident = const_cstr!("llvm.gcov");
1070 llvm::LLVMAddNamedMetadataOperand(
1071 debug_context.llmod,
1072 llvm_gcov_ident.as_ptr(),
1077 // Insert `llvm.ident` metadata on the wasm32 targets since that will
1078 // get hooked up to the "producer" sections `processed-by` information.
1079 if tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
1080 let name_metadata = llvm::LLVMMDStringInContext(
1081 debug_context.llcontext,
1082 rustc_producer.as_ptr().cast(),
1083 rustc_producer.as_bytes().len() as c_uint,
1085 llvm::LLVMAddNamedMetadataOperand(
1086 debug_context.llmod,
1087 const_cstr!("llvm.ident").as_ptr(),
1088 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1092 return unit_metadata;
1095 fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1096 let path_str = path_to_c_string(path);
1098 llvm::LLVMMDStringInContext(
1101 path_str.as_bytes().len() as c_uint,
1107 struct MetadataCreationResult<'ll> {
1108 metadata: &'ll DIType,
1109 already_stored_in_typemap: bool,
1112 impl MetadataCreationResult<'ll> {
1113 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1114 MetadataCreationResult { metadata, already_stored_in_typemap }
1119 struct SourceInfo<'ll> {
1124 /// Description of a type member, which can either be a regular field (as in
1125 /// structs or tuples) or an enum variant.
1127 struct MemberDescription<'ll> {
1129 type_metadata: &'ll DIType,
1134 discriminant: Option<u64>,
1135 source_info: Option<SourceInfo<'ll>>,
1138 impl<'ll> MemberDescription<'ll> {
1141 cx: &CodegenCx<'ll, '_>,
1142 composite_type_metadata: &'ll DIScope,
1144 let (file, line) = self
1146 .map(|info| (info.file, info.line))
1147 .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1149 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1151 composite_type_metadata,
1152 self.name.as_ptr().cast(),
1157 self.align.bits() as u32,
1159 match self.discriminant {
1161 Some(value) => Some(cx.const_u64(value)),
1170 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1171 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1172 /// creation of type member descriptions in order to break cycles arising from
1173 /// recursive type definitions.
1174 enum MemberDescriptionFactory<'ll, 'tcx> {
1175 StructMDF(StructMemberDescriptionFactory<'tcx>),
1176 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1177 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1178 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1179 VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>),
1182 impl MemberDescriptionFactory<'ll, 'tcx> {
1183 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1185 StructMDF(ref this) => this.create_member_descriptions(cx),
1186 TupleMDF(ref this) => this.create_member_descriptions(cx),
1187 EnumMDF(ref this) => this.create_member_descriptions(cx),
1188 UnionMDF(ref this) => this.create_member_descriptions(cx),
1189 VariantMDF(ref this) => this.create_member_descriptions(cx),
1194 //=-----------------------------------------------------------------------------
1196 //=-----------------------------------------------------------------------------
1198 /// Creates `MemberDescription`s for the fields of a struct.
1199 struct StructMemberDescriptionFactory<'tcx> {
1201 variant: &'tcx ty::VariantDef,
1205 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1206 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1207 let layout = cx.layout_of(self.ty);
1213 let name = if self.variant.ctor_kind == CtorKind::Fn {
1218 let field = layout.field(cx, i);
1221 type_metadata: type_metadata(cx, field.ty, self.span),
1222 offset: layout.fields.offset(i),
1224 align: field.align.abi,
1225 flags: DIFlags::FlagZero,
1234 fn prepare_struct_metadata(
1235 cx: &CodegenCx<'ll, 'tcx>,
1236 struct_type: Ty<'tcx>,
1237 unique_type_id: UniqueTypeId,
1239 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1240 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1242 let (struct_def_id, variant) = match struct_type.kind {
1243 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1244 _ => bug!("prepare_struct_metadata on a non-ADT"),
1247 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1249 let struct_metadata_stub = create_struct_stub(
1254 Some(containing_scope),
1258 create_and_register_recursive_type_forward_declaration(
1262 struct_metadata_stub,
1263 struct_metadata_stub,
1264 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }),
1268 //=-----------------------------------------------------------------------------
1270 //=-----------------------------------------------------------------------------
1272 /// Creates `MemberDescription`s for the fields of a tuple.
1273 struct TupleMemberDescriptionFactory<'tcx> {
1275 component_types: Vec<Ty<'tcx>>,
1279 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1280 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1281 let layout = cx.layout_of(self.ty);
1282 self.component_types
1285 .map(|(i, &component_type)| {
1286 let (size, align) = cx.size_and_align_of(component_type);
1288 name: format!("__{}", i),
1289 type_metadata: type_metadata(cx, component_type, self.span),
1290 offset: layout.fields.offset(i),
1293 flags: DIFlags::FlagZero,
1302 fn prepare_tuple_metadata(
1303 cx: &CodegenCx<'ll, 'tcx>,
1304 tuple_type: Ty<'tcx>,
1305 component_types: &[Ty<'tcx>],
1306 unique_type_id: UniqueTypeId,
1308 containing_scope: Option<&'ll DIScope>,
1309 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1310 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1312 let struct_stub = create_struct_stub(
1321 create_and_register_recursive_type_forward_declaration(
1327 TupleMDF(TupleMemberDescriptionFactory {
1329 component_types: component_types.to_vec(),
1335 //=-----------------------------------------------------------------------------
1337 //=-----------------------------------------------------------------------------
1339 struct UnionMemberDescriptionFactory<'tcx> {
1340 layout: TyAndLayout<'tcx>,
1341 variant: &'tcx ty::VariantDef,
1345 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1346 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1352 let field = self.layout.field(cx, i);
1354 name: f.ident.to_string(),
1355 type_metadata: type_metadata(cx, field.ty, self.span),
1358 align: field.align.abi,
1359 flags: DIFlags::FlagZero,
1368 fn prepare_union_metadata(
1369 cx: &CodegenCx<'ll, 'tcx>,
1370 union_type: Ty<'tcx>,
1371 unique_type_id: UniqueTypeId,
1373 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1374 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1376 let (union_def_id, variant) = match union_type.kind {
1377 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1378 _ => bug!("prepare_union_metadata on a non-ADT"),
1381 let containing_scope = get_namespace_for_item(cx, union_def_id);
1383 let union_metadata_stub =
1384 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1386 create_and_register_recursive_type_forward_declaration(
1390 union_metadata_stub,
1391 union_metadata_stub,
1392 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }),
1396 //=-----------------------------------------------------------------------------
1398 //=-----------------------------------------------------------------------------
1400 /// DWARF variant support is only available starting in LLVM 8, but
1401 /// on MSVC we have to use the fallback mode, because LLVM doesn't
1402 /// lower variant parts to PDB.
1403 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1404 cx.sess().target.target.options.is_like_msvc
1407 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1408 // per generator monomorphization, but it doesn't depend on substs.
1409 fn generator_layout_and_saved_local_names(
1412 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1413 let body = tcx.optimized_mir(def_id);
1414 let generator_layout = body.generator_layout.as_ref().unwrap();
1415 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1417 let state_arg = mir::Local::new(1);
1418 for var in &body.var_debug_info {
1419 if var.place.local != state_arg {
1422 match var.place.projection[..] {
1424 // Deref of the `Pin<&mut Self>` state argument.
1425 mir::ProjectionElem::Field(..),
1426 mir::ProjectionElem::Deref,
1428 // Field of a variant of the state.
1429 mir::ProjectionElem::Downcast(_, variant),
1430 mir::ProjectionElem::Field(field, _),
1432 let name = &mut generator_saved_local_names[
1433 generator_layout.variant_fields[variant][field]
1436 name.replace(var.name);
1442 (generator_layout, generator_saved_local_names)
1445 /// Describes the members of an enum value; an enum is described as a union of
1446 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1447 /// the members of this union; so for every variant of the given enum, this
1448 /// factory will produce one `MemberDescription` (all with no name and a fixed
1449 /// offset of zero bytes).
1450 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1451 enum_type: Ty<'tcx>,
1452 layout: TyAndLayout<'tcx>,
1453 tag_type_metadata: Option<&'ll DIType>,
1454 containing_scope: &'ll DIScope,
1458 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1459 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1460 let generator_variant_info_data = match self.enum_type.kind {
1461 ty::Generator(def_id, ..) => {
1462 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1467 let variant_info_for = |index: VariantIdx| match self.enum_type.kind {
1468 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1469 ty::Generator(def_id, _, _) => {
1470 let (generator_layout, generator_saved_local_names) =
1471 generator_variant_info_data.as_ref().unwrap();
1472 VariantInfo::Generator {
1474 generator_layout: *generator_layout,
1475 generator_saved_local_names,
1476 variant_index: index,
1482 // This will always find the metadata in the type map.
1483 let fallback = use_enum_fallback(cx);
1484 let self_metadata = if fallback {
1485 self.containing_scope
1487 type_metadata(cx, self.enum_type, self.span)
1489 let flags = match self.enum_type.kind {
1490 ty::Generator(..) => DIFlags::FlagArtificial,
1491 _ => DIFlags::FlagZero,
1494 match self.layout.variants {
1495 Variants::Single { index } => {
1496 if let ty::Adt(adt, _) = &self.enum_type.kind {
1497 if adt.variants.is_empty() {
1502 let variant_info = variant_info_for(index);
1503 let (variant_type_metadata, member_description_factory) = describe_enum_variant(
1512 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1514 set_members_of_composite_type(
1517 variant_type_metadata,
1518 member_descriptions,
1520 vec![MemberDescription {
1521 name: if fallback { String::new() } else { variant_info.variant_name() },
1522 type_metadata: variant_type_metadata,
1524 size: self.layout.size,
1525 align: self.layout.align.abi,
1528 source_info: variant_info.source_info(cx),
1531 Variants::Multiple {
1532 tag_encoding: TagEncoding::Direct,
1537 let tag_info = if fallback {
1539 tag_field: Field::from(tag_field),
1540 tag_type_metadata: self.tag_type_metadata.unwrap(),
1543 // This doesn't matter in this case.
1549 let variant = self.layout.for_variant(cx, i);
1550 let variant_info = variant_info_for(i);
1551 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1560 let member_descriptions =
1561 member_desc_factory.create_member_descriptions(cx);
1563 set_members_of_composite_type(
1566 variant_type_metadata,
1567 member_descriptions,
1574 variant_info.variant_name()
1576 type_metadata: variant_type_metadata,
1578 size: self.layout.size,
1579 align: self.layout.align.abi,
1582 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1585 source_info: variant_info.source_info(cx),
1590 Variants::Multiple {
1592 TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1598 let variant = self.layout.for_variant(cx, dataful_variant);
1599 // Create a description of the non-null variant.
1600 let (variant_type_metadata, member_description_factory) = describe_enum_variant(
1603 variant_info_for(dataful_variant),
1605 self.containing_scope,
1609 let variant_member_descriptions =
1610 member_description_factory.create_member_descriptions(cx);
1612 set_members_of_composite_type(
1615 variant_type_metadata,
1616 variant_member_descriptions,
1619 // Encode the information about the null variant in the union
1621 let mut name = String::from("RUST$ENCODED$ENUM$");
1622 // Right now it's not even going to work for `niche_start > 0`,
1623 // and for multiple niche variants it only supports the first.
1624 fn compute_field_path<'a, 'tcx>(
1625 cx: &CodegenCx<'a, 'tcx>,
1627 layout: TyAndLayout<'tcx>,
1631 for i in 0..layout.fields.count() {
1632 let field_offset = layout.fields.offset(i);
1633 if field_offset > offset {
1636 let inner_offset = offset - field_offset;
1637 let field = layout.field(cx, i);
1638 if inner_offset + size <= field.size {
1639 write!(name, "{}$", i).unwrap();
1640 compute_field_path(cx, name, field, inner_offset, size);
1648 self.layout.fields.offset(tag_field),
1649 self.layout.field(cx, tag_field).size,
1651 let variant_info = variant_info_for(*niche_variants.start());
1652 variant_info.map_struct_name(|variant_name| {
1653 name.push_str(variant_name);
1656 // Create the (singleton) list of descriptions of union members.
1657 vec![MemberDescription {
1659 type_metadata: variant_type_metadata,
1662 align: variant.align.abi,
1665 source_info: variant_info.source_info(cx),
1671 let variant = self.layout.for_variant(cx, i);
1672 let variant_info = variant_info_for(i);
1673 let (variant_type_metadata, member_desc_factory) =
1674 describe_enum_variant(
1683 let member_descriptions =
1684 member_desc_factory.create_member_descriptions(cx);
1686 set_members_of_composite_type(
1689 variant_type_metadata,
1690 member_descriptions,
1693 let niche_value = if i == dataful_variant {
1696 let value = (i.as_u32() as u128)
1697 .wrapping_sub(niche_variants.start().as_u32() as u128)
1698 .wrapping_add(niche_start);
1699 let value = truncate(value, tag.value.size(cx));
1700 // NOTE(eddyb) do *NOT* remove this assert, until
1701 // we pass the full 128-bit value to LLVM, otherwise
1702 // truncation will be silent and remain undetected.
1703 assert_eq!(value as u64 as u128, value);
1708 name: variant_info.variant_name(),
1709 type_metadata: variant_type_metadata,
1711 size: self.layout.size,
1712 align: self.layout.align.abi,
1714 discriminant: niche_value,
1715 source_info: variant_info.source_info(cx),
1725 // Creates `MemberDescription`s for the fields of a single enum variant.
1726 struct VariantMemberDescriptionFactory<'ll, 'tcx> {
1727 /// Cloned from the `layout::Struct` describing the variant.
1729 args: Vec<(String, Ty<'tcx>)>,
1730 tag_type_metadata: Option<&'ll DIType>,
1734 impl VariantMemberDescriptionFactory<'ll, 'tcx> {
1735 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1739 .map(|(i, &(ref name, ty))| {
1740 // Discriminant is always the first field of our variant
1741 // when using the enum fallback.
1742 let is_artificial_discr = use_enum_fallback(cx) && i == 0;
1743 let (size, align) = cx.size_and_align_of(ty);
1745 name: name.to_string(),
1746 type_metadata: if is_artificial_discr {
1747 self.tag_type_metadata.unwrap_or_else(|| type_metadata(cx, ty, self.span))
1749 type_metadata(cx, ty, self.span)
1751 offset: self.offsets[i],
1754 flags: if is_artificial_discr {
1755 DIFlags::FlagArtificial
1767 // FIXME: terminology here should be aligned with `abi::TagEncoding`.
1768 // `OptimizedTag` is `TagEncoding::Niche`, `RegularTag` is `TagEncoding::Direct`.
1769 // `NoTag` should be removed; users should use `Option<EnumTagInfo>` instead.
1770 #[derive(Copy, Clone)]
1771 enum EnumTagInfo<'ll> {
1772 RegularTag { tag_field: Field, tag_type_metadata: &'ll DIType },
1777 #[derive(Copy, Clone)]
1778 enum VariantInfo<'a, 'tcx> {
1779 Adt(&'tcx ty::VariantDef),
1782 generator_layout: &'tcx GeneratorLayout<'tcx>,
1783 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1784 variant_index: VariantIdx,
1788 impl<'tcx> VariantInfo<'_, 'tcx> {
1789 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1791 VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1792 VariantInfo::Generator { variant_index, .. } => {
1793 f(&GeneratorSubsts::variant_name(*variant_index))
1798 fn variant_name(&self) -> String {
1800 VariantInfo::Adt(variant) => variant.ident.to_string(),
1801 VariantInfo::Generator { variant_index, .. } => {
1802 // Since GDB currently prints out the raw discriminant along
1803 // with every variant, make each variant name be just the value
1804 // of the discriminant. The struct name for the variant includes
1805 // the actual variant description.
1806 format!("{}", variant_index.as_usize())
1811 fn field_name(&self, i: usize) -> String {
1812 let field_name = match *self {
1813 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1814 Some(variant.fields[i].ident.name)
1816 VariantInfo::Generator {
1818 generator_saved_local_names,
1822 generator_saved_local_names
1823 [generator_layout.variant_fields[variant_index][i.into()]]
1827 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1830 fn source_info(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1832 VariantInfo::Generator { def_id, variant_index, .. } => {
1834 cx.tcx.generator_layout(*def_id).variant_source_info[*variant_index].span;
1835 if !span.is_dummy() {
1836 let loc = cx.lookup_debug_loc(span.lo());
1837 return Some(SourceInfo {
1838 file: file_metadata(cx, &loc.file, def_id.krate),
1839 line: loc.line.unwrap_or(UNKNOWN_LINE_NUMBER),
1849 fn is_artificial(&self) -> bool {
1851 VariantInfo::Generator { .. } => true,
1852 VariantInfo::Adt(..) => false,
1857 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1858 /// `MemberDescriptionFactory` for producing the descriptions of the
1859 /// fields of the variant. This is a rudimentary version of a full
1860 /// `RecursiveTypeDescription`.
1861 fn describe_enum_variant(
1862 cx: &CodegenCx<'ll, 'tcx>,
1863 layout: layout::TyAndLayout<'tcx>,
1864 variant: VariantInfo<'_, 'tcx>,
1865 discriminant_info: EnumTagInfo<'ll>,
1866 containing_scope: &'ll DIScope,
1868 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1869 let metadata_stub = variant.map_struct_name(|variant_name| {
1870 let unique_type_id = debug_context(cx)
1873 .get_unique_type_id_of_enum_variant(cx, layout.ty, &variant_name);
1879 Some(containing_scope),
1880 // FIXME(tmandry): This doesn't seem to have any effect.
1881 if variant.is_artificial() { DIFlags::FlagArtificial } else { DIFlags::FlagZero },
1885 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1886 let (offsets, args) = if use_enum_fallback(cx) {
1887 // If this is not a univariant enum, there is also the discriminant field.
1888 let (discr_offset, discr_arg) = match discriminant_info {
1889 RegularTag { tag_field, .. } => {
1890 // We have the layout of an enum variant, we need the layout of the outer enum
1891 let enum_layout = cx.layout_of(layout.ty);
1892 let offset = enum_layout.fields.offset(tag_field.as_usize());
1894 ("RUST$ENUM$DISR".to_owned(), enum_layout.field(cx, tag_field.as_usize()).ty);
1895 (Some(offset), Some(args))
1902 .chain((0..layout.fields.count()).map(|i| layout.fields.offset(i)))
1907 (0..layout.fields.count())
1908 .map(|i| (variant.field_name(i), layout.field(cx, i).ty)),
1914 (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect(),
1915 (0..layout.fields.count())
1916 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
1921 let member_description_factory = VariantMDF(VariantMemberDescriptionFactory {
1924 tag_type_metadata: match discriminant_info {
1925 RegularTag { tag_type_metadata, .. } => Some(tag_type_metadata),
1931 (metadata_stub, member_description_factory)
1934 fn prepare_enum_metadata(
1935 cx: &CodegenCx<'ll, 'tcx>,
1936 enum_type: Ty<'tcx>,
1938 unique_type_id: UniqueTypeId,
1940 outer_field_tys: Vec<Ty<'tcx>>,
1941 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1943 let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
1944 // FIXME(tmandry): This doesn't seem to have any effect.
1945 let enum_flags = match enum_type.kind {
1946 ty::Generator(..) => DIFlags::FlagArtificial,
1947 _ => DIFlags::FlagZero,
1950 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1951 // FIXME: This should emit actual file metadata for the enum, but we
1952 // currently can't get the necessary information when it comes to types
1953 // imported from other crates. Formerly we violated the ODR when performing
1954 // LTO because we emitted debuginfo for the same type with varying file
1955 // metadata, so as a workaround we pretend that the type comes from
1957 let file_metadata = unknown_file_metadata(cx);
1959 let discriminant_type_metadata = |discr: Primitive| {
1960 let enumerators_metadata: Vec<_> = match enum_type.kind {
1961 ty::Adt(def, _) => def
1964 .map(|((_, discr), v)| {
1965 let name = v.ident.as_str();
1966 let is_unsigned = match discr.ty.kind {
1967 ty::Int(_) => false,
1968 ty::Uint(_) => true,
1969 _ => bug!("non integer discriminant"),
1972 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1974 name.as_ptr().cast(),
1976 // FIXME: what if enumeration has i128 discriminant?
1983 ty::Generator(_, substs, _) => substs
1985 .variant_range(enum_def_id, tcx)
1986 .map(|variant_index| {
1987 debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
1988 let name = GeneratorSubsts::variant_name(variant_index);
1990 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1992 name.as_ptr().cast(),
1994 // Generators use u32 as discriminant type, verified above.
1995 variant_index.as_u32().into(),
2004 let disr_type_key = (enum_def_id, discr);
2005 let cached_discriminant_type_metadata =
2006 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2007 match cached_discriminant_type_metadata {
2008 Some(discriminant_type_metadata) => discriminant_type_metadata,
2010 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2011 let discriminant_base_type_metadata =
2012 type_metadata(cx, discr.to_ty(tcx), rustc_span::DUMMY_SP);
2015 let discriminant_name = match enum_type.kind {
2017 item_name = tcx.item_name(enum_def_id).as_str();
2020 ty::Generator(..) => enum_name.as_str(),
2024 let discriminant_type_metadata = unsafe {
2025 llvm::LLVMRustDIBuilderCreateEnumerationType(
2028 discriminant_name.as_ptr().cast(),
2029 discriminant_name.len(),
2031 UNKNOWN_LINE_NUMBER,
2032 discriminant_size.bits(),
2033 discriminant_align.abi.bits() as u32,
2034 create_DIArray(DIB(cx), &enumerators_metadata),
2035 discriminant_base_type_metadata,
2041 .created_enum_disr_types
2043 .insert(disr_type_key, discriminant_type_metadata);
2045 discriminant_type_metadata
2050 let layout = cx.layout_of(enum_type);
2054 &Variants::Multiple { tag_encoding: TagEncoding::Direct, ref tag, .. },
2055 ) = (&layout.abi, &layout.variants)
2057 return FinalMetadata(discriminant_type_metadata(tag.value));
2060 if use_enum_fallback(cx) {
2061 let discriminant_type_metadata = match layout.variants {
2062 Variants::Single { .. }
2063 | Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, .. } => None,
2064 Variants::Multiple { tag_encoding: TagEncoding::Direct, ref tag, .. } => {
2065 Some(discriminant_type_metadata(tag.value))
2069 let enum_metadata = {
2070 let type_map = debug_context(cx).type_map.borrow();
2071 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2074 llvm::LLVMRustDIBuilderCreateUnionType(
2077 enum_name.as_ptr().cast(),
2080 UNKNOWN_LINE_NUMBER,
2082 layout.align.abi.bits() as u32,
2086 unique_type_id_str.as_ptr().cast(),
2087 unique_type_id_str.len(),
2092 return create_and_register_recursive_type_forward_declaration(
2098 EnumMDF(EnumMemberDescriptionFactory {
2101 tag_type_metadata: discriminant_type_metadata,
2108 let discriminator_name = match &enum_type.kind {
2109 ty::Generator(..) => "__state",
2112 let discriminator_metadata = match layout.variants {
2113 // A single-variant enum has no discriminant.
2114 Variants::Single { .. } => None,
2116 Variants::Multiple {
2117 tag_encoding: TagEncoding::Niche { .. }, ref tag, tag_field, ..
2119 // Find the integer type of the correct size.
2120 let size = tag.value.size(cx);
2121 let align = tag.value.align(cx);
2123 let tag_type = match tag.value {
2125 F32 => Integer::I32,
2126 F64 => Integer::I64,
2127 Pointer => cx.data_layout().ptr_sized_integer(),
2129 .to_ty(cx.tcx, false);
2131 let tag_metadata = basic_type_metadata(cx, tag_type);
2133 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2136 discriminator_name.as_ptr().cast(),
2137 discriminator_name.len(),
2139 UNKNOWN_LINE_NUMBER,
2141 align.abi.bits() as u32,
2142 layout.fields.offset(tag_field).bits(),
2143 DIFlags::FlagArtificial,
2149 Variants::Multiple { tag_encoding: TagEncoding::Direct, ref tag, tag_field, .. } => {
2150 let discr_type = tag.value.to_ty(cx.tcx);
2151 let (size, align) = cx.size_and_align_of(discr_type);
2153 let discr_metadata = basic_type_metadata(cx, discr_type);
2155 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2158 discriminator_name.as_ptr().cast(),
2159 discriminator_name.len(),
2161 UNKNOWN_LINE_NUMBER,
2163 align.bits() as u32,
2164 layout.fields.offset(tag_field).bits(),
2165 DIFlags::FlagArtificial,
2172 let mut outer_fields = match layout.variants {
2173 Variants::Single { .. } => vec![],
2174 Variants::Multiple { .. } => {
2175 let tuple_mdf = TupleMemberDescriptionFactory {
2177 component_types: outer_field_tys,
2181 .create_member_descriptions(cx)
2183 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2188 let variant_part_unique_type_id_str = debug_context(cx)
2191 .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2192 let empty_array = create_DIArray(DIB(cx), &[]);
2194 let variant_part = unsafe {
2195 llvm::LLVMRustDIBuilderCreateVariantPart(
2198 name.as_ptr().cast(),
2201 UNKNOWN_LINE_NUMBER,
2203 layout.align.abi.bits() as u32,
2205 discriminator_metadata,
2207 variant_part_unique_type_id_str.as_ptr().cast(),
2208 variant_part_unique_type_id_str.len(),
2211 outer_fields.push(Some(variant_part));
2213 let struct_wrapper = {
2214 // The variant part must be wrapped in a struct according to DWARF.
2215 let type_array = create_DIArray(DIB(cx), &outer_fields);
2217 let type_map = debug_context(cx).type_map.borrow();
2218 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2221 llvm::LLVMRustDIBuilderCreateStructType(
2223 Some(containing_scope),
2224 enum_name.as_ptr().cast(),
2227 UNKNOWN_LINE_NUMBER,
2229 layout.align.abi.bits() as u32,
2235 unique_type_id_str.as_ptr().cast(),
2236 unique_type_id_str.len(),
2241 create_and_register_recursive_type_forward_declaration(
2247 EnumMDF(EnumMemberDescriptionFactory {
2250 tag_type_metadata: None,
2257 /// Creates debug information for a composite type, that is, anything that
2258 /// results in a LLVM struct.
2260 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2261 fn composite_type_metadata(
2262 cx: &CodegenCx<'ll, 'tcx>,
2263 composite_type: Ty<'tcx>,
2264 composite_type_name: &str,
2265 composite_type_unique_id: UniqueTypeId,
2266 member_descriptions: Vec<MemberDescription<'ll>>,
2267 containing_scope: Option<&'ll DIScope>,
2269 // Ignore source location information as long as it
2270 // can't be reconstructed for non-local crates.
2271 _file_metadata: &'ll DIFile,
2272 _definition_span: Span,
2273 ) -> &'ll DICompositeType {
2274 // Create the (empty) struct metadata node ...
2275 let composite_type_metadata = create_struct_stub(
2278 composite_type_name,
2279 composite_type_unique_id,
2283 // ... and immediately create and add the member descriptions.
2284 set_members_of_composite_type(cx, composite_type, composite_type_metadata, member_descriptions);
2286 composite_type_metadata
2289 fn set_members_of_composite_type(
2290 cx: &CodegenCx<'ll, 'tcx>,
2291 composite_type: Ty<'tcx>,
2292 composite_type_metadata: &'ll DICompositeType,
2293 member_descriptions: Vec<MemberDescription<'ll>>,
2295 // In some rare cases LLVM metadata uniquing would lead to an existing type
2296 // description being used instead of a new one created in
2297 // create_struct_stub. This would cause a hard to trace assertion in
2298 // DICompositeType::SetTypeArray(). The following check makes sure that we
2299 // get a better error message if this should happen again due to some
2302 let mut composite_types_completed =
2303 debug_context(cx).composite_types_completed.borrow_mut();
2304 if !composite_types_completed.insert(&composite_type_metadata) {
2306 "debuginfo::set_members_of_composite_type() - \
2307 Already completed forward declaration re-encountered."
2312 let member_metadata: Vec<_> = member_descriptions
2314 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2317 let type_params = compute_type_parameters(cx, composite_type);
2319 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
2320 llvm::LLVMRustDICompositeTypeReplaceArrays(
2322 composite_type_metadata,
2329 /// Computes the type parameters for a type, if any, for the given metadata.
2330 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&'ll DIArray> {
2331 if let ty::Adt(def, substs) = ty.kind {
2332 if substs.types().next().is_some() {
2333 let generics = cx.tcx.generics_of(def.did);
2334 let names = get_parameter_names(cx, generics);
2335 let template_params: Vec<_> = substs
2338 .filter_map(|(kind, name)| {
2339 if let GenericArgKind::Type(ty) = kind.unpack() {
2341 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2342 let actual_type_metadata =
2343 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
2344 let name = &name.as_str();
2346 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2349 name.as_ptr().cast(),
2351 actual_type_metadata,
2360 return Some(create_DIArray(DIB(cx), &template_params[..]));
2363 return Some(create_DIArray(DIB(cx), &[]));
2365 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2366 let mut names = generics
2368 .map_or(vec![], |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2369 names.extend(generics.params.iter().map(|param| param.name));
2374 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2375 /// any caching, does not add any fields to the struct. This can be done later
2376 /// with `set_members_of_composite_type()`.
2377 fn create_struct_stub(
2378 cx: &CodegenCx<'ll, 'tcx>,
2379 struct_type: Ty<'tcx>,
2380 struct_type_name: &str,
2381 unique_type_id: UniqueTypeId,
2382 containing_scope: Option<&'ll DIScope>,
2384 ) -> &'ll DICompositeType {
2385 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2387 let type_map = debug_context(cx).type_map.borrow();
2388 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2390 let metadata_stub = unsafe {
2391 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2392 // pointer will lead to hard to trace and debug LLVM assertions
2393 // later on in `llvm/lib/IR/Value.cpp`.
2394 let empty_array = create_DIArray(DIB(cx), &[]);
2396 llvm::LLVMRustDIBuilderCreateStructType(
2399 struct_type_name.as_ptr().cast(),
2400 struct_type_name.len(),
2401 unknown_file_metadata(cx),
2402 UNKNOWN_LINE_NUMBER,
2404 struct_align.bits() as u32,
2410 unique_type_id.as_ptr().cast(),
2411 unique_type_id.len(),
2418 fn create_union_stub(
2419 cx: &CodegenCx<'ll, 'tcx>,
2420 union_type: Ty<'tcx>,
2421 union_type_name: &str,
2422 unique_type_id: UniqueTypeId,
2423 containing_scope: &'ll DIScope,
2424 ) -> &'ll DICompositeType {
2425 let (union_size, union_align) = cx.size_and_align_of(union_type);
2427 let type_map = debug_context(cx).type_map.borrow();
2428 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2430 let metadata_stub = unsafe {
2431 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2432 // pointer will lead to hard to trace and debug LLVM assertions
2433 // later on in `llvm/lib/IR/Value.cpp`.
2434 let empty_array = create_DIArray(DIB(cx), &[]);
2436 llvm::LLVMRustDIBuilderCreateUnionType(
2439 union_type_name.as_ptr().cast(),
2440 union_type_name.len(),
2441 unknown_file_metadata(cx),
2442 UNKNOWN_LINE_NUMBER,
2444 union_align.bits() as u32,
2448 unique_type_id.as_ptr().cast(),
2449 unique_type_id.len(),
2456 /// Creates debug information for the given global variable.
2458 /// Adds the created metadata nodes directly to the crate's IR.
2459 pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2460 if cx.dbg_cx.is_none() {
2464 // Only create type information if full debuginfo is enabled
2465 if cx.sess().opts.debuginfo != DebugInfo::Full {
2471 // We may want to remove the namespace scope if we're in an extern block (see
2472 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2473 let var_scope = get_namespace_for_item(cx, def_id);
2474 let span = tcx.def_span(def_id);
2476 let (file_metadata, line_number) = if !span.is_dummy() {
2477 let loc = cx.lookup_debug_loc(span.lo());
2478 (file_metadata(cx, &loc.file, LOCAL_CRATE), loc.line)
2480 (unknown_file_metadata(cx), None)
2483 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2484 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2485 let type_metadata = type_metadata(cx, variable_type, span);
2486 let var_name = tcx.item_name(def_id).as_str();
2487 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2488 // When empty, linkage_name field is omitted,
2489 // which is what we want for no_mangle statics
2490 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2492 let global_align = cx.align_of(variable_type);
2495 llvm::LLVMRustDIBuilderCreateStaticVariable(
2498 var_name.as_ptr().cast(),
2500 linkage_name.as_ptr().cast(),
2503 line_number.unwrap_or(UNKNOWN_LINE_NUMBER),
2508 global_align.bytes() as u32,
2513 /// Creates debug information for the given vtable, which is for the
2516 /// Adds the created metadata nodes directly to the crate's IR.
2517 pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: &'ll Value) {
2518 if cx.dbg_cx.is_none() {
2522 // Only create type information if full debuginfo is enabled
2523 if cx.sess().opts.debuginfo != DebugInfo::Full {
2527 let type_metadata = type_metadata(cx, ty, rustc_span::DUMMY_SP);
2530 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2531 // pointer will lead to hard to trace and debug LLVM assertions
2532 // later on in `llvm/lib/IR/Value.cpp`.
2533 let empty_array = create_DIArray(DIB(cx), &[]);
2534 let name = "vtable";
2536 // Create a new one each time. We don't want metadata caching
2537 // here, because each vtable will refer to a unique containing
2539 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
2542 name.as_ptr().cast(),
2544 unknown_file_metadata(cx),
2545 UNKNOWN_LINE_NUMBER,
2547 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
2548 DIFlags::FlagArtificial,
2552 Some(type_metadata),
2553 name.as_ptr().cast(),
2557 let linkage_name = "";
2558 llvm::LLVMRustDIBuilderCreateStaticVariable(
2561 name.as_ptr().cast(),
2563 linkage_name.as_ptr().cast(),
2565 unknown_file_metadata(cx),
2566 UNKNOWN_LINE_NUMBER,
2576 /// Creates an "extension" of an existing `DIScope` into another file.
2577 pub fn extend_scope_to_file(
2578 cx: &CodegenCx<'ll, '_>,
2579 scope_metadata: &'ll DIScope,
2580 file: &rustc_span::SourceFile,
2581 defining_crate: CrateNum,
2582 ) -> &'ll DILexicalBlock {
2583 let file_metadata = file_metadata(cx, &file, defining_crate);
2584 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }