1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::RecursiveTypeDescription::*;
12 use self::MemberDescriptionFactory::*;
13 use self::EnumDiscriminantInfo::*;
15 use super::utils::{debug_context, DIB, span_start,
16 get_namespace_for_item, create_DIArray, is_node_local_to_unit};
17 use super::namespace::mangled_name_of_instance;
18 use super::type_names::compute_debuginfo_type_name;
19 use super::{CrateDebugContext};
22 use llvm::{self, ValueRef};
23 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor,
24 DICompositeType, DILexicalBlock, DIFlags};
26 use rustc::hir::TransFnAttrFlags;
27 use rustc::hir::def::CtorKind;
28 use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
29 use rustc::ty::fold::TypeVisitor;
30 use rustc::ty::util::TypeIdHasher;
31 use rustc::ich::Fingerprint;
32 use rustc::ty::Instance;
33 use common::CodegenCx;
34 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
35 use rustc::ty::layout::{self, Align, LayoutOf, PrimitiveExt, Size, TyLayout};
36 use rustc::session::config;
37 use rustc::util::nodemap::FxHashMap;
38 use rustc::util::common::path2cstr;
40 use libc::{c_uint, c_longlong};
41 use std::ffi::CString;
44 use std::path::{Path, PathBuf};
46 use syntax::symbol::{Interner, InternedString, Symbol};
47 use syntax_pos::{self, Span, FileName};
51 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
52 const DW_LANG_RUST: c_uint = 0x1c;
53 #[allow(non_upper_case_globals)]
54 const DW_ATE_boolean: c_uint = 0x02;
55 #[allow(non_upper_case_globals)]
56 const DW_ATE_float: c_uint = 0x04;
57 #[allow(non_upper_case_globals)]
58 const DW_ATE_signed: c_uint = 0x05;
59 #[allow(non_upper_case_globals)]
60 const DW_ATE_unsigned: c_uint = 0x07;
61 #[allow(non_upper_case_globals)]
62 const DW_ATE_unsigned_char: c_uint = 0x08;
64 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
65 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
67 // ptr::null() doesn't work :(
68 pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope);
70 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
71 pub struct UniqueTypeId(ast::Name);
73 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
74 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
75 // faster lookup, also by Ty. The TypeMap is responsible for creating
77 pub struct TypeMap<'tcx> {
78 // The UniqueTypeIds created so far
79 unique_id_interner: Interner,
80 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
81 unique_id_to_metadata: FxHashMap<UniqueTypeId, DIType>,
82 // A map from types to debuginfo metadata. This is a N:1 mapping.
83 type_to_metadata: FxHashMap<Ty<'tcx>, DIType>,
84 // A map from types to UniqueTypeId. This is a N:1 mapping.
85 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>
88 impl<'tcx> TypeMap<'tcx> {
89 pub fn new() -> TypeMap<'tcx> {
91 unique_id_interner: Interner::new(),
92 type_to_metadata: FxHashMap(),
93 unique_id_to_metadata: FxHashMap(),
94 type_to_unique_id: FxHashMap(),
98 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
99 // the mapping already exists.
100 fn register_type_with_metadata<'a>(&mut self,
103 if self.type_to_metadata.insert(type_, metadata).is_some() {
104 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
108 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
109 // fail if the mapping already exists.
110 fn register_unique_id_with_metadata(&mut self,
111 unique_type_id: UniqueTypeId,
113 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
114 bug!("Type metadata for unique id '{}' is already in the TypeMap!",
115 self.get_unique_type_id_as_string(unique_type_id));
119 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
120 self.type_to_metadata.get(&type_).cloned()
123 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
124 self.unique_id_to_metadata.get(&unique_type_id).cloned()
127 // Get the string representation of a UniqueTypeId. This method will fail if
128 // the id is unknown.
129 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
130 let UniqueTypeId(interner_key) = unique_type_id;
131 self.unique_id_interner.get(interner_key)
134 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
135 // type has been requested before, this is just a table lookup. Otherwise an
136 // ID will be generated and stored for later lookup.
137 fn get_unique_type_id_of_type<'a>(&mut self, cx: &CodegenCx<'a, 'tcx>,
138 type_: Ty<'tcx>) -> UniqueTypeId {
139 // Let's see if we already have something in the cache
140 match self.type_to_unique_id.get(&type_).cloned() {
141 Some(unique_type_id) => return unique_type_id,
142 None => { /* generate one */}
145 // The hasher we are using to generate the UniqueTypeId. We want
146 // something that provides more than the 64 bits of the DefaultHasher.
147 let mut type_id_hasher = TypeIdHasher::<Fingerprint>::new(cx.tcx);
148 type_id_hasher.visit_ty(type_);
149 let unique_type_id = type_id_hasher.finish().to_hex();
151 let key = self.unique_id_interner.intern(&unique_type_id);
152 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
154 return UniqueTypeId(key);
157 // Get the UniqueTypeId for an enum variant. Enum variants are not really
158 // types of their own, so they need special handling. We still need a
159 // UniqueTypeId for them, since to debuginfo they *are* real types.
160 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
161 cx: &CodegenCx<'a, 'tcx>,
165 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
166 let enum_variant_type_id = format!("{}::{}",
167 self.get_unique_type_id_as_string(enum_type_id),
169 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
170 UniqueTypeId(interner_key)
174 // A description of some recursive type. It can either be already finished (as
175 // with FinalMetadata) or it is not yet finished, but contains all information
176 // needed to generate the missing parts of the description. See the
177 // documentation section on Recursive Types at the top of this file for more
179 enum RecursiveTypeDescription<'tcx> {
181 unfinished_type: Ty<'tcx>,
182 unique_type_id: UniqueTypeId,
183 metadata_stub: DICompositeType,
184 member_description_factory: MemberDescriptionFactory<'tcx>,
186 FinalMetadata(DICompositeType)
189 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
190 cx: &CodegenCx<'a, 'tcx>,
191 unfinished_type: Ty<'tcx>,
192 unique_type_id: UniqueTypeId,
193 metadata_stub: DICompositeType,
194 member_description_factory: MemberDescriptionFactory<'tcx>)
195 -> RecursiveTypeDescription<'tcx> {
197 // Insert the stub into the TypeMap in order to allow for recursive references
198 let mut type_map = debug_context(cx).type_map.borrow_mut();
199 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
200 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
206 member_description_factory,
210 impl<'tcx> RecursiveTypeDescription<'tcx> {
211 // Finishes up the description of the type in question (mostly by providing
212 // descriptions of the fields of the given type) and returns the final type
214 fn finalize<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> MetadataCreationResult {
216 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
221 ref member_description_factory,
223 // Make sure that we have a forward declaration of the type in
224 // the TypeMap so that recursive references are possible. This
225 // will always be the case if the RecursiveTypeDescription has
226 // been properly created through the
227 // create_and_register_recursive_type_forward_declaration()
230 let type_map = debug_context(cx).type_map.borrow();
231 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
232 type_map.find_metadata_for_type(unfinished_type).is_none() {
233 bug!("Forward declaration of potentially recursive type \
234 '{:?}' was not found in TypeMap!",
239 // ... then create the member descriptions ...
240 let member_descriptions =
241 member_description_factory.create_member_descriptions(cx);
243 // ... and attach them to the stub to complete it.
244 set_members_of_composite_type(cx,
246 &member_descriptions[..]);
247 return MetadataCreationResult::new(metadata_stub, true);
253 // Returns from the enclosing function if the type metadata with the given
254 // unique id can be found in the type map
255 macro_rules! return_if_metadata_created_in_meantime {
256 ($cx: expr, $unique_type_id: expr) => (
257 match debug_context($cx).type_map
259 .find_metadata_for_unique_id($unique_type_id) {
260 Some(metadata) => return MetadataCreationResult::new(metadata, true),
261 None => { /* proceed normally */ }
266 fn fixed_vec_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
267 unique_type_id: UniqueTypeId,
268 array_or_slice_type: Ty<'tcx>,
269 element_type: Ty<'tcx>,
271 -> MetadataCreationResult {
272 let element_type_metadata = type_metadata(cx, element_type, span);
274 return_if_metadata_created_in_meantime!(cx, unique_type_id);
276 let (size, align) = cx.size_and_align_of(array_or_slice_type);
278 let upper_bound = match array_or_slice_type.sty {
279 ty::TyArray(_, len) => {
280 len.val.unwrap_u64() as c_longlong
285 let subrange = unsafe {
286 llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
289 let subscripts = create_DIArray(DIB(cx), &[subrange]);
290 let metadata = unsafe {
291 llvm::LLVMRustDIBuilderCreateArrayType(
294 align.abi_bits() as u32,
295 element_type_metadata,
299 return MetadataCreationResult::new(metadata, false);
302 fn vec_slice_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
303 slice_ptr_type: Ty<'tcx>,
304 element_type: Ty<'tcx>,
305 unique_type_id: UniqueTypeId,
307 -> MetadataCreationResult {
308 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
310 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
312 return_if_metadata_created_in_meantime!(cx, unique_type_id);
314 let slice_type_name = compute_debuginfo_type_name(cx, slice_ptr_type, true);
316 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
317 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
319 let member_descriptions = [
321 name: "data_ptr".to_string(),
322 type_metadata: data_ptr_metadata,
323 offset: Size::from_bytes(0),
325 align: pointer_align,
326 flags: DIFlags::FlagZero,
329 name: "length".to_string(),
330 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
331 offset: pointer_size,
334 flags: DIFlags::FlagZero,
338 let file_metadata = unknown_file_metadata(cx);
340 let metadata = composite_type_metadata(cx,
342 &slice_type_name[..],
344 &member_descriptions,
348 MetadataCreationResult::new(metadata, false)
351 fn subroutine_type_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
352 unique_type_id: UniqueTypeId,
353 signature: ty::PolyFnSig<'tcx>,
355 -> MetadataCreationResult
357 let signature = cx.tcx.normalize_erasing_late_bound_regions(
358 ty::ParamEnv::reveal_all(),
362 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs().len() + 1);
365 signature_metadata.push(match signature.output().sty {
366 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
367 _ => type_metadata(cx, signature.output(), span)
371 for &argument_type in signature.inputs() {
372 signature_metadata.push(type_metadata(cx, argument_type, span));
375 return_if_metadata_created_in_meantime!(cx, unique_type_id);
377 return MetadataCreationResult::new(
379 llvm::LLVMRustDIBuilderCreateSubroutineType(
381 unknown_file_metadata(cx),
382 create_DIArray(DIB(cx), &signature_metadata[..]))
387 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
388 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
389 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
390 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
391 // of a DST struct, there is no trait_object_type and the results of this
392 // function will be a little bit weird.
393 fn trait_pointer_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
394 trait_type: Ty<'tcx>,
395 trait_object_type: Option<Ty<'tcx>>,
396 unique_type_id: UniqueTypeId)
398 // The implementation provided here is a stub. It makes sure that the trait
399 // type is assigned the correct name, size, namespace, and source location.
400 // But it does not describe the trait's methods.
402 let containing_scope = match trait_type.sty {
403 ty::TyDynamic(ref data, ..) => if let Some(principal) = data.principal() {
404 let def_id = principal.def_id();
405 get_namespace_for_item(cx, def_id)
410 bug!("debuginfo: Unexpected trait-object type in \
411 trait_pointer_metadata(): {:?}",
416 let trait_object_type = trait_object_type.unwrap_or(trait_type);
417 let trait_type_name =
418 compute_debuginfo_type_name(cx, trait_object_type, false);
420 let file_metadata = unknown_file_metadata(cx);
422 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
424 assert_eq!(abi::FAT_PTR_ADDR, 0);
425 assert_eq!(abi::FAT_PTR_EXTRA, 1);
427 let data_ptr_field = layout.field(cx, 0);
428 let vtable_field = layout.field(cx, 1);
429 let member_descriptions = [
431 name: "pointer".to_string(),
432 type_metadata: type_metadata(cx,
433 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
434 syntax_pos::DUMMY_SP),
435 offset: layout.fields.offset(0),
436 size: data_ptr_field.size,
437 align: data_ptr_field.align,
438 flags: DIFlags::FlagArtificial,
441 name: "vtable".to_string(),
442 type_metadata: type_metadata(cx, vtable_field.ty, syntax_pos::DUMMY_SP),
443 offset: layout.fields.offset(1),
444 size: vtable_field.size,
445 align: vtable_field.align,
446 flags: DIFlags::FlagArtificial,
450 composite_type_metadata(cx,
452 &trait_type_name[..],
454 &member_descriptions,
457 syntax_pos::DUMMY_SP)
460 pub fn type_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
462 usage_site_span: Span)
464 // Get the unique type id of this type.
465 let unique_type_id = {
466 let mut type_map = debug_context(cx).type_map.borrow_mut();
467 // First, try to find the type in TypeMap. If we have seen it before, we
468 // can exit early here.
469 match type_map.find_metadata_for_type(t) {
474 // The Ty is not in the TypeMap but maybe we have already seen
475 // an equivalent type (e.g. only differing in region arguments).
476 // In order to find out, generate the unique type id and look
478 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
479 match type_map.find_metadata_for_unique_id(unique_type_id) {
481 // There is already an equivalent type in the TypeMap.
482 // Register this Ty as an alias in the cache and
483 // return the cached metadata.
484 type_map.register_type_with_metadata(t, metadata);
488 // There really is no type metadata for this type, so
489 // proceed by creating it.
497 debug!("type_metadata: {:?}", t);
499 let ptr_metadata = |ty: Ty<'tcx>| {
501 ty::TySlice(typ) => {
502 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
505 Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span))
507 ty::TyDynamic(..) => {
508 Ok(MetadataCreationResult::new(
509 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
513 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
515 match debug_context(cx).type_map
517 .find_metadata_for_unique_id(unique_type_id) {
518 Some(metadata) => return Err(metadata),
519 None => { /* proceed normally */ }
522 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
528 let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
535 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
537 ty::TyTuple(ref elements) if elements.is_empty() => {
538 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
540 ty::TyArray(typ, _) |
541 ty::TySlice(typ) => {
542 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
545 fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span)
547 ty::TyDynamic(..) => {
548 MetadataCreationResult::new(
549 trait_pointer_metadata(cx, t, None, unique_type_id),
552 ty::TyForeign(..) => {
553 MetadataCreationResult::new(
554 foreign_type_metadata(cx, t, unique_type_id),
557 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
558 ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
559 match ptr_metadata(ty) {
561 Err(metadata) => return metadata,
564 ty::TyAdt(def, _) if def.is_box() => {
565 match ptr_metadata(t.boxed_ty()) {
567 Err(metadata) => return metadata,
570 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
571 let fn_metadata = subroutine_type_metadata(cx,
574 usage_site_span).metadata;
575 match debug_context(cx).type_map
577 .find_metadata_for_unique_id(unique_type_id) {
578 Some(metadata) => return metadata,
579 None => { /* proceed normally */ }
582 // This is actually a function pointer, so wrap it in pointer DI
583 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
586 ty::TyClosure(def_id, substs) => {
587 let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx).collect();
588 prepare_tuple_metadata(cx,
592 usage_site_span).finalize(cx)
594 ty::TyGenerator(def_id, substs, _) => {
595 let upvar_tys : Vec<_> = substs.field_tys(def_id, cx.tcx).map(|t| {
596 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)
598 prepare_tuple_metadata(cx,
602 usage_site_span).finalize(cx)
604 ty::TyAdt(def, ..) => match def.adt_kind() {
606 prepare_struct_metadata(cx,
609 usage_site_span).finalize(cx)
612 prepare_union_metadata(cx,
615 usage_site_span).finalize(cx)
618 prepare_enum_metadata(cx,
622 usage_site_span).finalize(cx)
625 ty::TyTuple(ref elements) => {
626 prepare_tuple_metadata(cx,
630 usage_site_span).finalize(cx)
633 bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
638 let mut type_map = debug_context(cx).type_map.borrow_mut();
640 if already_stored_in_typemap {
641 // Also make sure that we already have a TypeMap entry for the unique type id.
642 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
643 Some(metadata) => metadata,
645 span_bug!(usage_site_span,
646 "Expected type metadata for unique \
647 type id '{}' to already be in \
648 the debuginfo::TypeMap but it \
650 type_map.get_unique_type_id_as_string(unique_type_id),
655 match type_map.find_metadata_for_type(t) {
657 if metadata != metadata_for_uid {
658 span_bug!(usage_site_span,
659 "Mismatch between Ty and \
660 UniqueTypeId maps in \
661 debuginfo::TypeMap. \
662 UniqueTypeId={}, Ty={}",
663 type_map.get_unique_type_id_as_string(unique_type_id),
668 type_map.register_type_with_metadata(t, metadata);
672 type_map.register_type_with_metadata(t, metadata);
673 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
680 pub fn file_metadata(cx: &CodegenCx,
681 file_name: &FileName,
682 defining_crate: CrateNum) -> DIFile {
683 debug!("file_metadata: file_name: {}, defining_crate: {}",
687 let directory = if defining_crate == LOCAL_CRATE {
688 &cx.sess().working_dir.0
690 // If the path comes from an upstream crate we assume it has been made
691 // independent of the compiler's working directory one way or another.
695 file_metadata_raw(cx, &file_name.to_string(), &directory.to_string_lossy())
698 pub fn unknown_file_metadata(cx: &CodegenCx) -> DIFile {
699 file_metadata_raw(cx, "<unknown>", "")
702 fn file_metadata_raw(cx: &CodegenCx,
706 let key = (Symbol::intern(file_name), Symbol::intern(directory));
708 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(&key) {
709 return *file_metadata;
712 debug!("file_metadata: file_name: {}, directory: {}", file_name, directory);
714 let file_name = CString::new(file_name).unwrap();
715 let directory = CString::new(directory).unwrap();
717 let file_metadata = unsafe {
718 llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
723 let mut created_files = debug_context(cx).created_files.borrow_mut();
724 created_files.insert(key, file_metadata);
728 fn basic_type_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
729 t: Ty<'tcx>) -> DIType {
731 debug!("basic_type_metadata: {:?}", t);
733 let (name, encoding) = match t.sty {
734 ty::TyNever => ("!", DW_ATE_unsigned),
735 ty::TyTuple(ref elements) if elements.is_empty() =>
736 ("()", DW_ATE_unsigned),
737 ty::TyBool => ("bool", DW_ATE_boolean),
738 ty::TyChar => ("char", DW_ATE_unsigned_char),
739 ty::TyInt(int_ty) => {
740 (int_ty.ty_to_string(), DW_ATE_signed)
742 ty::TyUint(uint_ty) => {
743 (uint_ty.ty_to_string(), DW_ATE_unsigned)
745 ty::TyFloat(float_ty) => {
746 (float_ty.ty_to_string(), DW_ATE_float)
748 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
751 let (size, align) = cx.size_and_align_of(t);
752 let name = CString::new(name).unwrap();
753 let ty_metadata = unsafe {
754 llvm::LLVMRustDIBuilderCreateBasicType(
758 align.abi_bits() as u32,
765 fn foreign_type_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
767 unique_type_id: UniqueTypeId) -> DIType {
768 debug!("foreign_type_metadata: {:?}", t);
770 let name = compute_debuginfo_type_name(cx, t, false);
771 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA)
774 fn pointer_type_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
775 pointer_type: Ty<'tcx>,
776 pointee_type_metadata: DIType)
778 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
779 let name = compute_debuginfo_type_name(cx, pointer_type, false);
780 let name = CString::new(name).unwrap();
782 llvm::LLVMRustDIBuilderCreatePointerType(
784 pointee_type_metadata,
786 pointer_align.abi_bits() as u32,
791 pub fn compile_unit_metadata(tcx: TyCtxt,
792 codegen_unit_name: &str,
793 debug_context: &CrateDebugContext)
795 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
796 Some(ref path) => path.clone(),
797 None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
800 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
801 // if multiple object files with the same DW_AT_name are linked together.
802 // As a workaround we generate unique names for each object file. Those do
803 // not correspond to an actual source file but that should be harmless.
804 if tcx.sess.target.target.options.is_like_osx {
805 name_in_debuginfo.push("@");
806 name_in_debuginfo.push(codegen_unit_name);
809 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
810 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
811 let producer = format!("clang LLVM (rustc version {})",
812 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
814 let name_in_debuginfo = name_in_debuginfo.to_string_lossy().into_owned();
815 let name_in_debuginfo = CString::new(name_in_debuginfo).unwrap();
816 let work_dir = CString::new(&tcx.sess.working_dir.0.to_string_lossy()[..]).unwrap();
817 let producer = CString::new(producer).unwrap();
819 let split_name = "\0";
822 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
823 debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
825 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
826 debug_context.builder,
830 tcx.sess.opts.optimize != config::OptLevel::No,
831 flags.as_ptr() as *const _,
833 split_name.as_ptr() as *const _);
835 if tcx.sess.opts.debugging_opts.profile {
836 let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
840 path_to_mdstring(debug_context.llcontext,
841 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno")),
842 path_to_mdstring(debug_context.llcontext,
843 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda")),
846 let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
847 gcov_cu_info.as_ptr(),
848 gcov_cu_info.len() as c_uint);
850 let llvm_gcov_ident = CString::new("llvm.gcov").unwrap();
851 llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
852 llvm_gcov_ident.as_ptr(),
856 return unit_metadata;
859 fn path_to_mdstring(llcx: llvm::ContextRef, path: &Path) -> llvm::ValueRef {
860 let path_str = path2cstr(path);
862 llvm::LLVMMDStringInContext(llcx,
864 path_str.as_bytes().len() as c_uint)
869 struct MetadataCreationResult {
871 already_stored_in_typemap: bool
874 impl MetadataCreationResult {
875 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
876 MetadataCreationResult {
878 already_stored_in_typemap,
883 // Description of a type member, which can either be a regular field (as in
884 // structs or tuples) or an enum variant.
886 struct MemberDescription {
888 type_metadata: DIType,
895 // A factory for MemberDescriptions. It produces a list of member descriptions
896 // for some record-like type. MemberDescriptionFactories are used to defer the
897 // creation of type member descriptions in order to break cycles arising from
898 // recursive type definitions.
899 enum MemberDescriptionFactory<'tcx> {
900 StructMDF(StructMemberDescriptionFactory<'tcx>),
901 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
902 EnumMDF(EnumMemberDescriptionFactory<'tcx>),
903 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
904 VariantMDF(VariantMemberDescriptionFactory<'tcx>)
907 impl<'tcx> MemberDescriptionFactory<'tcx> {
908 fn create_member_descriptions<'a>(&self, cx: &CodegenCx<'a, 'tcx>)
909 -> Vec<MemberDescription> {
911 StructMDF(ref this) => {
912 this.create_member_descriptions(cx)
914 TupleMDF(ref this) => {
915 this.create_member_descriptions(cx)
917 EnumMDF(ref this) => {
918 this.create_member_descriptions(cx)
920 UnionMDF(ref this) => {
921 this.create_member_descriptions(cx)
923 VariantMDF(ref this) => {
924 this.create_member_descriptions(cx)
930 //=-----------------------------------------------------------------------------
932 //=-----------------------------------------------------------------------------
934 // Creates MemberDescriptions for the fields of a struct
935 struct StructMemberDescriptionFactory<'tcx> {
937 variant: &'tcx ty::VariantDef,
941 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
942 fn create_member_descriptions<'a>(&self, cx: &CodegenCx<'a, 'tcx>)
943 -> Vec<MemberDescription> {
944 let layout = cx.layout_of(self.ty);
945 self.variant.fields.iter().enumerate().map(|(i, f)| {
946 let name = if self.variant.ctor_kind == CtorKind::Fn {
951 let field = layout.field(cx, i);
952 let (size, align) = field.size_and_align();
955 type_metadata: type_metadata(cx, field.ty, self.span),
956 offset: layout.fields.offset(i),
959 flags: DIFlags::FlagZero,
966 fn prepare_struct_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
967 struct_type: Ty<'tcx>,
968 unique_type_id: UniqueTypeId,
970 -> RecursiveTypeDescription<'tcx> {
971 let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
973 let (struct_def_id, variant) = match struct_type.sty {
974 ty::TyAdt(def, _) => (def.did, def.non_enum_variant()),
975 _ => bug!("prepare_struct_metadata on a non-ADT")
978 let containing_scope = get_namespace_for_item(cx, struct_def_id);
980 let struct_metadata_stub = create_struct_stub(cx,
986 create_and_register_recursive_type_forward_declaration(
990 struct_metadata_stub,
991 StructMDF(StructMemberDescriptionFactory {
999 //=-----------------------------------------------------------------------------
1001 //=-----------------------------------------------------------------------------
1003 // Creates MemberDescriptions for the fields of a tuple
1004 struct TupleMemberDescriptionFactory<'tcx> {
1006 component_types: Vec<Ty<'tcx>>,
1010 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1011 fn create_member_descriptions<'a>(&self, cx: &CodegenCx<'a, 'tcx>)
1012 -> Vec<MemberDescription> {
1013 let layout = cx.layout_of(self.ty);
1014 self.component_types.iter().enumerate().map(|(i, &component_type)| {
1015 let (size, align) = cx.size_and_align_of(component_type);
1017 name: format!("__{}", i),
1018 type_metadata: type_metadata(cx, component_type, self.span),
1019 offset: layout.fields.offset(i),
1022 flags: DIFlags::FlagZero,
1028 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1029 tuple_type: Ty<'tcx>,
1030 component_types: &[Ty<'tcx>],
1031 unique_type_id: UniqueTypeId,
1033 -> RecursiveTypeDescription<'tcx> {
1034 let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1036 create_and_register_recursive_type_forward_declaration(
1040 create_struct_stub(cx,
1045 TupleMDF(TupleMemberDescriptionFactory {
1047 component_types: component_types.to_vec(),
1053 //=-----------------------------------------------------------------------------
1055 //=-----------------------------------------------------------------------------
1057 struct UnionMemberDescriptionFactory<'tcx> {
1058 layout: TyLayout<'tcx>,
1059 variant: &'tcx ty::VariantDef,
1063 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1064 fn create_member_descriptions<'a>(&self, cx: &CodegenCx<'a, 'tcx>)
1065 -> Vec<MemberDescription> {
1066 self.variant.fields.iter().enumerate().map(|(i, f)| {
1067 let field = self.layout.field(cx, i);
1068 let (size, align) = field.size_and_align();
1070 name: f.name.to_string(),
1071 type_metadata: type_metadata(cx, field.ty, self.span),
1072 offset: Size::from_bytes(0),
1075 flags: DIFlags::FlagZero,
1081 fn prepare_union_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1082 union_type: Ty<'tcx>,
1083 unique_type_id: UniqueTypeId,
1085 -> RecursiveTypeDescription<'tcx> {
1086 let union_name = compute_debuginfo_type_name(cx, union_type, false);
1088 let (union_def_id, variant) = match union_type.sty {
1089 ty::TyAdt(def, _) => (def.did, def.non_enum_variant()),
1090 _ => bug!("prepare_union_metadata on a non-ADT")
1093 let containing_scope = get_namespace_for_item(cx, union_def_id);
1095 let union_metadata_stub = create_union_stub(cx,
1101 create_and_register_recursive_type_forward_declaration(
1105 union_metadata_stub,
1106 UnionMDF(UnionMemberDescriptionFactory {
1107 layout: cx.layout_of(union_type),
1114 //=-----------------------------------------------------------------------------
1116 //=-----------------------------------------------------------------------------
1118 // Describes the members of an enum value: An enum is described as a union of
1119 // structs in DWARF. This MemberDescriptionFactory provides the description for
1120 // the members of this union; so for every variant of the given enum, this
1121 // factory will produce one MemberDescription (all with no name and a fixed
1122 // offset of zero bytes).
1123 struct EnumMemberDescriptionFactory<'tcx> {
1124 enum_type: Ty<'tcx>,
1125 layout: TyLayout<'tcx>,
1126 discriminant_type_metadata: Option<DIType>,
1127 containing_scope: DIScope,
1131 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1132 fn create_member_descriptions<'a>(&self, cx: &CodegenCx<'a, 'tcx>)
1133 -> Vec<MemberDescription> {
1134 let adt = &self.enum_type.ty_adt_def().unwrap();
1135 match self.layout.variants {
1136 layout::Variants::Single { .. } if adt.variants.is_empty() => vec![],
1137 layout::Variants::Single { index } => {
1138 let (variant_type_metadata, member_description_factory) =
1139 describe_enum_variant(cx,
1141 &adt.variants[index],
1143 self.containing_scope,
1146 let member_descriptions =
1147 member_description_factory.create_member_descriptions(cx);
1149 set_members_of_composite_type(cx,
1150 variant_type_metadata,
1151 &member_descriptions[..]);
1154 name: "".to_string(),
1155 type_metadata: variant_type_metadata,
1156 offset: Size::from_bytes(0),
1157 size: self.layout.size,
1158 align: self.layout.align,
1159 flags: DIFlags::FlagZero
1163 layout::Variants::Tagged { ref variants, .. } => {
1164 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1166 (0..variants.len()).map(|i| {
1167 let variant = self.layout.for_variant(cx, i);
1168 let (variant_type_metadata, member_desc_factory) =
1169 describe_enum_variant(cx,
1173 self.containing_scope,
1176 let member_descriptions = member_desc_factory
1177 .create_member_descriptions(cx);
1179 set_members_of_composite_type(cx,
1180 variant_type_metadata,
1181 &member_descriptions);
1183 name: "".to_string(),
1184 type_metadata: variant_type_metadata,
1185 offset: Size::from_bytes(0),
1187 align: variant.align,
1188 flags: DIFlags::FlagZero
1192 layout::Variants::NicheFilling { dataful_variant, ref niche_variants, .. } => {
1193 let variant = self.layout.for_variant(cx, dataful_variant);
1194 // Create a description of the non-null variant
1195 let (variant_type_metadata, member_description_factory) =
1196 describe_enum_variant(cx,
1198 &adt.variants[dataful_variant],
1199 OptimizedDiscriminant,
1200 self.containing_scope,
1203 let variant_member_descriptions =
1204 member_description_factory.create_member_descriptions(cx);
1206 set_members_of_composite_type(cx,
1207 variant_type_metadata,
1208 &variant_member_descriptions[..]);
1210 // Encode the information about the null variant in the union
1212 let mut name = String::from("RUST$ENCODED$ENUM$");
1213 // HACK(eddyb) the debuggers should just handle offset+size
1214 // of discriminant instead of us having to recover its path.
1215 // Right now it's not even going to work for `niche_start > 0`,
1216 // and for multiple niche variants it only supports the first.
1217 fn compute_field_path<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1219 layout: TyLayout<'tcx>,
1222 for i in 0..layout.fields.count() {
1223 let field_offset = layout.fields.offset(i);
1224 if field_offset > offset {
1227 let inner_offset = offset - field_offset;
1228 let field = layout.field(cx, i);
1229 if inner_offset + size <= field.size {
1230 write!(name, "{}$", i).unwrap();
1231 compute_field_path(cx, name, field, inner_offset, size);
1235 compute_field_path(cx, &mut name,
1237 self.layout.fields.offset(0),
1238 self.layout.field(cx, 0).size);
1239 name.push_str(&adt.variants[niche_variants.start].name.as_str());
1241 // Create the (singleton) list of descriptions of union members.
1245 type_metadata: variant_type_metadata,
1246 offset: Size::from_bytes(0),
1248 align: variant.align,
1249 flags: DIFlags::FlagZero
1257 // Creates MemberDescriptions for the fields of a single enum variant.
1258 struct VariantMemberDescriptionFactory<'tcx> {
1259 // Cloned from the layout::Struct describing the variant.
1260 offsets: Vec<layout::Size>,
1261 args: Vec<(String, Ty<'tcx>)>,
1262 discriminant_type_metadata: Option<DIType>,
1266 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1267 fn create_member_descriptions<'a>(&self, cx: &CodegenCx<'a, 'tcx>)
1268 -> Vec<MemberDescription> {
1269 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1270 let (size, align) = cx.size_and_align_of(ty);
1272 name: name.to_string(),
1273 type_metadata: match self.discriminant_type_metadata {
1274 Some(metadata) if i == 0 => metadata,
1275 _ => type_metadata(cx, ty, self.span)
1277 offset: self.offsets[i],
1280 flags: DIFlags::FlagZero
1286 #[derive(Copy, Clone)]
1287 enum EnumDiscriminantInfo {
1288 RegularDiscriminant(DIType),
1289 OptimizedDiscriminant,
1293 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1294 // of the variant, and (3) a MemberDescriptionFactory for producing the
1295 // descriptions of the fields of the variant. This is a rudimentary version of a
1296 // full RecursiveTypeDescription.
1297 fn describe_enum_variant<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1298 layout: layout::TyLayout<'tcx>,
1299 variant: &'tcx ty::VariantDef,
1300 discriminant_info: EnumDiscriminantInfo,
1301 containing_scope: DIScope,
1303 -> (DICompositeType, MemberDescriptionFactory<'tcx>) {
1304 let variant_name = variant.name.as_str();
1305 let unique_type_id = debug_context(cx).type_map
1307 .get_unique_type_id_of_enum_variant(
1312 let metadata_stub = create_struct_stub(cx,
1318 // If this is not a univariant enum, there is also the discriminant field.
1319 let (discr_offset, discr_arg) = match discriminant_info {
1320 RegularDiscriminant(_) => {
1321 let enum_layout = cx.layout_of(layout.ty);
1322 (Some(enum_layout.fields.offset(0)),
1323 Some(("RUST$ENUM$DISR".to_string(), enum_layout.field(cx, 0).ty)))
1327 let offsets = discr_offset.into_iter().chain((0..layout.fields.count()).map(|i| {
1328 layout.fields.offset(i)
1331 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1332 let args = discr_arg.into_iter().chain((0..layout.fields.count()).map(|i| {
1333 let name = if variant.ctor_kind == CtorKind::Fn {
1336 variant.fields[i].name.to_string()
1338 (name, layout.field(cx, i).ty)
1341 let member_description_factory =
1342 VariantMDF(VariantMemberDescriptionFactory {
1345 discriminant_type_metadata: match discriminant_info {
1346 RegularDiscriminant(discriminant_type_metadata) => {
1347 Some(discriminant_type_metadata)
1354 (metadata_stub, member_description_factory)
1357 fn prepare_enum_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1358 enum_type: Ty<'tcx>,
1360 unique_type_id: UniqueTypeId,
1362 -> RecursiveTypeDescription<'tcx> {
1363 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1365 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1366 // FIXME: This should emit actual file metadata for the enum, but we
1367 // currently can't get the necessary information when it comes to types
1368 // imported from other crates. Formerly we violated the ODR when performing
1369 // LTO because we emitted debuginfo for the same type with varying file
1370 // metadata, so as a workaround we pretend that the type comes from
1372 let file_metadata = unknown_file_metadata(cx);
1374 let def = enum_type.ty_adt_def().unwrap();
1375 let enumerators_metadata: Vec<DIDescriptor> = def.discriminants(cx.tcx)
1378 let token = v.name.as_str();
1379 let name = CString::new(token.as_bytes()).unwrap();
1381 llvm::LLVMRustDIBuilderCreateEnumerator(
1384 // FIXME: what if enumeration has i128 discriminant?
1390 let discriminant_type_metadata = |discr: layout::Primitive| {
1391 let disr_type_key = (enum_def_id, discr);
1392 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1394 .get(&disr_type_key).cloned();
1395 match cached_discriminant_type_metadata {
1396 Some(discriminant_type_metadata) => discriminant_type_metadata,
1398 let (discriminant_size, discriminant_align) =
1399 (discr.size(cx), discr.align(cx));
1400 let discriminant_base_type_metadata =
1401 type_metadata(cx, discr.to_ty(cx.tcx), syntax_pos::DUMMY_SP);
1402 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id).as_str();
1404 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1405 let discriminant_type_metadata = unsafe {
1406 llvm::LLVMRustDIBuilderCreateEnumerationType(
1411 UNKNOWN_LINE_NUMBER,
1412 discriminant_size.bits(),
1413 discriminant_align.abi_bits() as u32,
1414 create_DIArray(DIB(cx), &enumerators_metadata),
1415 discriminant_base_type_metadata)
1418 debug_context(cx).created_enum_disr_types
1420 .insert(disr_type_key, discriminant_type_metadata);
1422 discriminant_type_metadata
1427 let layout = cx.layout_of(enum_type);
1429 let discriminant_type_metadata = match layout.variants {
1430 layout::Variants::Single { .. } |
1431 layout::Variants::NicheFilling { .. } => None,
1432 layout::Variants::Tagged { ref discr, .. } => {
1433 Some(discriminant_type_metadata(discr.value))
1437 match (&layout.abi, discriminant_type_metadata) {
1438 (&layout::Abi::Scalar(_), Some(discr)) => return FinalMetadata(discr),
1442 let (enum_type_size, enum_type_align) = layout.size_and_align();
1444 let enum_name = CString::new(enum_name).unwrap();
1445 let unique_type_id_str = CString::new(
1446 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1448 let enum_metadata = unsafe {
1449 llvm::LLVMRustDIBuilderCreateUnionType(
1454 UNKNOWN_LINE_NUMBER,
1455 enum_type_size.bits(),
1456 enum_type_align.abi_bits() as u32,
1460 unique_type_id_str.as_ptr())
1463 return create_and_register_recursive_type_forward_declaration(
1468 EnumMDF(EnumMemberDescriptionFactory {
1471 discriminant_type_metadata,
1477 fn get_enum_discriminant_name(cx: &CodegenCx,
1480 cx.tcx.item_name(def_id)
1484 /// Creates debug information for a composite type, that is, anything that
1485 /// results in a LLVM struct.
1487 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1488 fn composite_type_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1489 composite_type: Ty<'tcx>,
1490 composite_type_name: &str,
1491 composite_type_unique_id: UniqueTypeId,
1492 member_descriptions: &[MemberDescription],
1493 containing_scope: DIScope,
1495 // Ignore source location information as long as it
1496 // can't be reconstructed for non-local crates.
1497 _file_metadata: DIFile,
1498 _definition_span: Span)
1499 -> DICompositeType {
1500 // Create the (empty) struct metadata node ...
1501 let composite_type_metadata = create_struct_stub(cx,
1503 composite_type_name,
1504 composite_type_unique_id,
1506 // ... and immediately create and add the member descriptions.
1507 set_members_of_composite_type(cx,
1508 composite_type_metadata,
1509 member_descriptions);
1511 return composite_type_metadata;
1514 fn set_members_of_composite_type(cx: &CodegenCx,
1515 composite_type_metadata: DICompositeType,
1516 member_descriptions: &[MemberDescription]) {
1517 // In some rare cases LLVM metadata uniquing would lead to an existing type
1518 // description being used instead of a new one created in
1519 // create_struct_stub. This would cause a hard to trace assertion in
1520 // DICompositeType::SetTypeArray(). The following check makes sure that we
1521 // get a better error message if this should happen again due to some
1524 let mut composite_types_completed =
1525 debug_context(cx).composite_types_completed.borrow_mut();
1526 if composite_types_completed.contains(&composite_type_metadata) {
1527 bug!("debuginfo::set_members_of_composite_type() - \
1528 Already completed forward declaration re-encountered.");
1530 composite_types_completed.insert(composite_type_metadata);
1534 let member_metadata: Vec<DIDescriptor> = member_descriptions
1536 .map(|member_description| {
1537 let member_name = member_description.name.as_bytes();
1538 let member_name = CString::new(member_name).unwrap();
1540 llvm::LLVMRustDIBuilderCreateMemberType(
1542 composite_type_metadata,
1543 member_name.as_ptr(),
1544 unknown_file_metadata(cx),
1545 UNKNOWN_LINE_NUMBER,
1546 member_description.size.bits(),
1547 member_description.align.abi_bits() as u32,
1548 member_description.offset.bits(),
1549 member_description.flags,
1550 member_description.type_metadata)
1556 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1557 llvm::LLVMRustDICompositeTypeSetTypeArray(
1558 DIB(cx), composite_type_metadata, type_array);
1562 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1563 // any caching, does not add any fields to the struct. This can be done later
1564 // with set_members_of_composite_type().
1565 fn create_struct_stub<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1566 struct_type: Ty<'tcx>,
1567 struct_type_name: &str,
1568 unique_type_id: UniqueTypeId,
1569 containing_scope: DIScope)
1570 -> DICompositeType {
1571 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
1573 let name = CString::new(struct_type_name).unwrap();
1574 let unique_type_id = CString::new(
1575 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1577 let metadata_stub = unsafe {
1578 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1579 // pointer will lead to hard to trace and debug LLVM assertions
1580 // later on in llvm/lib/IR/Value.cpp.
1581 let empty_array = create_DIArray(DIB(cx), &[]);
1583 llvm::LLVMRustDIBuilderCreateStructType(
1587 unknown_file_metadata(cx),
1588 UNKNOWN_LINE_NUMBER,
1590 struct_align.abi_bits() as u32,
1596 unique_type_id.as_ptr())
1599 return metadata_stub;
1602 fn create_union_stub<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1603 union_type: Ty<'tcx>,
1604 union_type_name: &str,
1605 unique_type_id: UniqueTypeId,
1606 containing_scope: DIScope)
1607 -> DICompositeType {
1608 let (union_size, union_align) = cx.size_and_align_of(union_type);
1610 let name = CString::new(union_type_name).unwrap();
1611 let unique_type_id = CString::new(
1612 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1614 let metadata_stub = unsafe {
1615 // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
1616 // pointer will lead to hard to trace and debug LLVM assertions
1617 // later on in llvm/lib/IR/Value.cpp.
1618 let empty_array = create_DIArray(DIB(cx), &[]);
1620 llvm::LLVMRustDIBuilderCreateUnionType(
1624 unknown_file_metadata(cx),
1625 UNKNOWN_LINE_NUMBER,
1627 union_align.abi_bits() as u32,
1631 unique_type_id.as_ptr())
1634 return metadata_stub;
1637 /// Creates debug information for the given global variable.
1639 /// Adds the created metadata nodes directly to the crate's IR.
1640 pub fn create_global_var_metadata(cx: &CodegenCx,
1643 if cx.dbg_cx.is_none() {
1648 let attrs = tcx.trans_fn_attrs(def_id);
1650 if attrs.flags.contains(TransFnAttrFlags::NO_DEBUG) {
1654 let no_mangle = attrs.flags.contains(TransFnAttrFlags::NO_MANGLE);
1655 // We may want to remove the namespace scope if we're in an extern block, see:
1656 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952
1657 let var_scope = get_namespace_for_item(cx, def_id);
1658 let span = tcx.def_span(def_id);
1660 let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP {
1661 let loc = span_start(cx, span);
1662 (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint)
1664 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1667 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
1668 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx);
1669 let type_metadata = type_metadata(cx, variable_type, span);
1670 let var_name = tcx.item_name(def_id).to_string();
1671 let var_name = CString::new(var_name).unwrap();
1672 let linkage_name = if no_mangle {
1675 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id));
1676 Some(CString::new(linkage_name.to_string()).unwrap())
1679 let global_align = cx.align_of(variable_type);
1682 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1685 // If null, linkage_name field is omitted,
1686 // which is what we want for no_mangle statics
1687 linkage_name.as_ref()
1688 .map_or(ptr::null(), |name| name.as_ptr()),
1695 global_align.abi() as u32,
1700 // Creates an "extension" of an existing DIScope into another file.
1701 pub fn extend_scope_to_file(cx: &CodegenCx,
1702 scope_metadata: DIScope,
1703 file: &syntax_pos::FileMap,
1704 defining_crate: CrateNum)
1706 let file_metadata = file_metadata(cx, &file.name, defining_crate);
1708 llvm::LLVMRustDIBuilderCreateLexicalBlockFile(
1715 /// Creates debug information for the given vtable, which is for the
1718 /// Adds the created metadata nodes directly to the crate's IR.
1719 pub fn create_vtable_metadata<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1722 if cx.dbg_cx.is_none() {
1726 let type_metadata = type_metadata(cx, ty, syntax_pos::DUMMY_SP);
1729 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1730 // pointer will lead to hard to trace and debug LLVM assertions
1731 // later on in llvm/lib/IR/Value.cpp.
1732 let empty_array = create_DIArray(DIB(cx), &[]);
1734 let name = CString::new("vtable").unwrap();
1736 // Create a new one each time. We don't want metadata caching
1737 // here, because each vtable will refer to a unique containing
1739 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
1743 unknown_file_metadata(cx),
1744 UNKNOWN_LINE_NUMBER,
1745 Size::from_bytes(0).bits(),
1746 cx.tcx.data_layout.pointer_align.abi_bits() as u32,
1747 DIFlags::FlagArtificial,
1755 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1765 unknown_file_metadata(cx),
1766 UNKNOWN_LINE_NUMBER,