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::MemberOffset
::*;
13 use self::MemberDescriptionFactory
::*;
14 use self::EnumDiscriminantInfo
::*;
16 use super::utils
::{debug_context
, DIB
, span_start
, bytes_to_bits
, size_and_align_of
,
17 get_namespace_for_item
, create_DIArray
, is_node_local_to_unit
};
18 use super::namespace
::mangled_name_of_item
;
19 use super::type_names
::compute_debuginfo_type_name
;
20 use super::{CrateDebugContext}
;
22 use context
::SharedCrateContext
;
24 use llvm
::{self, ValueRef}
;
25 use llvm
::debuginfo
::{DIType
, DIFile
, DIScope
, DIDescriptor
,
26 DICompositeType
, DILexicalBlock
, DIFlags
};
28 use rustc
::hir
::def
::CtorKind
;
29 use rustc
::hir
::def_id
::{DefId, CrateNum, LOCAL_CRATE}
;
30 use rustc
::ty
::fold
::TypeVisitor
;
31 use rustc
::ty
::subst
::Substs
;
32 use rustc
::ty
::util
::TypeIdHasher
;
34 use rustc
::ich
::Fingerprint
;
35 use {type_of, machine, monomorphize}
;
36 use common
::{self, CrateContext}
;
38 use rustc
::ty
::{self, AdtKind, Ty}
;
39 use rustc
::ty
::layout
::{self, LayoutTyper}
;
40 use rustc
::session
::{Session, config}
;
41 use rustc
::util
::nodemap
::FxHashMap
;
42 use rustc
::util
::common
::path2cstr
;
44 use libc
::{c_uint, c_longlong}
;
45 use std
::ffi
::CString
;
49 use syntax
::symbol
::{Interner, InternedString, Symbol}
;
50 use syntax_pos
::{self, Span}
;
54 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
55 const DW_LANG_RUST
: c_uint
= 0x1c;
56 #[allow(non_upper_case_globals)]
57 const DW_ATE_boolean
: c_uint
= 0x02;
58 #[allow(non_upper_case_globals)]
59 const DW_ATE_float
: c_uint
= 0x04;
60 #[allow(non_upper_case_globals)]
61 const DW_ATE_signed
: c_uint
= 0x05;
62 #[allow(non_upper_case_globals)]
63 const DW_ATE_unsigned
: c_uint
= 0x07;
64 #[allow(non_upper_case_globals)]
65 const DW_ATE_unsigned_char
: c_uint
= 0x08;
67 pub const UNKNOWN_LINE_NUMBER
: c_uint
= 0;
68 pub const UNKNOWN_COLUMN_NUMBER
: c_uint
= 0;
70 // ptr::null() doesn't work :(
71 pub const NO_SCOPE_METADATA
: DIScope
= (0 as DIScope
);
73 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
74 pub struct UniqueTypeId(ast
::Name
);
76 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
77 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
78 // faster lookup, also by Ty. The TypeMap is responsible for creating
80 pub struct TypeMap
<'tcx
> {
81 // The UniqueTypeIds created so far
82 unique_id_interner
: Interner
,
83 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
84 unique_id_to_metadata
: FxHashMap
<UniqueTypeId
, DIType
>,
85 // A map from types to debuginfo metadata. This is a N:1 mapping.
86 type_to_metadata
: FxHashMap
<Ty
<'tcx
>, DIType
>,
87 // A map from types to UniqueTypeId. This is a N:1 mapping.
88 type_to_unique_id
: FxHashMap
<Ty
<'tcx
>, UniqueTypeId
>
91 impl<'tcx
> TypeMap
<'tcx
> {
92 pub fn new() -> TypeMap
<'tcx
> {
94 unique_id_interner
: Interner
::new(),
95 type_to_metadata
: FxHashMap(),
96 unique_id_to_metadata
: FxHashMap(),
97 type_to_unique_id
: FxHashMap(),
101 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
102 // the mapping already exists.
103 fn register_type_with_metadata
<'a
>(&mut self,
106 if self.type_to_metadata
.insert(type_
, metadata
).is_some() {
107 bug
!("Type metadata for Ty '{}' is already in the TypeMap!", type_
);
111 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
112 // fail if the mapping already exists.
113 fn register_unique_id_with_metadata(&mut self,
114 unique_type_id
: UniqueTypeId
,
116 if self.unique_id_to_metadata
.insert(unique_type_id
, metadata
).is_some() {
117 bug
!("Type metadata for unique id '{}' is already in the TypeMap!",
118 self.get_unique_type_id_as_string(unique_type_id
));
122 fn find_metadata_for_type(&self, type_
: Ty
<'tcx
>) -> Option
<DIType
> {
123 self.type_to_metadata
.get(&type_
).cloned()
126 fn find_metadata_for_unique_id(&self, unique_type_id
: UniqueTypeId
) -> Option
<DIType
> {
127 self.unique_id_to_metadata
.get(&unique_type_id
).cloned()
130 // Get the string representation of a UniqueTypeId. This method will fail if
131 // the id is unknown.
132 fn get_unique_type_id_as_string(&self, unique_type_id
: UniqueTypeId
) -> &str {
133 let UniqueTypeId(interner_key
) = unique_type_id
;
134 self.unique_id_interner
.get(interner_key
)
137 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
138 // type has been requested before, this is just a table lookup. Otherwise an
139 // ID will be generated and stored for later lookup.
140 fn get_unique_type_id_of_type
<'a
>(&mut self, cx
: &CrateContext
<'a
, 'tcx
>,
141 type_
: Ty
<'tcx
>) -> UniqueTypeId
{
142 // Let's see if we already have something in the cache
143 match self.type_to_unique_id
.get(&type_
).cloned() {
144 Some(unique_type_id
) => return unique_type_id
,
145 None
=> { /* generate one */}
148 // The hasher we are using to generate the UniqueTypeId. We want
149 // something that provides more than the 64 bits of the DefaultHasher.
150 let mut type_id_hasher
= TypeIdHasher
::<Fingerprint
>::new(cx
.tcx());
151 type_id_hasher
.visit_ty(type_
);
152 let unique_type_id
= type_id_hasher
.finish().to_hex();
154 let key
= self.unique_id_interner
.intern(&unique_type_id
);
155 self.type_to_unique_id
.insert(type_
, UniqueTypeId(key
));
157 return UniqueTypeId(key
);
160 // Get the UniqueTypeId for an enum variant. Enum variants are not really
161 // types of their own, so they need special handling. We still need a
162 // UniqueTypeId for them, since to debuginfo they *are* real types.
163 fn get_unique_type_id_of_enum_variant
<'a
>(&mut self,
164 cx
: &CrateContext
<'a
, 'tcx
>,
168 let enum_type_id
= self.get_unique_type_id_of_type(cx
, enum_type
);
169 let enum_variant_type_id
= format
!("{}::{}",
170 self.get_unique_type_id_as_string(enum_type_id
),
172 let interner_key
= self.unique_id_interner
.intern(&enum_variant_type_id
);
173 UniqueTypeId(interner_key
)
177 // A description of some recursive type. It can either be already finished (as
178 // with FinalMetadata) or it is not yet finished, but contains all information
179 // needed to generate the missing parts of the description. See the
180 // documentation section on Recursive Types at the top of this file for more
182 enum RecursiveTypeDescription
<'tcx
> {
184 unfinished_type
: Ty
<'tcx
>,
185 unique_type_id
: UniqueTypeId
,
186 metadata_stub
: DICompositeType
,
188 member_description_factory
: MemberDescriptionFactory
<'tcx
>,
190 FinalMetadata(DICompositeType
)
193 fn create_and_register_recursive_type_forward_declaration
<'a
, 'tcx
>(
194 cx
: &CrateContext
<'a
, 'tcx
>,
195 unfinished_type
: Ty
<'tcx
>,
196 unique_type_id
: UniqueTypeId
,
197 metadata_stub
: DICompositeType
,
199 member_description_factory
: MemberDescriptionFactory
<'tcx
>)
200 -> RecursiveTypeDescription
<'tcx
> {
202 // Insert the stub into the TypeMap in order to allow for recursive references
203 let mut type_map
= debug_context(cx
).type_map
.borrow_mut();
204 type_map
.register_unique_id_with_metadata(unique_type_id
, metadata_stub
);
205 type_map
.register_type_with_metadata(unfinished_type
, metadata_stub
);
212 member_description_factory
,
216 impl<'tcx
> RecursiveTypeDescription
<'tcx
> {
217 // Finishes up the description of the type in question (mostly by providing
218 // descriptions of the fields of the given type) and returns the final type
220 fn finalize
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>) -> MetadataCreationResult
{
222 FinalMetadata(metadata
) => MetadataCreationResult
::new(metadata
, false),
228 ref member_description_factory
,
231 // Make sure that we have a forward declaration of the type in
232 // the TypeMap so that recursive references are possible. This
233 // will always be the case if the RecursiveTypeDescription has
234 // been properly created through the
235 // create_and_register_recursive_type_forward_declaration()
238 let type_map
= debug_context(cx
).type_map
.borrow();
239 if type_map
.find_metadata_for_unique_id(unique_type_id
).is_none() ||
240 type_map
.find_metadata_for_type(unfinished_type
).is_none() {
241 bug
!("Forward declaration of potentially recursive type \
242 '{:?}' was not found in TypeMap!",
247 // ... then create the member descriptions ...
248 let member_descriptions
=
249 member_description_factory
.create_member_descriptions(cx
);
251 // ... and attach them to the stub to complete it.
252 set_members_of_composite_type(cx
,
255 &member_descriptions
[..]);
256 return MetadataCreationResult
::new(metadata_stub
, true);
262 // Returns from the enclosing function if the type metadata with the given
263 // unique id can be found in the type map
264 macro_rules
! return_if_metadata_created_in_meantime
{
265 ($cx
: expr
, $unique_type_id
: expr
) => (
266 match debug_context($cx
).type_map
268 .find_metadata_for_unique_id($unique_type_id
) {
269 Some(metadata
) => return MetadataCreationResult
::new(metadata
, true),
270 None
=> { /* proceed normally */ }
275 fn fixed_vec_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
276 unique_type_id
: UniqueTypeId
,
277 element_type
: Ty
<'tcx
>,
280 -> MetadataCreationResult
{
281 let element_type_metadata
= type_metadata(cx
, element_type
, span
);
283 return_if_metadata_created_in_meantime
!(cx
, unique_type_id
);
285 let element_llvm_type
= type_of
::type_of(cx
, element_type
);
286 let (element_type_size
, element_type_align
) = size_and_align_of(cx
, element_llvm_type
);
288 let (array_size_in_bytes
, upper_bound
) = match len
{
289 Some(len
) => (element_type_size
* len
, len
as c_longlong
),
293 let subrange
= unsafe {
294 llvm
::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx
), 0, upper_bound
)
297 let subscripts
= create_DIArray(DIB(cx
), &[subrange
]);
298 let metadata
= unsafe {
299 llvm
::LLVMRustDIBuilderCreateArrayType(
301 bytes_to_bits(array_size_in_bytes
),
302 bytes_to_bits(element_type_align
),
303 element_type_metadata
,
307 return MetadataCreationResult
::new(metadata
, false);
310 fn vec_slice_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
312 element_type
: Ty
<'tcx
>,
313 unique_type_id
: UniqueTypeId
,
315 -> MetadataCreationResult
{
316 let data_ptr_type
= cx
.tcx().mk_ptr(ty
::TypeAndMut
{
318 mutbl
: hir
::MutImmutable
321 let element_type_metadata
= type_metadata(cx
, data_ptr_type
, span
);
323 return_if_metadata_created_in_meantime
!(cx
, unique_type_id
);
325 let slice_llvm_type
= type_of
::type_of(cx
, vec_type
);
326 let slice_type_name
= compute_debuginfo_type_name(cx
, vec_type
, true);
328 let member_llvm_types
= slice_llvm_type
.field_types();
329 assert
!(slice_layout_is_correct(cx
,
330 &member_llvm_types
[..],
332 let member_descriptions
= [
334 name
: "data_ptr".to_string(),
335 llvm_type
: member_llvm_types
[0],
336 type_metadata
: element_type_metadata
,
337 offset
: ComputedMemberOffset
,
338 flags
: DIFlags
::FlagZero
,
341 name
: "length".to_string(),
342 llvm_type
: member_llvm_types
[1],
343 type_metadata
: type_metadata(cx
, cx
.tcx().types
.usize, span
),
344 offset
: ComputedMemberOffset
,
345 flags
: DIFlags
::FlagZero
,
349 assert
!(member_descriptions
.len() == member_llvm_types
.len());
351 let file_metadata
= unknown_file_metadata(cx
);
353 let metadata
= composite_type_metadata(cx
,
355 &slice_type_name
[..],
357 &member_descriptions
,
361 return MetadataCreationResult
::new(metadata
, false);
363 fn slice_layout_is_correct
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
364 member_llvm_types
: &[Type
],
365 element_type
: Ty
<'tcx
>)
367 member_llvm_types
.len() == 2 &&
368 member_llvm_types
[0] == type_of
::type_of(cx
, element_type
).ptr_to() &&
369 member_llvm_types
[1] == cx
.isize_ty()
373 fn subroutine_type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
374 unique_type_id
: UniqueTypeId
,
375 signature
: ty
::PolyFnSig
<'tcx
>,
377 -> MetadataCreationResult
379 let signature
= cx
.tcx().erase_late_bound_regions_and_normalize(&signature
);
381 let mut signature_metadata
: Vec
<DIType
> = Vec
::with_capacity(signature
.inputs().len() + 1);
384 signature_metadata
.push(match signature
.output().sty
{
385 ty
::TyTuple(ref tys
, _
) if tys
.is_empty() => ptr
::null_mut(),
386 _
=> type_metadata(cx
, signature
.output(), span
)
390 for &argument_type
in signature
.inputs() {
391 signature_metadata
.push(type_metadata(cx
, argument_type
, span
));
394 return_if_metadata_created_in_meantime
!(cx
, unique_type_id
);
396 return MetadataCreationResult
::new(
398 llvm
::LLVMRustDIBuilderCreateSubroutineType(
400 unknown_file_metadata(cx
),
401 create_DIArray(DIB(cx
), &signature_metadata
[..]))
406 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
407 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
408 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
409 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
410 // of a DST struct, there is no trait_object_type and the results of this
411 // function will be a little bit weird.
412 fn trait_pointer_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
413 trait_type
: Ty
<'tcx
>,
414 trait_object_type
: Option
<Ty
<'tcx
>>,
415 unique_type_id
: UniqueTypeId
)
417 // The implementation provided here is a stub. It makes sure that the trait
418 // type is assigned the correct name, size, namespace, and source location.
419 // But it does not describe the trait's methods.
421 let containing_scope
= match trait_type
.sty
{
422 ty
::TyDynamic(ref data
, ..) => if let Some(principal
) = data
.principal() {
423 let def_id
= principal
.def_id();
424 get_namespace_for_item(cx
, def_id
)
429 bug
!("debuginfo: Unexpected trait-object type in \
430 trait_pointer_metadata(): {:?}",
435 let trait_object_type
= trait_object_type
.unwrap_or(trait_type
);
436 let trait_type_name
=
437 compute_debuginfo_type_name(cx
, trait_object_type
, false);
439 let trait_llvm_type
= type_of
::type_of(cx
, trait_object_type
);
440 let file_metadata
= unknown_file_metadata(cx
);
443 let ptr_type
= cx
.tcx().mk_ptr(ty
::TypeAndMut
{
444 ty
: cx
.tcx().types
.u8,
445 mutbl
: hir
::MutImmutable
447 let ptr_type_metadata
= type_metadata(cx
, ptr_type
, syntax_pos
::DUMMY_SP
);
448 let llvm_type
= type_of
::type_of(cx
, ptr_type
);
450 assert_eq
!(abi
::FAT_PTR_ADDR
, 0);
451 assert_eq
!(abi
::FAT_PTR_EXTRA
, 1);
452 let member_descriptions
= [
454 name
: "pointer".to_string(),
455 llvm_type
: llvm_type
,
456 type_metadata
: ptr_type_metadata
,
457 offset
: ComputedMemberOffset
,
458 flags
: DIFlags
::FlagArtificial
,
461 name
: "vtable".to_string(),
462 llvm_type
: llvm_type
,
463 type_metadata
: ptr_type_metadata
,
464 offset
: ComputedMemberOffset
,
465 flags
: DIFlags
::FlagArtificial
,
469 composite_type_metadata(cx
,
471 &trait_type_name
[..],
473 &member_descriptions
,
476 syntax_pos
::DUMMY_SP
)
479 pub fn type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
481 usage_site_span
: Span
)
483 // Get the unique type id of this type.
484 let unique_type_id
= {
485 let mut type_map
= debug_context(cx
).type_map
.borrow_mut();
486 // First, try to find the type in TypeMap. If we have seen it before, we
487 // can exit early here.
488 match type_map
.find_metadata_for_type(t
) {
493 // The Ty is not in the TypeMap but maybe we have already seen
494 // an equivalent type (e.g. only differing in region arguments).
495 // In order to find out, generate the unique type id and look
497 let unique_type_id
= type_map
.get_unique_type_id_of_type(cx
, t
);
498 match type_map
.find_metadata_for_unique_id(unique_type_id
) {
500 // There is already an equivalent type in the TypeMap.
501 // Register this Ty as an alias in the cache and
502 // return the cached metadata.
503 type_map
.register_type_with_metadata(t
, metadata
);
507 // There really is no type metadata for this type, so
508 // proceed by creating it.
516 debug
!("type_metadata: {:?}", t
);
518 let ptr_metadata
= |ty
: Ty
<'tcx
>| {
520 ty
::TySlice(typ
) => {
521 Ok(vec_slice_metadata(cx
, t
, typ
, unique_type_id
, usage_site_span
))
524 Ok(vec_slice_metadata(cx
, t
, cx
.tcx().types
.u8, unique_type_id
, usage_site_span
))
526 ty
::TyDynamic(..) => {
527 Ok(MetadataCreationResult
::new(
528 trait_pointer_metadata(cx
, ty
, Some(t
), unique_type_id
),
532 let pointee_metadata
= type_metadata(cx
, ty
, usage_site_span
);
534 match debug_context(cx
).type_map
536 .find_metadata_for_unique_id(unique_type_id
) {
537 Some(metadata
) => return Err(metadata
),
538 None
=> { /* proceed normally */ }
541 Ok(MetadataCreationResult
::new(pointer_type_metadata(cx
, t
, pointee_metadata
),
547 let MetadataCreationResult { metadata, already_stored_in_typemap }
= match t
.sty
{
554 MetadataCreationResult
::new(basic_type_metadata(cx
, t
), false)
556 ty
::TyTuple(ref elements
, _
) if elements
.is_empty() => {
557 MetadataCreationResult
::new(basic_type_metadata(cx
, t
), false)
559 ty
::TyArray(typ
, len
) => {
560 let len
= len
.val
.to_const_int().unwrap().to_u64().unwrap();
561 fixed_vec_metadata(cx
, unique_type_id
, typ
, Some(len
), usage_site_span
)
563 ty
::TySlice(typ
) => {
564 fixed_vec_metadata(cx
, unique_type_id
, typ
, None
, usage_site_span
)
567 fixed_vec_metadata(cx
, unique_type_id
, cx
.tcx().types
.i8, None
, usage_site_span
)
569 ty
::TyDynamic(..) => {
570 MetadataCreationResult
::new(
571 trait_pointer_metadata(cx
, t
, None
, unique_type_id
),
574 ty
::TyForeign(..) => {
575 MetadataCreationResult
::new(
576 foreign_type_metadata(cx
, t
, unique_type_id
),
579 ty
::TyRawPtr(ty
::TypeAndMut{ty, ..}
) |
580 ty
::TyRef(_
, ty
::TypeAndMut{ty, ..}
) => {
581 match ptr_metadata(ty
) {
583 Err(metadata
) => return metadata
,
586 ty
::TyAdt(def
, _
) if def
.is_box() => {
587 match ptr_metadata(t
.boxed_ty()) {
589 Err(metadata
) => return metadata
,
592 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) => {
593 let fn_metadata
= subroutine_type_metadata(cx
,
596 usage_site_span
).metadata
;
597 match debug_context(cx
).type_map
599 .find_metadata_for_unique_id(unique_type_id
) {
600 Some(metadata
) => return metadata
,
601 None
=> { /* proceed normally */ }
604 // This is actually a function pointer, so wrap it in pointer DI
605 MetadataCreationResult
::new(pointer_type_metadata(cx
, t
, fn_metadata
), false)
608 ty
::TyClosure(def_id
, substs
) => {
609 let upvar_tys
: Vec
<_
> = substs
.upvar_tys(def_id
, cx
.tcx()).collect();
610 prepare_tuple_metadata(cx
,
614 usage_site_span
).finalize(cx
)
616 ty
::TyGenerator(def_id
, substs
, _
) => {
617 let upvar_tys
: Vec
<_
> = substs
.field_tys(def_id
, cx
.tcx()).map(|t
| {
618 cx
.tcx().fully_normalize_associated_types_in(&t
)
620 prepare_tuple_metadata(cx
,
624 usage_site_span
).finalize(cx
)
626 ty
::TyAdt(def
, ..) => match def
.adt_kind() {
628 prepare_struct_metadata(cx
,
631 usage_site_span
).finalize(cx
)
634 prepare_union_metadata(cx
,
637 usage_site_span
).finalize(cx
)
640 prepare_enum_metadata(cx
,
644 usage_site_span
).finalize(cx
)
647 ty
::TyTuple(ref elements
, _
) => {
648 prepare_tuple_metadata(cx
,
652 usage_site_span
).finalize(cx
)
655 bug
!("debuginfo: unexpected type in type_metadata: {:?}", t
)
660 let mut type_map
= debug_context(cx
).type_map
.borrow_mut();
662 if already_stored_in_typemap
{
663 // Also make sure that we already have a TypeMap entry for the unique type id.
664 let metadata_for_uid
= match type_map
.find_metadata_for_unique_id(unique_type_id
) {
665 Some(metadata
) => metadata
,
667 span_bug
!(usage_site_span
,
668 "Expected type metadata for unique \
669 type id '{}' to already be in \
670 the debuginfo::TypeMap but it \
672 type_map
.get_unique_type_id_as_string(unique_type_id
),
677 match type_map
.find_metadata_for_type(t
) {
679 if metadata
!= metadata_for_uid
{
680 span_bug
!(usage_site_span
,
681 "Mismatch between Ty and \
682 UniqueTypeId maps in \
683 debuginfo::TypeMap. \
684 UniqueTypeId={}, Ty={}",
685 type_map
.get_unique_type_id_as_string(unique_type_id
),
690 type_map
.register_type_with_metadata(t
, metadata
);
694 type_map
.register_type_with_metadata(t
, metadata
);
695 type_map
.register_unique_id_with_metadata(unique_type_id
, metadata
);
702 pub fn file_metadata(cx
: &CrateContext
,
704 defining_crate
: CrateNum
) -> DIFile
{
705 debug
!("file_metadata: file_name: {}, defining_crate: {}",
709 let directory
= if defining_crate
== LOCAL_CRATE
{
710 &cx
.sess().working_dir
.0[..]
712 // If the path comes from an upstream crate we assume it has been made
713 // independent of the compiler's working directory one way or another.
717 file_metadata_raw(cx
, file_name
, directory
)
720 pub fn unknown_file_metadata(cx
: &CrateContext
) -> DIFile
{
721 file_metadata_raw(cx
, "<unknown>", "")
724 fn file_metadata_raw(cx
: &CrateContext
,
728 let key
= (Symbol
::intern(file_name
), Symbol
::intern(directory
));
730 if let Some(file_metadata
) = debug_context(cx
).created_files
.borrow().get(&key
) {
731 return *file_metadata
;
734 debug
!("file_metadata: file_name: {}, directory: {}", file_name
, directory
);
736 let file_name
= CString
::new(file_name
).unwrap();
737 let directory
= CString
::new(directory
).unwrap();
739 let file_metadata
= unsafe {
740 llvm
::LLVMRustDIBuilderCreateFile(DIB(cx
),
745 let mut created_files
= debug_context(cx
).created_files
.borrow_mut();
746 created_files
.insert(key
, file_metadata
);
750 fn basic_type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
751 t
: Ty
<'tcx
>) -> DIType
{
753 debug
!("basic_type_metadata: {:?}", t
);
755 let (name
, encoding
) = match t
.sty
{
756 ty
::TyNever
=> ("!", DW_ATE_unsigned
),
757 ty
::TyTuple(ref elements
, _
) if elements
.is_empty() =>
758 ("()", DW_ATE_unsigned
),
759 ty
::TyBool
=> ("bool", DW_ATE_boolean
),
760 ty
::TyChar
=> ("char", DW_ATE_unsigned_char
),
761 ty
::TyInt(int_ty
) => {
762 (int_ty
.ty_to_string(), DW_ATE_signed
)
764 ty
::TyUint(uint_ty
) => {
765 (uint_ty
.ty_to_string(), DW_ATE_unsigned
)
767 ty
::TyFloat(float_ty
) => {
768 (float_ty
.ty_to_string(), DW_ATE_float
)
770 _
=> bug
!("debuginfo::basic_type_metadata - t is invalid type")
773 let llvm_type
= type_of
::type_of(cx
, t
);
774 let (size
, align
) = size_and_align_of(cx
, llvm_type
);
775 let name
= CString
::new(name
).unwrap();
776 let ty_metadata
= unsafe {
777 llvm
::LLVMRustDIBuilderCreateBasicType(
781 bytes_to_bits(align
),
788 fn foreign_type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
790 unique_type_id
: UniqueTypeId
) -> DIType
{
791 debug
!("foreign_type_metadata: {:?}", t
);
793 let llvm_type
= type_of
::type_of(cx
, t
);
795 let name
= compute_debuginfo_type_name(cx
, t
, false);
796 create_struct_stub(cx
, llvm_type
, &name
, unique_type_id
, NO_SCOPE_METADATA
)
799 fn pointer_type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
800 pointer_type
: Ty
<'tcx
>,
801 pointee_type_metadata
: DIType
)
803 let pointer_llvm_type
= type_of
::type_of(cx
, pointer_type
);
804 let (pointer_size
, pointer_align
) = size_and_align_of(cx
, pointer_llvm_type
);
805 let name
= compute_debuginfo_type_name(cx
, pointer_type
, false);
806 let name
= CString
::new(name
).unwrap();
807 let ptr_metadata
= unsafe {
808 llvm
::LLVMRustDIBuilderCreatePointerType(
810 pointee_type_metadata
,
811 bytes_to_bits(pointer_size
),
812 bytes_to_bits(pointer_align
),
818 pub fn compile_unit_metadata(scc
: &SharedCrateContext
,
819 codegen_unit_name
: &str,
820 debug_context
: &CrateDebugContext
,
823 let mut name_in_debuginfo
= match sess
.local_crate_source_file
{
824 Some(ref path
) => path
.clone(),
825 None
=> scc
.tcx().crate_name(LOCAL_CRATE
).to_string(),
828 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
829 // if multiple object files with the same DW_AT_name are linked together.
830 // As a workaround we generate unique names for each object file. Those do
831 // not correspond to an actual source file but that should be harmless.
832 if scc
.sess().target
.target
.options
.is_like_osx
{
833 name_in_debuginfo
.push_str("@");
834 name_in_debuginfo
.push_str(codegen_unit_name
);
837 debug
!("compile_unit_metadata: {:?}", name_in_debuginfo
);
838 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
839 let producer
= format
!("clang LLVM (rustc version {})",
840 (option_env
!("CFG_VERSION")).expect("CFG_VERSION"));
842 let name_in_debuginfo
= CString
::new(name_in_debuginfo
).unwrap();
843 let work_dir
= CString
::new(&sess
.working_dir
.0[..]).unwrap();
844 let producer
= CString
::new(producer
).unwrap();
846 let split_name
= "\0";
849 let file_metadata
= llvm
::LLVMRustDIBuilderCreateFile(
850 debug_context
.builder
, name_in_debuginfo
.as_ptr(), work_dir
.as_ptr());
852 let unit_metadata
= llvm
::LLVMRustDIBuilderCreateCompileUnit(
853 debug_context
.builder
,
857 sess
.opts
.optimize
!= config
::OptLevel
::No
,
858 flags
.as_ptr() as *const _
,
860 split_name
.as_ptr() as *const _
);
862 if sess
.opts
.debugging_opts
.profile
{
863 let cu_desc_metadata
= llvm
::LLVMRustMetadataAsValue(debug_context
.llcontext
,
867 path_to_mdstring(debug_context
.llcontext
,
868 &scc
.tcx().output_filenames(LOCAL_CRATE
).with_extension("gcno")),
869 path_to_mdstring(debug_context
.llcontext
,
870 &scc
.tcx().output_filenames(LOCAL_CRATE
).with_extension("gcda")),
873 let gcov_metadata
= llvm
::LLVMMDNodeInContext(debug_context
.llcontext
,
874 gcov_cu_info
.as_ptr(),
875 gcov_cu_info
.len() as c_uint
);
877 let llvm_gcov_ident
= CString
::new("llvm.gcov").unwrap();
878 llvm
::LLVMAddNamedMetadataOperand(debug_context
.llmod
,
879 llvm_gcov_ident
.as_ptr(),
883 return unit_metadata
;
886 fn path_to_mdstring(llcx
: llvm
::ContextRef
, path
: &Path
) -> llvm
::ValueRef
{
887 let path_str
= path2cstr(path
);
889 llvm
::LLVMMDStringInContext(llcx
,
891 path_str
.as_bytes().len() as c_uint
)
896 struct MetadataCreationResult
{
898 already_stored_in_typemap
: bool
901 impl MetadataCreationResult
{
902 fn new(metadata
: DIType
, already_stored_in_typemap
: bool
) -> MetadataCreationResult
{
903 MetadataCreationResult
{
905 already_stored_in_typemap
,
912 FixedMemberOffset { bytes: usize }
,
913 // For ComputedMemberOffset, the offset is read from the llvm type definition.
917 // Description of a type member, which can either be a regular field (as in
918 // structs or tuples) or an enum variant.
920 struct MemberDescription
{
923 type_metadata
: DIType
,
924 offset
: MemberOffset
,
928 // A factory for MemberDescriptions. It produces a list of member descriptions
929 // for some record-like type. MemberDescriptionFactories are used to defer the
930 // creation of type member descriptions in order to break cycles arising from
931 // recursive type definitions.
932 enum MemberDescriptionFactory
<'tcx
> {
933 StructMDF(StructMemberDescriptionFactory
<'tcx
>),
934 TupleMDF(TupleMemberDescriptionFactory
<'tcx
>),
935 EnumMDF(EnumMemberDescriptionFactory
<'tcx
>),
936 UnionMDF(UnionMemberDescriptionFactory
<'tcx
>),
937 VariantMDF(VariantMemberDescriptionFactory
<'tcx
>)
940 impl<'tcx
> MemberDescriptionFactory
<'tcx
> {
941 fn create_member_descriptions
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>)
942 -> Vec
<MemberDescription
> {
944 StructMDF(ref this
) => {
945 this
.create_member_descriptions(cx
)
947 TupleMDF(ref this
) => {
948 this
.create_member_descriptions(cx
)
950 EnumMDF(ref this
) => {
951 this
.create_member_descriptions(cx
)
953 UnionMDF(ref this
) => {
954 this
.create_member_descriptions(cx
)
956 VariantMDF(ref this
) => {
957 this
.create_member_descriptions(cx
)
963 //=-----------------------------------------------------------------------------
965 //=-----------------------------------------------------------------------------
967 // Creates MemberDescriptions for the fields of a struct
968 struct StructMemberDescriptionFactory
<'tcx
> {
970 variant
: &'tcx ty
::VariantDef
,
971 substs
: &'tcx Substs
<'tcx
>,
975 impl<'tcx
> StructMemberDescriptionFactory
<'tcx
> {
976 fn create_member_descriptions
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>)
977 -> Vec
<MemberDescription
> {
978 let layout
= cx
.layout_of(self.ty
);
981 let offsets
= match *layout
{
982 layout
::Univariant { ref variant, .. }
=> &variant
.offsets
,
983 layout
::Vector { element, count }
=> {
984 let element_size
= element
.size(cx
).bytes();
986 map(|i
| layout
::Size
::from_bytes(i
*element_size
))
987 .collect
::<Vec
<layout
::Size
>>();
990 _
=> bug
!("{} is not a struct", self.ty
)
993 self.variant
.fields
.iter().enumerate().map(|(i
, f
)| {
994 let name
= if self.variant
.ctor_kind
== CtorKind
::Fn
{
999 let fty
= monomorphize
::field_ty(cx
.tcx(), self.substs
, f
);
1001 let offset
= FixedMemberOffset { bytes: offsets[i].bytes() as usize}
;
1005 llvm_type
: type_of
::in_memory_type_of(cx
, fty
),
1006 type_metadata
: type_metadata(cx
, fty
, self.span
),
1008 flags
: DIFlags
::FlagZero
,
1015 fn prepare_struct_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
1016 struct_type
: Ty
<'tcx
>,
1017 unique_type_id
: UniqueTypeId
,
1019 -> RecursiveTypeDescription
<'tcx
> {
1020 let struct_name
= compute_debuginfo_type_name(cx
, struct_type
, false);
1021 let struct_llvm_type
= type_of
::in_memory_type_of(cx
, struct_type
);
1023 let (struct_def_id
, variant
, substs
) = match struct_type
.sty
{
1024 ty
::TyAdt(def
, substs
) => (def
.did
, def
.struct_variant(), substs
),
1025 _
=> bug
!("prepare_struct_metadata on a non-ADT")
1028 let containing_scope
= get_namespace_for_item(cx
, struct_def_id
);
1030 let struct_metadata_stub
= create_struct_stub(cx
,
1036 create_and_register_recursive_type_forward_declaration(
1040 struct_metadata_stub
,
1042 StructMDF(StructMemberDescriptionFactory
{
1051 //=-----------------------------------------------------------------------------
1053 //=-----------------------------------------------------------------------------
1055 // Creates MemberDescriptions for the fields of a tuple
1056 struct TupleMemberDescriptionFactory
<'tcx
> {
1058 component_types
: Vec
<Ty
<'tcx
>>,
1062 impl<'tcx
> TupleMemberDescriptionFactory
<'tcx
> {
1063 fn create_member_descriptions
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>)
1064 -> Vec
<MemberDescription
> {
1065 let layout
= cx
.layout_of(self.ty
);
1066 let offsets
= if let layout
::Univariant { ref variant, .. }
= *layout
{
1069 bug
!("{} is not a tuple", self.ty
);
1072 self.component_types
1075 .map(|(i
, &component_type
)| {
1077 name
: format
!("__{}", i
),
1078 llvm_type
: type_of
::type_of(cx
, component_type
),
1079 type_metadata
: type_metadata(cx
, component_type
, self.span
),
1080 offset
: FixedMemberOffset { bytes: offsets[i].bytes() as usize }
,
1081 flags
: DIFlags
::FlagZero
,
1087 fn prepare_tuple_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
1088 tuple_type
: Ty
<'tcx
>,
1089 component_types
: &[Ty
<'tcx
>],
1090 unique_type_id
: UniqueTypeId
,
1092 -> RecursiveTypeDescription
<'tcx
> {
1093 let tuple_name
= compute_debuginfo_type_name(cx
, tuple_type
, false);
1094 let tuple_llvm_type
= type_of
::type_of(cx
, tuple_type
);
1096 create_and_register_recursive_type_forward_declaration(
1100 create_struct_stub(cx
,
1106 TupleMDF(TupleMemberDescriptionFactory
{
1108 component_types
: component_types
.to_vec(),
1114 //=-----------------------------------------------------------------------------
1116 //=-----------------------------------------------------------------------------
1118 struct UnionMemberDescriptionFactory
<'tcx
> {
1119 variant
: &'tcx ty
::VariantDef
,
1120 substs
: &'tcx Substs
<'tcx
>,
1124 impl<'tcx
> UnionMemberDescriptionFactory
<'tcx
> {
1125 fn create_member_descriptions
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>)
1126 -> Vec
<MemberDescription
> {
1127 self.variant
.fields
.iter().map(|field
| {
1128 let fty
= monomorphize
::field_ty(cx
.tcx(), self.substs
, field
);
1130 name
: field
.name
.to_string(),
1131 llvm_type
: type_of
::type_of(cx
, fty
),
1132 type_metadata
: type_metadata(cx
, fty
, self.span
),
1133 offset
: FixedMemberOffset { bytes: 0 }
,
1134 flags
: DIFlags
::FlagZero
,
1140 fn prepare_union_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
1141 union_type
: Ty
<'tcx
>,
1142 unique_type_id
: UniqueTypeId
,
1144 -> RecursiveTypeDescription
<'tcx
> {
1145 let union_name
= compute_debuginfo_type_name(cx
, union_type
, false);
1146 let union_llvm_type
= type_of
::in_memory_type_of(cx
, union_type
);
1148 let (union_def_id
, variant
, substs
) = match union_type
.sty
{
1149 ty
::TyAdt(def
, substs
) => (def
.did
, def
.struct_variant(), substs
),
1150 _
=> bug
!("prepare_union_metadata on a non-ADT")
1153 let containing_scope
= get_namespace_for_item(cx
, union_def_id
);
1155 let union_metadata_stub
= create_union_stub(cx
,
1161 create_and_register_recursive_type_forward_declaration(
1165 union_metadata_stub
,
1167 UnionMDF(UnionMemberDescriptionFactory
{
1175 //=-----------------------------------------------------------------------------
1177 //=-----------------------------------------------------------------------------
1179 // Describes the members of an enum value: An enum is described as a union of
1180 // structs in DWARF. This MemberDescriptionFactory provides the description for
1181 // the members of this union; so for every variant of the given enum, this
1182 // factory will produce one MemberDescription (all with no name and a fixed
1183 // offset of zero bytes).
1184 struct EnumMemberDescriptionFactory
<'tcx
> {
1185 enum_type
: Ty
<'tcx
>,
1186 type_rep
: &'tcx layout
::Layout
,
1187 discriminant_type_metadata
: Option
<DIType
>,
1188 containing_scope
: DIScope
,
1189 file_metadata
: DIFile
,
1193 impl<'tcx
> EnumMemberDescriptionFactory
<'tcx
> {
1194 fn create_member_descriptions
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>)
1195 -> Vec
<MemberDescription
> {
1196 let adt
= &self.enum_type
.ty_adt_def().unwrap();
1197 let substs
= match self.enum_type
.sty
{
1198 ty
::TyAdt(def
, ref s
) if def
.adt_kind() == AdtKind
::Enum
=> s
,
1199 _
=> bug
!("{} is not an enum", self.enum_type
)
1201 match *self.type_rep
{
1202 layout
::General { ref variants, .. }
=> {
1203 let discriminant_info
= RegularDiscriminant(self.discriminant_type_metadata
1208 .map(|(i
, struct_def
)| {
1209 let (variant_type_metadata
,
1211 member_desc_factory
) =
1212 describe_enum_variant(cx
,
1217 self.containing_scope
,
1220 let member_descriptions
= member_desc_factory
1221 .create_member_descriptions(cx
);
1223 set_members_of_composite_type(cx
,
1224 variant_type_metadata
,
1226 &member_descriptions
);
1228 name
: "".to_string(),
1229 llvm_type
: variant_llvm_type
,
1230 type_metadata
: variant_type_metadata
,
1231 offset
: FixedMemberOffset { bytes: 0 }
,
1232 flags
: DIFlags
::FlagZero
1236 layout
::Univariant{ ref variant, .. }
=> {
1237 assert
!(adt
.variants
.len() <= 1);
1239 if adt
.variants
.is_empty() {
1242 let (variant_type_metadata
,
1244 member_description_factory
) =
1245 describe_enum_variant(cx
,
1250 self.containing_scope
,
1253 let member_descriptions
=
1254 member_description_factory
.create_member_descriptions(cx
);
1256 set_members_of_composite_type(cx
,
1257 variant_type_metadata
,
1259 &member_descriptions
[..]);
1262 name
: "".to_string(),
1263 llvm_type
: variant_llvm_type
,
1264 type_metadata
: variant_type_metadata
,
1265 offset
: FixedMemberOffset { bytes: 0 }
,
1266 flags
: DIFlags
::FlagZero
1271 layout
::RawNullablePointer { nndiscr: non_null_variant_index, .. }
=> {
1272 // As far as debuginfo is concerned, the pointer this enum
1273 // represents is still wrapped in a struct. This is to make the
1274 // DWARF representation of enums uniform.
1276 // First create a description of the artificial wrapper struct:
1277 let non_null_variant
= &adt
.variants
[non_null_variant_index
as usize];
1278 let non_null_variant_name
= non_null_variant
.name
.as_str();
1280 // The llvm type and metadata of the pointer
1281 let nnty
= monomorphize
::field_ty(cx
.tcx(), &substs
, &non_null_variant
.fields
[0] );
1282 let non_null_llvm_type
= type_of
::type_of(cx
, nnty
);
1283 let non_null_type_metadata
= type_metadata(cx
, nnty
, self.span
);
1285 // The type of the artificial struct wrapping the pointer
1286 let artificial_struct_llvm_type
= Type
::struct_(cx
,
1287 &[non_null_llvm_type
],
1290 // For the metadata of the wrapper struct, we need to create a
1291 // MemberDescription of the struct's single field.
1292 let sole_struct_member_description
= MemberDescription
{
1293 name
: match non_null_variant
.ctor_kind
{
1294 CtorKind
::Fn
=> "__0".to_string(),
1295 CtorKind
::Fictive
=> {
1296 non_null_variant
.fields
[0].name
.to_string()
1298 CtorKind
::Const
=> bug
!()
1300 llvm_type
: non_null_llvm_type
,
1301 type_metadata
: non_null_type_metadata
,
1302 offset
: FixedMemberOffset { bytes: 0 }
,
1303 flags
: DIFlags
::FlagZero
1306 let unique_type_id
= debug_context(cx
).type_map
1308 .get_unique_type_id_of_enum_variant(
1311 &non_null_variant_name
);
1313 // Now we can create the metadata of the artificial struct
1314 let artificial_struct_metadata
=
1315 composite_type_metadata(cx
,
1316 artificial_struct_llvm_type
,
1317 &non_null_variant_name
,
1319 &[sole_struct_member_description
],
1320 self.containing_scope
,
1322 syntax_pos
::DUMMY_SP
);
1324 // Encode the information about the null variant in the union
1326 let null_variant_index
= (1 - non_null_variant_index
) as usize;
1327 let null_variant_name
= adt
.variants
[null_variant_index
].name
;
1328 let union_member_name
= format
!("RUST$ENCODED$ENUM${}${}",
1332 // Finally create the (singleton) list of descriptions of union
1336 name
: union_member_name
,
1337 llvm_type
: artificial_struct_llvm_type
,
1338 type_metadata
: artificial_struct_metadata
,
1339 offset
: FixedMemberOffset { bytes: 0 }
,
1340 flags
: DIFlags
::FlagZero
1344 layout
::StructWrappedNullablePointer
{ nonnull
: ref struct_def
,
1346 ref discrfield_source
, ..} => {
1347 // Create a description of the non-null variant
1348 let (variant_type_metadata
, variant_llvm_type
, member_description_factory
) =
1349 describe_enum_variant(cx
,
1352 &adt
.variants
[nndiscr
as usize],
1353 OptimizedDiscriminant
,
1354 self.containing_scope
,
1357 let variant_member_descriptions
=
1358 member_description_factory
.create_member_descriptions(cx
);
1360 set_members_of_composite_type(cx
,
1361 variant_type_metadata
,
1363 &variant_member_descriptions
[..]);
1365 // Encode the information about the null variant in the union
1367 let null_variant_index
= (1 - nndiscr
) as usize;
1368 let null_variant_name
= adt
.variants
[null_variant_index
].name
;
1369 let discrfield_source
= discrfield_source
.iter()
1371 .map(|x
| x
.to_string())
1372 .collect
::<Vec
<_
>>().join("$");
1373 let union_member_name
= format
!("RUST$ENCODED$ENUM${}${}",
1377 // Create the (singleton) list of descriptions of union members.
1380 name
: union_member_name
,
1381 llvm_type
: variant_llvm_type
,
1382 type_metadata
: variant_type_metadata
,
1383 offset
: FixedMemberOffset { bytes: 0 }
,
1384 flags
: DIFlags
::FlagZero
1388 layout
::CEnum { .. }
=> span_bug
!(self.span
, "This should be unreachable."),
1389 ref l @ _
=> bug
!("Not an enum layout: {:#?}", l
)
1394 // Creates MemberDescriptions for the fields of a single enum variant.
1395 struct VariantMemberDescriptionFactory
<'tcx
> {
1396 // Cloned from the layout::Struct describing the variant.
1397 offsets
: &'tcx
[layout
::Size
],
1398 args
: Vec
<(String
, Ty
<'tcx
>)>,
1399 discriminant_type_metadata
: Option
<DIType
>,
1403 impl<'tcx
> VariantMemberDescriptionFactory
<'tcx
> {
1404 fn create_member_descriptions
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>)
1405 -> Vec
<MemberDescription
> {
1406 self.args
.iter().enumerate().map(|(i
, &(ref name
, ty
))| {
1408 name
: name
.to_string(),
1409 llvm_type
: type_of
::type_of(cx
, ty
),
1410 type_metadata
: match self.discriminant_type_metadata
{
1411 Some(metadata
) if i
== 0 => metadata
,
1412 _
=> type_metadata(cx
, ty
, self.span
)
1414 offset
: FixedMemberOffset { bytes: self.offsets[i].bytes() as usize }
,
1415 flags
: DIFlags
::FlagZero
1421 #[derive(Copy, Clone)]
1422 enum EnumDiscriminantInfo
{
1423 RegularDiscriminant(DIType
),
1424 OptimizedDiscriminant
,
1428 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1429 // of the variant, and (3) a MemberDescriptionFactory for producing the
1430 // descriptions of the fields of the variant. This is a rudimentary version of a
1431 // full RecursiveTypeDescription.
1432 fn describe_enum_variant
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
1433 enum_type
: Ty
<'tcx
>,
1434 struct_def
: &'tcx layout
::Struct
,
1435 variant
: &'tcx ty
::VariantDef
,
1436 discriminant_info
: EnumDiscriminantInfo
,
1437 containing_scope
: DIScope
,
1439 -> (DICompositeType
, Type
, MemberDescriptionFactory
<'tcx
>) {
1440 let substs
= match enum_type
.sty
{
1441 ty
::TyAdt(def
, s
) if def
.adt_kind() == AdtKind
::Enum
=> s
,
1442 ref t @ _
=> bug
!("{:#?} is not an enum", t
)
1445 let maybe_discr_and_signed
: Option
<(layout
::Integer
, bool
)> = match *cx
.layout_of(enum_type
) {
1446 layout
::CEnum {discr, ..}
=> Some((discr
, true)),
1447 layout
::General{discr, ..}
=> Some((discr
, false)),
1448 layout
::Univariant { .. }
1449 | layout
::RawNullablePointer { .. }
1450 | layout
::StructWrappedNullablePointer { .. }
=> None
,
1451 ref l @ _
=> bug
!("This should be unreachable. Type is {:#?} layout is {:#?}", enum_type
, l
)
1454 let mut field_tys
= variant
.fields
.iter().map(|f
| {
1455 monomorphize
::field_ty(cx
.tcx(), &substs
, f
)
1456 }).collect
::<Vec
<_
>>();
1458 if let Some((discr
, signed
)) = maybe_discr_and_signed
{
1459 field_tys
.insert(0, discr
.to_ty(&cx
.tcx(), signed
));
1463 let variant_llvm_type
=
1464 Type
::struct_(cx
, &field_tys
1466 .map(|t
| type_of
::type_of(cx
, t
))
1467 .collect
::<Vec
<_
>>()
1470 // Could do some consistency checks here: size, align, field count, discr type
1472 let variant_name
= variant
.name
.as_str();
1473 let unique_type_id
= debug_context(cx
).type_map
1475 .get_unique_type_id_of_enum_variant(
1480 let metadata_stub
= create_struct_stub(cx
,
1486 // Get the argument names from the enum variant info
1487 let mut arg_names
: Vec
<_
> = match variant
.ctor_kind
{
1488 CtorKind
::Const
=> vec
![],
1493 .map(|(i
, _
)| format
!("__{}", i
))
1496 CtorKind
::Fictive
=> {
1499 .map(|f
| f
.name
.to_string())
1504 // If this is not a univariant enum, there is also the discriminant field.
1505 match discriminant_info
{
1506 RegularDiscriminant(_
) => arg_names
.insert(0, "RUST$ENUM$DISR".to_string()),
1507 _
=> { /* do nothing */ }
1510 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1511 let args
: Vec
<(String
, Ty
)> = arg_names
.iter()
1512 .zip(field_tys
.iter())
1513 .map(|(s
, &t
)| (s
.to_string(), t
))
1516 let member_description_factory
=
1517 VariantMDF(VariantMemberDescriptionFactory
{
1518 offsets
: &struct_def
.offsets
[..],
1520 discriminant_type_metadata
: match discriminant_info
{
1521 RegularDiscriminant(discriminant_type_metadata
) => {
1522 Some(discriminant_type_metadata
)
1529 (metadata_stub
, variant_llvm_type
, member_description_factory
)
1532 fn prepare_enum_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
1533 enum_type
: Ty
<'tcx
>,
1535 unique_type_id
: UniqueTypeId
,
1537 -> RecursiveTypeDescription
<'tcx
> {
1538 let enum_name
= compute_debuginfo_type_name(cx
, enum_type
, false);
1540 let containing_scope
= get_namespace_for_item(cx
, enum_def_id
);
1541 // FIXME: This should emit actual file metadata for the enum, but we
1542 // currently can't get the necessary information when it comes to types
1543 // imported from other crates. Formerly we violated the ODR when performing
1544 // LTO because we emitted debuginfo for the same type with varying file
1545 // metadata, so as a workaround we pretend that the type comes from
1547 let file_metadata
= unknown_file_metadata(cx
);
1549 let def
= enum_type
.ty_adt_def().unwrap();
1550 let enumerators_metadata
: Vec
<DIDescriptor
> = def
.discriminants(cx
.tcx())
1553 let token
= v
.name
.as_str();
1554 let name
= CString
::new(token
.as_bytes()).unwrap();
1556 llvm
::LLVMRustDIBuilderCreateEnumerator(
1559 // FIXME: what if enumeration has i128 discriminant?
1560 discr
.to_u128_unchecked() as u64)
1565 let discriminant_type_metadata
= |inttype
: layout
::Integer
, signed
: bool
| {
1566 let disr_type_key
= (enum_def_id
, inttype
);
1567 let cached_discriminant_type_metadata
= debug_context(cx
).created_enum_disr_types
1569 .get(&disr_type_key
).cloned();
1570 match cached_discriminant_type_metadata
{
1571 Some(discriminant_type_metadata
) => discriminant_type_metadata
,
1573 let discriminant_llvm_type
= Type
::from_integer(cx
, inttype
);
1574 let (discriminant_size
, discriminant_align
) =
1575 size_and_align_of(cx
, discriminant_llvm_type
);
1576 let discriminant_base_type_metadata
=
1578 inttype
.to_ty(&cx
.tcx(), signed
),
1579 syntax_pos
::DUMMY_SP
);
1580 let discriminant_name
= get_enum_discriminant_name(cx
, enum_def_id
);
1582 let name
= CString
::new(discriminant_name
.as_bytes()).unwrap();
1583 let discriminant_type_metadata
= unsafe {
1584 llvm
::LLVMRustDIBuilderCreateEnumerationType(
1589 UNKNOWN_LINE_NUMBER
,
1590 bytes_to_bits(discriminant_size
),
1591 bytes_to_bits(discriminant_align
),
1592 create_DIArray(DIB(cx
), &enumerators_metadata
),
1593 discriminant_base_type_metadata
)
1596 debug_context(cx
).created_enum_disr_types
1598 .insert(disr_type_key
, discriminant_type_metadata
);
1600 discriminant_type_metadata
1605 let type_rep
= cx
.layout_of(enum_type
);
1607 let discriminant_type_metadata
= match *type_rep
{
1608 layout
::CEnum { discr, signed, .. }
=> {
1609 return FinalMetadata(discriminant_type_metadata(discr
, signed
))
1611 layout
::RawNullablePointer { .. }
|
1612 layout
::StructWrappedNullablePointer { .. }
|
1613 layout
::Univariant { .. }
=> None
,
1614 layout
::General { discr, .. }
=> Some(discriminant_type_metadata(discr
, false)),
1615 ref l @ _
=> bug
!("Not an enum layout: {:#?}", l
)
1618 let enum_llvm_type
= type_of
::type_of(cx
, enum_type
);
1619 let (enum_type_size
, enum_type_align
) = size_and_align_of(cx
, enum_llvm_type
);
1621 let enum_name
= CString
::new(enum_name
).unwrap();
1622 let unique_type_id_str
= CString
::new(
1623 debug_context(cx
).type_map
.borrow().get_unique_type_id_as_string(unique_type_id
).as_bytes()
1625 let enum_metadata
= unsafe {
1626 llvm
::LLVMRustDIBuilderCreateUnionType(
1631 UNKNOWN_LINE_NUMBER
,
1632 bytes_to_bits(enum_type_size
),
1633 bytes_to_bits(enum_type_align
),
1637 unique_type_id_str
.as_ptr())
1640 return create_and_register_recursive_type_forward_declaration(
1646 EnumMDF(EnumMemberDescriptionFactory
{
1648 type_rep
: type_rep
.layout
,
1649 discriminant_type_metadata
,
1656 fn get_enum_discriminant_name(cx
: &CrateContext
,
1659 cx
.tcx().item_name(def_id
)
1663 /// Creates debug information for a composite type, that is, anything that
1664 /// results in a LLVM struct.
1666 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1667 fn composite_type_metadata(cx
: &CrateContext
,
1668 composite_llvm_type
: Type
,
1669 composite_type_name
: &str,
1670 composite_type_unique_id
: UniqueTypeId
,
1671 member_descriptions
: &[MemberDescription
],
1672 containing_scope
: DIScope
,
1674 // Ignore source location information as long as it
1675 // can't be reconstructed for non-local crates.
1676 _file_metadata
: DIFile
,
1677 _definition_span
: Span
)
1678 -> DICompositeType
{
1679 // Create the (empty) struct metadata node ...
1680 let composite_type_metadata
= create_struct_stub(cx
,
1681 composite_llvm_type
,
1682 composite_type_name
,
1683 composite_type_unique_id
,
1685 // ... and immediately create and add the member descriptions.
1686 set_members_of_composite_type(cx
,
1687 composite_type_metadata
,
1688 composite_llvm_type
,
1689 member_descriptions
);
1691 return composite_type_metadata
;
1694 fn set_members_of_composite_type(cx
: &CrateContext
,
1695 composite_type_metadata
: DICompositeType
,
1696 composite_llvm_type
: Type
,
1697 member_descriptions
: &[MemberDescription
]) {
1698 // In some rare cases LLVM metadata uniquing would lead to an existing type
1699 // description being used instead of a new one created in
1700 // create_struct_stub. This would cause a hard to trace assertion in
1701 // DICompositeType::SetTypeArray(). The following check makes sure that we
1702 // get a better error message if this should happen again due to some
1705 let mut composite_types_completed
=
1706 debug_context(cx
).composite_types_completed
.borrow_mut();
1707 if composite_types_completed
.contains(&composite_type_metadata
) {
1708 bug
!("debuginfo::set_members_of_composite_type() - \
1709 Already completed forward declaration re-encountered.");
1711 composite_types_completed
.insert(composite_type_metadata
);
1715 let member_metadata
: Vec
<DIDescriptor
> = member_descriptions
1718 .map(|(i
, member_description
)| {
1719 let (member_size
, member_align
) = size_and_align_of(cx
, member_description
.llvm_type
);
1720 let member_offset
= match member_description
.offset
{
1721 FixedMemberOffset { bytes }
=> bytes
as u64,
1722 ComputedMemberOffset
=> machine
::llelement_offset(cx
, composite_llvm_type
, i
)
1725 let member_name
= member_description
.name
.as_bytes();
1726 let member_name
= CString
::new(member_name
).unwrap();
1728 llvm
::LLVMRustDIBuilderCreateMemberType(
1730 composite_type_metadata
,
1731 member_name
.as_ptr(),
1732 unknown_file_metadata(cx
),
1733 UNKNOWN_LINE_NUMBER
,
1734 bytes_to_bits(member_size
),
1735 bytes_to_bits(member_align
),
1736 bytes_to_bits(member_offset
),
1737 member_description
.flags
,
1738 member_description
.type_metadata
)
1744 let type_array
= create_DIArray(DIB(cx
), &member_metadata
[..]);
1745 llvm
::LLVMRustDICompositeTypeSetTypeArray(
1746 DIB(cx
), composite_type_metadata
, type_array
);
1750 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1751 // any caching, does not add any fields to the struct. This can be done later
1752 // with set_members_of_composite_type().
1753 fn create_struct_stub(cx
: &CrateContext
,
1754 struct_llvm_type
: Type
,
1755 struct_type_name
: &str,
1756 unique_type_id
: UniqueTypeId
,
1757 containing_scope
: DIScope
)
1758 -> DICompositeType
{
1759 let (struct_size
, struct_align
) = size_and_align_of(cx
, struct_llvm_type
);
1761 let name
= CString
::new(struct_type_name
).unwrap();
1762 let unique_type_id
= CString
::new(
1763 debug_context(cx
).type_map
.borrow().get_unique_type_id_as_string(unique_type_id
).as_bytes()
1765 let metadata_stub
= unsafe {
1766 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1767 // pointer will lead to hard to trace and debug LLVM assertions
1768 // later on in llvm/lib/IR/Value.cpp.
1769 let empty_array
= create_DIArray(DIB(cx
), &[]);
1771 llvm
::LLVMRustDIBuilderCreateStructType(
1775 unknown_file_metadata(cx
),
1776 UNKNOWN_LINE_NUMBER
,
1777 bytes_to_bits(struct_size
),
1778 bytes_to_bits(struct_align
),
1784 unique_type_id
.as_ptr())
1787 return metadata_stub
;
1790 fn create_union_stub(cx
: &CrateContext
,
1791 union_llvm_type
: Type
,
1792 union_type_name
: &str,
1793 unique_type_id
: UniqueTypeId
,
1794 containing_scope
: DIScope
)
1795 -> DICompositeType
{
1796 let (union_size
, union_align
) = size_and_align_of(cx
, union_llvm_type
);
1798 let name
= CString
::new(union_type_name
).unwrap();
1799 let unique_type_id
= CString
::new(
1800 debug_context(cx
).type_map
.borrow().get_unique_type_id_as_string(unique_type_id
).as_bytes()
1802 let metadata_stub
= unsafe {
1803 // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
1804 // pointer will lead to hard to trace and debug LLVM assertions
1805 // later on in llvm/lib/IR/Value.cpp.
1806 let empty_array
= create_DIArray(DIB(cx
), &[]);
1808 llvm
::LLVMRustDIBuilderCreateUnionType(
1812 unknown_file_metadata(cx
),
1813 UNKNOWN_LINE_NUMBER
,
1814 bytes_to_bits(union_size
),
1815 bytes_to_bits(union_align
),
1819 unique_type_id
.as_ptr())
1822 return metadata_stub
;
1825 /// Creates debug information for the given global variable.
1827 /// Adds the created metadata nodes directly to the crate's IR.
1828 pub fn create_global_var_metadata(cx
: &CrateContext
,
1829 node_id
: ast
::NodeId
,
1831 if cx
.dbg_cx().is_none() {
1837 let node_def_id
= tcx
.hir
.local_def_id(node_id
);
1838 let var_scope
= get_namespace_for_item(cx
, node_def_id
);
1839 let span
= cx
.tcx().def_span(node_def_id
);
1841 let (file_metadata
, line_number
) = if span
!= syntax_pos
::DUMMY_SP
{
1842 let loc
= span_start(cx
, span
);
1843 (file_metadata(cx
, &loc
.file
.name
, LOCAL_CRATE
), loc
.line
as c_uint
)
1845 (unknown_file_metadata(cx
), UNKNOWN_LINE_NUMBER
)
1848 let is_local_to_unit
= is_node_local_to_unit(cx
, node_id
);
1849 let variable_type
= common
::def_ty(cx
.tcx(), node_def_id
, Substs
::empty());
1850 let type_metadata
= type_metadata(cx
, variable_type
, span
);
1851 let var_name
= tcx
.item_name(node_def_id
).to_string();
1852 let linkage_name
= mangled_name_of_item(cx
, node_def_id
, "");
1854 let var_name
= CString
::new(var_name
).unwrap();
1855 let linkage_name
= CString
::new(linkage_name
).unwrap();
1857 let global_align
= cx
.align_of(variable_type
);
1860 llvm
::LLVMRustDIBuilderCreateStaticVariable(DIB(cx
),
1863 linkage_name
.as_ptr(),
1875 // Creates an "extension" of an existing DIScope into another file.
1876 pub fn extend_scope_to_file(ccx
: &CrateContext
,
1877 scope_metadata
: DIScope
,
1878 file
: &syntax_pos
::FileMap
,
1879 defining_crate
: CrateNum
)
1881 let file_metadata
= file_metadata(ccx
, &file
.name
, defining_crate
);
1883 llvm
::LLVMRustDIBuilderCreateLexicalBlockFile(
1890 /// Creates debug information for the given vtable, which is for the
1893 /// Adds the created metadata nodes directly to the crate's IR.
1894 pub fn create_vtable_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
1897 if cx
.dbg_cx().is_none() {
1901 let type_metadata
= type_metadata(cx
, ty
, syntax_pos
::DUMMY_SP
);
1902 let llvm_vtable_type
= Type
::vtable_ptr(cx
).element_type();
1903 let (struct_size
, struct_align
) = size_and_align_of(cx
, llvm_vtable_type
);
1906 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1907 // pointer will lead to hard to trace and debug LLVM assertions
1908 // later on in llvm/lib/IR/Value.cpp.
1909 let empty_array
= create_DIArray(DIB(cx
), &[]);
1911 let name
= CString
::new("vtable").unwrap();
1913 // Create a new one each time. We don't want metadata caching
1914 // here, because each vtable will refer to a unique containing
1916 let vtable_type
= llvm
::LLVMRustDIBuilderCreateStructType(
1920 unknown_file_metadata(cx
),
1921 UNKNOWN_LINE_NUMBER
,
1922 bytes_to_bits(struct_size
),
1923 bytes_to_bits(struct_align
),
1924 DIFlags
::FlagArtificial
,
1932 llvm
::LLVMRustDIBuilderCreateStaticVariable(DIB(cx
),
1942 unknown_file_metadata(cx
),
1943 UNKNOWN_LINE_NUMBER
,