]> git.proxmox.com Git - rustc.git/blob - src/librustc_trans/debuginfo/metadata.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / librustc_trans / debuginfo / metadata.rs
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.
4 //
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.
10
11 use self::RecursiveTypeDescription::*;
12 use self::MemberOffset::*;
13 use self::MemberDescriptionFactory::*;
14 use self::EnumDiscriminantInfo::*;
15
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};
21 use abi;
22 use context::SharedCrateContext;
23
24 use llvm::{self, ValueRef};
25 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor,
26 DICompositeType, DILexicalBlock, DIFlags};
27
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;
33 use rustc::hir;
34 use rustc::ich::Fingerprint;
35 use {type_of, machine, monomorphize};
36 use common::{self, CrateContext};
37 use type_::Type;
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;
43
44 use libc::{c_uint, c_longlong};
45 use std::ffi::CString;
46 use std::ptr;
47 use std::path::Path;
48 use syntax::ast;
49 use syntax::symbol::{Interner, InternedString, Symbol};
50 use syntax_pos::{self, Span};
51
52
53 // From DWARF 5.
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;
66
67 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
68 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
69
70 // ptr::null() doesn't work :(
71 pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope);
72
73 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
74 pub struct UniqueTypeId(ast::Name);
75
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
79 // UniqueTypeIds.
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>
89 }
90
91 impl<'tcx> TypeMap<'tcx> {
92 pub fn new() -> TypeMap<'tcx> {
93 TypeMap {
94 unique_id_interner: Interner::new(),
95 type_to_metadata: FxHashMap(),
96 unique_id_to_metadata: FxHashMap(),
97 type_to_unique_id: FxHashMap(),
98 }
99 }
100
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,
104 type_: Ty<'tcx>,
105 metadata: DIType) {
106 if self.type_to_metadata.insert(type_, metadata).is_some() {
107 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
108 }
109 }
110
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,
115 metadata: DIType) {
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));
119 }
120 }
121
122 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
123 self.type_to_metadata.get(&type_).cloned()
124 }
125
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()
128 }
129
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)
135 }
136
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 */}
146 };
147
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();
153
154 let key = self.unique_id_interner.intern(&unique_type_id);
155 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
156
157 return UniqueTypeId(key);
158 }
159
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>,
165 enum_type: Ty<'tcx>,
166 variant_name: &str)
167 -> UniqueTypeId {
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),
171 variant_name);
172 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
173 UniqueTypeId(interner_key)
174 }
175 }
176
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
181 // information.
182 enum RecursiveTypeDescription<'tcx> {
183 UnfinishedMetadata {
184 unfinished_type: Ty<'tcx>,
185 unique_type_id: UniqueTypeId,
186 metadata_stub: DICompositeType,
187 llvm_type: Type,
188 member_description_factory: MemberDescriptionFactory<'tcx>,
189 },
190 FinalMetadata(DICompositeType)
191 }
192
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,
198 llvm_type: Type,
199 member_description_factory: MemberDescriptionFactory<'tcx>)
200 -> RecursiveTypeDescription<'tcx> {
201
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);
206
207 UnfinishedMetadata {
208 unfinished_type,
209 unique_type_id,
210 metadata_stub,
211 llvm_type,
212 member_description_factory,
213 }
214 }
215
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
219 // metadata.
220 fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
221 match *self {
222 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
223 UnfinishedMetadata {
224 unfinished_type,
225 unique_type_id,
226 metadata_stub,
227 llvm_type,
228 ref member_description_factory,
229 ..
230 } => {
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()
236 // function.
237 {
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!",
243 unfinished_type);
244 }
245 }
246
247 // ... then create the member descriptions ...
248 let member_descriptions =
249 member_description_factory.create_member_descriptions(cx);
250
251 // ... and attach them to the stub to complete it.
252 set_members_of_composite_type(cx,
253 metadata_stub,
254 llvm_type,
255 &member_descriptions[..]);
256 return MetadataCreationResult::new(metadata_stub, true);
257 }
258 }
259 }
260 }
261
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
267 .borrow()
268 .find_metadata_for_unique_id($unique_type_id) {
269 Some(metadata) => return MetadataCreationResult::new(metadata, true),
270 None => { /* proceed normally */ }
271 }
272 )
273 }
274
275 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
276 unique_type_id: UniqueTypeId,
277 element_type: Ty<'tcx>,
278 len: Option<u64>,
279 span: Span)
280 -> MetadataCreationResult {
281 let element_type_metadata = type_metadata(cx, element_type, span);
282
283 return_if_metadata_created_in_meantime!(cx, unique_type_id);
284
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);
287
288 let (array_size_in_bytes, upper_bound) = match len {
289 Some(len) => (element_type_size * len, len as c_longlong),
290 None => (0, -1)
291 };
292
293 let subrange = unsafe {
294 llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
295 };
296
297 let subscripts = create_DIArray(DIB(cx), &[subrange]);
298 let metadata = unsafe {
299 llvm::LLVMRustDIBuilderCreateArrayType(
300 DIB(cx),
301 bytes_to_bits(array_size_in_bytes),
302 bytes_to_bits(element_type_align),
303 element_type_metadata,
304 subscripts)
305 };
306
307 return MetadataCreationResult::new(metadata, false);
308 }
309
310 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
311 vec_type: Ty<'tcx>,
312 element_type: Ty<'tcx>,
313 unique_type_id: UniqueTypeId,
314 span: Span)
315 -> MetadataCreationResult {
316 let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
317 ty: element_type,
318 mutbl: hir::MutImmutable
319 });
320
321 let element_type_metadata = type_metadata(cx, data_ptr_type, span);
322
323 return_if_metadata_created_in_meantime!(cx, unique_type_id);
324
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);
327
328 let member_llvm_types = slice_llvm_type.field_types();
329 assert!(slice_layout_is_correct(cx,
330 &member_llvm_types[..],
331 element_type));
332 let member_descriptions = [
333 MemberDescription {
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,
339 },
340 MemberDescription {
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,
346 },
347 ];
348
349 assert!(member_descriptions.len() == member_llvm_types.len());
350
351 let file_metadata = unknown_file_metadata(cx);
352
353 let metadata = composite_type_metadata(cx,
354 slice_llvm_type,
355 &slice_type_name[..],
356 unique_type_id,
357 &member_descriptions,
358 NO_SCOPE_METADATA,
359 file_metadata,
360 span);
361 return MetadataCreationResult::new(metadata, false);
362
363 fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
364 member_llvm_types: &[Type],
365 element_type: Ty<'tcx>)
366 -> bool {
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()
370 }
371 }
372
373 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
374 unique_type_id: UniqueTypeId,
375 signature: ty::PolyFnSig<'tcx>,
376 span: Span)
377 -> MetadataCreationResult
378 {
379 let signature = cx.tcx().erase_late_bound_regions_and_normalize(&signature);
380
381 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs().len() + 1);
382
383 // return type
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)
387 });
388
389 // regular arguments
390 for &argument_type in signature.inputs() {
391 signature_metadata.push(type_metadata(cx, argument_type, span));
392 }
393
394 return_if_metadata_created_in_meantime!(cx, unique_type_id);
395
396 return MetadataCreationResult::new(
397 unsafe {
398 llvm::LLVMRustDIBuilderCreateSubroutineType(
399 DIB(cx),
400 unknown_file_metadata(cx),
401 create_DIArray(DIB(cx), &signature_metadata[..]))
402 },
403 false);
404 }
405
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)
416 -> DIType {
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.
420
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)
425 } else {
426 NO_SCOPE_METADATA
427 },
428 _ => {
429 bug!("debuginfo: Unexpected trait-object type in \
430 trait_pointer_metadata(): {:?}",
431 trait_type);
432 }
433 };
434
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);
438
439 let trait_llvm_type = type_of::type_of(cx, trait_object_type);
440 let file_metadata = unknown_file_metadata(cx);
441
442
443 let ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
444 ty: cx.tcx().types.u8,
445 mutbl: hir::MutImmutable
446 });
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);
449
450 assert_eq!(abi::FAT_PTR_ADDR, 0);
451 assert_eq!(abi::FAT_PTR_EXTRA, 1);
452 let member_descriptions = [
453 MemberDescription {
454 name: "pointer".to_string(),
455 llvm_type: llvm_type,
456 type_metadata: ptr_type_metadata,
457 offset: ComputedMemberOffset,
458 flags: DIFlags::FlagArtificial,
459 },
460 MemberDescription {
461 name: "vtable".to_string(),
462 llvm_type: llvm_type,
463 type_metadata: ptr_type_metadata,
464 offset: ComputedMemberOffset,
465 flags: DIFlags::FlagArtificial,
466 },
467 ];
468
469 composite_type_metadata(cx,
470 trait_llvm_type,
471 &trait_type_name[..],
472 unique_type_id,
473 &member_descriptions,
474 containing_scope,
475 file_metadata,
476 syntax_pos::DUMMY_SP)
477 }
478
479 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
480 t: Ty<'tcx>,
481 usage_site_span: Span)
482 -> DIType {
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) {
489 Some(metadata) => {
490 return metadata;
491 },
492 None => {
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
496 // that up.
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) {
499 Some(metadata) => {
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);
504 return metadata;
505 },
506 None => {
507 // There really is no type metadata for this type, so
508 // proceed by creating it.
509 unique_type_id
510 }
511 }
512 }
513 }
514 };
515
516 debug!("type_metadata: {:?}", t);
517
518 let ptr_metadata = |ty: Ty<'tcx>| {
519 match ty.sty {
520 ty::TySlice(typ) => {
521 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
522 }
523 ty::TyStr => {
524 Ok(vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span))
525 }
526 ty::TyDynamic(..) => {
527 Ok(MetadataCreationResult::new(
528 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
529 false))
530 }
531 _ => {
532 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
533
534 match debug_context(cx).type_map
535 .borrow()
536 .find_metadata_for_unique_id(unique_type_id) {
537 Some(metadata) => return Err(metadata),
538 None => { /* proceed normally */ }
539 };
540
541 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
542 false))
543 }
544 }
545 };
546
547 let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
548 ty::TyNever |
549 ty::TyBool |
550 ty::TyChar |
551 ty::TyInt(_) |
552 ty::TyUint(_) |
553 ty::TyFloat(_) => {
554 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
555 }
556 ty::TyTuple(ref elements, _) if elements.is_empty() => {
557 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
558 }
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)
562 }
563 ty::TySlice(typ) => {
564 fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
565 }
566 ty::TyStr => {
567 fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
568 }
569 ty::TyDynamic(..) => {
570 MetadataCreationResult::new(
571 trait_pointer_metadata(cx, t, None, unique_type_id),
572 false)
573 }
574 ty::TyForeign(..) => {
575 MetadataCreationResult::new(
576 foreign_type_metadata(cx, t, unique_type_id),
577 false)
578 }
579 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
580 ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
581 match ptr_metadata(ty) {
582 Ok(res) => res,
583 Err(metadata) => return metadata,
584 }
585 }
586 ty::TyAdt(def, _) if def.is_box() => {
587 match ptr_metadata(t.boxed_ty()) {
588 Ok(res) => res,
589 Err(metadata) => return metadata,
590 }
591 }
592 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
593 let fn_metadata = subroutine_type_metadata(cx,
594 unique_type_id,
595 t.fn_sig(cx.tcx()),
596 usage_site_span).metadata;
597 match debug_context(cx).type_map
598 .borrow()
599 .find_metadata_for_unique_id(unique_type_id) {
600 Some(metadata) => return metadata,
601 None => { /* proceed normally */ }
602 };
603
604 // This is actually a function pointer, so wrap it in pointer DI
605 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
606
607 }
608 ty::TyClosure(def_id, substs) => {
609 let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx()).collect();
610 prepare_tuple_metadata(cx,
611 t,
612 &upvar_tys,
613 unique_type_id,
614 usage_site_span).finalize(cx)
615 }
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)
619 }).collect();
620 prepare_tuple_metadata(cx,
621 t,
622 &upvar_tys,
623 unique_type_id,
624 usage_site_span).finalize(cx)
625 }
626 ty::TyAdt(def, ..) => match def.adt_kind() {
627 AdtKind::Struct => {
628 prepare_struct_metadata(cx,
629 t,
630 unique_type_id,
631 usage_site_span).finalize(cx)
632 }
633 AdtKind::Union => {
634 prepare_union_metadata(cx,
635 t,
636 unique_type_id,
637 usage_site_span).finalize(cx)
638 }
639 AdtKind::Enum => {
640 prepare_enum_metadata(cx,
641 t,
642 def.did,
643 unique_type_id,
644 usage_site_span).finalize(cx)
645 }
646 },
647 ty::TyTuple(ref elements, _) => {
648 prepare_tuple_metadata(cx,
649 t,
650 &elements[..],
651 unique_type_id,
652 usage_site_span).finalize(cx)
653 }
654 _ => {
655 bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
656 }
657 };
658
659 {
660 let mut type_map = debug_context(cx).type_map.borrow_mut();
661
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,
666 None => {
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 \
671 was not. (Ty = {})",
672 type_map.get_unique_type_id_as_string(unique_type_id),
673 t);
674 }
675 };
676
677 match type_map.find_metadata_for_type(t) {
678 Some(metadata) => {
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),
686 t);
687 }
688 }
689 None => {
690 type_map.register_type_with_metadata(t, metadata);
691 }
692 }
693 } else {
694 type_map.register_type_with_metadata(t, metadata);
695 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
696 }
697 }
698
699 metadata
700 }
701
702 pub fn file_metadata(cx: &CrateContext,
703 file_name: &str,
704 defining_crate: CrateNum) -> DIFile {
705 debug!("file_metadata: file_name: {}, defining_crate: {}",
706 file_name,
707 defining_crate);
708
709 let directory = if defining_crate == LOCAL_CRATE {
710 &cx.sess().working_dir.0[..]
711 } else {
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.
714 ""
715 };
716
717 file_metadata_raw(cx, file_name, directory)
718 }
719
720 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
721 file_metadata_raw(cx, "<unknown>", "")
722 }
723
724 fn file_metadata_raw(cx: &CrateContext,
725 file_name: &str,
726 directory: &str)
727 -> DIFile {
728 let key = (Symbol::intern(file_name), Symbol::intern(directory));
729
730 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(&key) {
731 return *file_metadata;
732 }
733
734 debug!("file_metadata: file_name: {}, directory: {}", file_name, directory);
735
736 let file_name = CString::new(file_name).unwrap();
737 let directory = CString::new(directory).unwrap();
738
739 let file_metadata = unsafe {
740 llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
741 file_name.as_ptr(),
742 directory.as_ptr())
743 };
744
745 let mut created_files = debug_context(cx).created_files.borrow_mut();
746 created_files.insert(key, file_metadata);
747 file_metadata
748 }
749
750 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
751 t: Ty<'tcx>) -> DIType {
752
753 debug!("basic_type_metadata: {:?}", t);
754
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)
763 },
764 ty::TyUint(uint_ty) => {
765 (uint_ty.ty_to_string(), DW_ATE_unsigned)
766 },
767 ty::TyFloat(float_ty) => {
768 (float_ty.ty_to_string(), DW_ATE_float)
769 },
770 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
771 };
772
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(
778 DIB(cx),
779 name.as_ptr(),
780 bytes_to_bits(size),
781 bytes_to_bits(align),
782 encoding)
783 };
784
785 return ty_metadata;
786 }
787
788 fn foreign_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
789 t: Ty<'tcx>,
790 unique_type_id: UniqueTypeId) -> DIType {
791 debug!("foreign_type_metadata: {:?}", t);
792
793 let llvm_type = type_of::type_of(cx, t);
794
795 let name = compute_debuginfo_type_name(cx, t, false);
796 create_struct_stub(cx, llvm_type, &name, unique_type_id, NO_SCOPE_METADATA)
797 }
798
799 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
800 pointer_type: Ty<'tcx>,
801 pointee_type_metadata: DIType)
802 -> 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(
809 DIB(cx),
810 pointee_type_metadata,
811 bytes_to_bits(pointer_size),
812 bytes_to_bits(pointer_align),
813 name.as_ptr())
814 };
815 return ptr_metadata;
816 }
817
818 pub fn compile_unit_metadata(scc: &SharedCrateContext,
819 codegen_unit_name: &str,
820 debug_context: &CrateDebugContext,
821 sess: &Session)
822 -> DIDescriptor {
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(),
826 };
827
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);
835 }
836
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"));
841
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();
845 let flags = "\0";
846 let split_name = "\0";
847
848 unsafe {
849 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
850 debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
851
852 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
853 debug_context.builder,
854 DW_LANG_RUST,
855 file_metadata,
856 producer.as_ptr(),
857 sess.opts.optimize != config::OptLevel::No,
858 flags.as_ptr() as *const _,
859 0,
860 split_name.as_ptr() as *const _);
861
862 if sess.opts.debugging_opts.profile {
863 let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
864 unit_metadata);
865
866 let gcov_cu_info = [
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")),
871 cu_desc_metadata,
872 ];
873 let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
874 gcov_cu_info.as_ptr(),
875 gcov_cu_info.len() as c_uint);
876
877 let llvm_gcov_ident = CString::new("llvm.gcov").unwrap();
878 llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
879 llvm_gcov_ident.as_ptr(),
880 gcov_metadata);
881 }
882
883 return unit_metadata;
884 };
885
886 fn path_to_mdstring(llcx: llvm::ContextRef, path: &Path) -> llvm::ValueRef {
887 let path_str = path2cstr(path);
888 unsafe {
889 llvm::LLVMMDStringInContext(llcx,
890 path_str.as_ptr(),
891 path_str.as_bytes().len() as c_uint)
892 }
893 }
894 }
895
896 struct MetadataCreationResult {
897 metadata: DIType,
898 already_stored_in_typemap: bool
899 }
900
901 impl MetadataCreationResult {
902 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
903 MetadataCreationResult {
904 metadata,
905 already_stored_in_typemap,
906 }
907 }
908 }
909
910 #[derive(Debug)]
911 enum MemberOffset {
912 FixedMemberOffset { bytes: usize },
913 // For ComputedMemberOffset, the offset is read from the llvm type definition.
914 ComputedMemberOffset
915 }
916
917 // Description of a type member, which can either be a regular field (as in
918 // structs or tuples) or an enum variant.
919 #[derive(Debug)]
920 struct MemberDescription {
921 name: String,
922 llvm_type: Type,
923 type_metadata: DIType,
924 offset: MemberOffset,
925 flags: DIFlags,
926 }
927
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>)
938 }
939
940 impl<'tcx> MemberDescriptionFactory<'tcx> {
941 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
942 -> Vec<MemberDescription> {
943 match *self {
944 StructMDF(ref this) => {
945 this.create_member_descriptions(cx)
946 }
947 TupleMDF(ref this) => {
948 this.create_member_descriptions(cx)
949 }
950 EnumMDF(ref this) => {
951 this.create_member_descriptions(cx)
952 }
953 UnionMDF(ref this) => {
954 this.create_member_descriptions(cx)
955 }
956 VariantMDF(ref this) => {
957 this.create_member_descriptions(cx)
958 }
959 }
960 }
961 }
962
963 //=-----------------------------------------------------------------------------
964 // Structs
965 //=-----------------------------------------------------------------------------
966
967 // Creates MemberDescriptions for the fields of a struct
968 struct StructMemberDescriptionFactory<'tcx> {
969 ty: Ty<'tcx>,
970 variant: &'tcx ty::VariantDef,
971 substs: &'tcx Substs<'tcx>,
972 span: Span,
973 }
974
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);
979
980 let tmp;
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();
985 tmp = (0..count).
986 map(|i| layout::Size::from_bytes(i*element_size))
987 .collect::<Vec<layout::Size>>();
988 &tmp
989 }
990 _ => bug!("{} is not a struct", self.ty)
991 };
992
993 self.variant.fields.iter().enumerate().map(|(i, f)| {
994 let name = if self.variant.ctor_kind == CtorKind::Fn {
995 format!("__{}", i)
996 } else {
997 f.name.to_string()
998 };
999 let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
1000
1001 let offset = FixedMemberOffset { bytes: offsets[i].bytes() as usize};
1002
1003 MemberDescription {
1004 name,
1005 llvm_type: type_of::in_memory_type_of(cx, fty),
1006 type_metadata: type_metadata(cx, fty, self.span),
1007 offset,
1008 flags: DIFlags::FlagZero,
1009 }
1010 }).collect()
1011 }
1012 }
1013
1014
1015 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1016 struct_type: Ty<'tcx>,
1017 unique_type_id: UniqueTypeId,
1018 span: Span)
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);
1022
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")
1026 };
1027
1028 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1029
1030 let struct_metadata_stub = create_struct_stub(cx,
1031 struct_llvm_type,
1032 &struct_name,
1033 unique_type_id,
1034 containing_scope);
1035
1036 create_and_register_recursive_type_forward_declaration(
1037 cx,
1038 struct_type,
1039 unique_type_id,
1040 struct_metadata_stub,
1041 struct_llvm_type,
1042 StructMDF(StructMemberDescriptionFactory {
1043 ty: struct_type,
1044 variant,
1045 substs,
1046 span,
1047 })
1048 )
1049 }
1050
1051 //=-----------------------------------------------------------------------------
1052 // Tuples
1053 //=-----------------------------------------------------------------------------
1054
1055 // Creates MemberDescriptions for the fields of a tuple
1056 struct TupleMemberDescriptionFactory<'tcx> {
1057 ty: Ty<'tcx>,
1058 component_types: Vec<Ty<'tcx>>,
1059 span: Span,
1060 }
1061
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 {
1067 &variant.offsets
1068 } else {
1069 bug!("{} is not a tuple", self.ty);
1070 };
1071
1072 self.component_types
1073 .iter()
1074 .enumerate()
1075 .map(|(i, &component_type)| {
1076 MemberDescription {
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,
1082 }
1083 }).collect()
1084 }
1085 }
1086
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,
1091 span: Span)
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);
1095
1096 create_and_register_recursive_type_forward_declaration(
1097 cx,
1098 tuple_type,
1099 unique_type_id,
1100 create_struct_stub(cx,
1101 tuple_llvm_type,
1102 &tuple_name[..],
1103 unique_type_id,
1104 NO_SCOPE_METADATA),
1105 tuple_llvm_type,
1106 TupleMDF(TupleMemberDescriptionFactory {
1107 ty: tuple_type,
1108 component_types: component_types.to_vec(),
1109 span,
1110 })
1111 )
1112 }
1113
1114 //=-----------------------------------------------------------------------------
1115 // Unions
1116 //=-----------------------------------------------------------------------------
1117
1118 struct UnionMemberDescriptionFactory<'tcx> {
1119 variant: &'tcx ty::VariantDef,
1120 substs: &'tcx Substs<'tcx>,
1121 span: Span,
1122 }
1123
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);
1129 MemberDescription {
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,
1135 }
1136 }).collect()
1137 }
1138 }
1139
1140 fn prepare_union_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1141 union_type: Ty<'tcx>,
1142 unique_type_id: UniqueTypeId,
1143 span: Span)
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);
1147
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")
1151 };
1152
1153 let containing_scope = get_namespace_for_item(cx, union_def_id);
1154
1155 let union_metadata_stub = create_union_stub(cx,
1156 union_llvm_type,
1157 &union_name,
1158 unique_type_id,
1159 containing_scope);
1160
1161 create_and_register_recursive_type_forward_declaration(
1162 cx,
1163 union_type,
1164 unique_type_id,
1165 union_metadata_stub,
1166 union_llvm_type,
1167 UnionMDF(UnionMemberDescriptionFactory {
1168 variant,
1169 substs,
1170 span,
1171 })
1172 )
1173 }
1174
1175 //=-----------------------------------------------------------------------------
1176 // Enums
1177 //=-----------------------------------------------------------------------------
1178
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,
1190 span: Span,
1191 }
1192
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)
1200 };
1201 match *self.type_rep {
1202 layout::General { ref variants, .. } => {
1203 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1204 .expect(""));
1205 variants
1206 .iter()
1207 .enumerate()
1208 .map(|(i, struct_def)| {
1209 let (variant_type_metadata,
1210 variant_llvm_type,
1211 member_desc_factory) =
1212 describe_enum_variant(cx,
1213 self.enum_type,
1214 struct_def,
1215 &adt.variants[i],
1216 discriminant_info,
1217 self.containing_scope,
1218 self.span);
1219
1220 let member_descriptions = member_desc_factory
1221 .create_member_descriptions(cx);
1222
1223 set_members_of_composite_type(cx,
1224 variant_type_metadata,
1225 variant_llvm_type,
1226 &member_descriptions);
1227 MemberDescription {
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
1233 }
1234 }).collect()
1235 },
1236 layout::Univariant{ ref variant, .. } => {
1237 assert!(adt.variants.len() <= 1);
1238
1239 if adt.variants.is_empty() {
1240 vec![]
1241 } else {
1242 let (variant_type_metadata,
1243 variant_llvm_type,
1244 member_description_factory) =
1245 describe_enum_variant(cx,
1246 self.enum_type,
1247 variant,
1248 &adt.variants[0],
1249 NoDiscriminant,
1250 self.containing_scope,
1251 self.span);
1252
1253 let member_descriptions =
1254 member_description_factory.create_member_descriptions(cx);
1255
1256 set_members_of_composite_type(cx,
1257 variant_type_metadata,
1258 variant_llvm_type,
1259 &member_descriptions[..]);
1260 vec![
1261 MemberDescription {
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
1267 }
1268 ]
1269 }
1270 }
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.
1275
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();
1279
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);
1284
1285 // The type of the artificial struct wrapping the pointer
1286 let artificial_struct_llvm_type = Type::struct_(cx,
1287 &[non_null_llvm_type],
1288 false);
1289
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()
1297 }
1298 CtorKind::Const => bug!()
1299 },
1300 llvm_type: non_null_llvm_type,
1301 type_metadata: non_null_type_metadata,
1302 offset: FixedMemberOffset { bytes: 0 },
1303 flags: DIFlags::FlagZero
1304 };
1305
1306 let unique_type_id = debug_context(cx).type_map
1307 .borrow_mut()
1308 .get_unique_type_id_of_enum_variant(
1309 cx,
1310 self.enum_type,
1311 &non_null_variant_name);
1312
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,
1318 unique_type_id,
1319 &[sole_struct_member_description],
1320 self.containing_scope,
1321 self.file_metadata,
1322 syntax_pos::DUMMY_SP);
1323
1324 // Encode the information about the null variant in the union
1325 // member's name.
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${}${}",
1329 0,
1330 null_variant_name);
1331
1332 // Finally create the (singleton) list of descriptions of union
1333 // members.
1334 vec![
1335 MemberDescription {
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
1341 }
1342 ]
1343 },
1344 layout::StructWrappedNullablePointer { nonnull: ref struct_def,
1345 nndiscr,
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,
1350 self.enum_type,
1351 struct_def,
1352 &adt.variants[nndiscr as usize],
1353 OptimizedDiscriminant,
1354 self.containing_scope,
1355 self.span);
1356
1357 let variant_member_descriptions =
1358 member_description_factory.create_member_descriptions(cx);
1359
1360 set_members_of_composite_type(cx,
1361 variant_type_metadata,
1362 variant_llvm_type,
1363 &variant_member_descriptions[..]);
1364
1365 // Encode the information about the null variant in the union
1366 // member's name.
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()
1370 .skip(1)
1371 .map(|x| x.to_string())
1372 .collect::<Vec<_>>().join("$");
1373 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1374 discrfield_source,
1375 null_variant_name);
1376
1377 // Create the (singleton) list of descriptions of union members.
1378 vec![
1379 MemberDescription {
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
1385 }
1386 ]
1387 },
1388 layout::CEnum { .. } => span_bug!(self.span, "This should be unreachable."),
1389 ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1390 }
1391 }
1392 }
1393
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>,
1400 span: Span,
1401 }
1402
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))| {
1407 MemberDescription {
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)
1413 },
1414 offset: FixedMemberOffset { bytes: self.offsets[i].bytes() as usize },
1415 flags: DIFlags::FlagZero
1416 }
1417 }).collect()
1418 }
1419 }
1420
1421 #[derive(Copy, Clone)]
1422 enum EnumDiscriminantInfo {
1423 RegularDiscriminant(DIType),
1424 OptimizedDiscriminant,
1425 NoDiscriminant
1426 }
1427
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,
1438 span: Span)
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)
1443 };
1444
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)
1452 };
1453
1454 let mut field_tys = variant.fields.iter().map(|f| {
1455 monomorphize::field_ty(cx.tcx(), &substs, f)
1456 }).collect::<Vec<_>>();
1457
1458 if let Some((discr, signed)) = maybe_discr_and_signed {
1459 field_tys.insert(0, discr.to_ty(&cx.tcx(), signed));
1460 }
1461
1462
1463 let variant_llvm_type =
1464 Type::struct_(cx, &field_tys
1465 .iter()
1466 .map(|t| type_of::type_of(cx, t))
1467 .collect::<Vec<_>>()
1468 ,
1469 struct_def.packed);
1470 // Could do some consistency checks here: size, align, field count, discr type
1471
1472 let variant_name = variant.name.as_str();
1473 let unique_type_id = debug_context(cx).type_map
1474 .borrow_mut()
1475 .get_unique_type_id_of_enum_variant(
1476 cx,
1477 enum_type,
1478 &variant_name);
1479
1480 let metadata_stub = create_struct_stub(cx,
1481 variant_llvm_type,
1482 &variant_name,
1483 unique_type_id,
1484 containing_scope);
1485
1486 // Get the argument names from the enum variant info
1487 let mut arg_names: Vec<_> = match variant.ctor_kind {
1488 CtorKind::Const => vec![],
1489 CtorKind::Fn => {
1490 variant.fields
1491 .iter()
1492 .enumerate()
1493 .map(|(i, _)| format!("__{}", i))
1494 .collect()
1495 }
1496 CtorKind::Fictive => {
1497 variant.fields
1498 .iter()
1499 .map(|f| f.name.to_string())
1500 .collect()
1501 }
1502 };
1503
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 */ }
1508 };
1509
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))
1514 .collect();
1515
1516 let member_description_factory =
1517 VariantMDF(VariantMemberDescriptionFactory {
1518 offsets: &struct_def.offsets[..],
1519 args,
1520 discriminant_type_metadata: match discriminant_info {
1521 RegularDiscriminant(discriminant_type_metadata) => {
1522 Some(discriminant_type_metadata)
1523 }
1524 _ => None
1525 },
1526 span,
1527 });
1528
1529 (metadata_stub, variant_llvm_type, member_description_factory)
1530 }
1531
1532 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1533 enum_type: Ty<'tcx>,
1534 enum_def_id: DefId,
1535 unique_type_id: UniqueTypeId,
1536 span: Span)
1537 -> RecursiveTypeDescription<'tcx> {
1538 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1539
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
1546 // <unknown>
1547 let file_metadata = unknown_file_metadata(cx);
1548
1549 let def = enum_type.ty_adt_def().unwrap();
1550 let enumerators_metadata: Vec<DIDescriptor> = def.discriminants(cx.tcx())
1551 .zip(&def.variants)
1552 .map(|(discr, v)| {
1553 let token = v.name.as_str();
1554 let name = CString::new(token.as_bytes()).unwrap();
1555 unsafe {
1556 llvm::LLVMRustDIBuilderCreateEnumerator(
1557 DIB(cx),
1558 name.as_ptr(),
1559 // FIXME: what if enumeration has i128 discriminant?
1560 discr.to_u128_unchecked() as u64)
1561 }
1562 })
1563 .collect();
1564
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
1568 .borrow()
1569 .get(&disr_type_key).cloned();
1570 match cached_discriminant_type_metadata {
1571 Some(discriminant_type_metadata) => discriminant_type_metadata,
1572 None => {
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 =
1577 type_metadata(cx,
1578 inttype.to_ty(&cx.tcx(), signed),
1579 syntax_pos::DUMMY_SP);
1580 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1581
1582 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1583 let discriminant_type_metadata = unsafe {
1584 llvm::LLVMRustDIBuilderCreateEnumerationType(
1585 DIB(cx),
1586 containing_scope,
1587 name.as_ptr(),
1588 file_metadata,
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)
1594 };
1595
1596 debug_context(cx).created_enum_disr_types
1597 .borrow_mut()
1598 .insert(disr_type_key, discriminant_type_metadata);
1599
1600 discriminant_type_metadata
1601 }
1602 }
1603 };
1604
1605 let type_rep = cx.layout_of(enum_type);
1606
1607 let discriminant_type_metadata = match *type_rep {
1608 layout::CEnum { discr, signed, .. } => {
1609 return FinalMetadata(discriminant_type_metadata(discr, signed))
1610 },
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)
1616 };
1617
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);
1620
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()
1624 ).unwrap();
1625 let enum_metadata = unsafe {
1626 llvm::LLVMRustDIBuilderCreateUnionType(
1627 DIB(cx),
1628 containing_scope,
1629 enum_name.as_ptr(),
1630 file_metadata,
1631 UNKNOWN_LINE_NUMBER,
1632 bytes_to_bits(enum_type_size),
1633 bytes_to_bits(enum_type_align),
1634 DIFlags::FlagZero,
1635 ptr::null_mut(),
1636 0, // RuntimeLang
1637 unique_type_id_str.as_ptr())
1638 };
1639
1640 return create_and_register_recursive_type_forward_declaration(
1641 cx,
1642 enum_type,
1643 unique_type_id,
1644 enum_metadata,
1645 enum_llvm_type,
1646 EnumMDF(EnumMemberDescriptionFactory {
1647 enum_type,
1648 type_rep: type_rep.layout,
1649 discriminant_type_metadata,
1650 containing_scope,
1651 file_metadata,
1652 span,
1653 }),
1654 );
1655
1656 fn get_enum_discriminant_name(cx: &CrateContext,
1657 def_id: DefId)
1658 -> InternedString {
1659 cx.tcx().item_name(def_id)
1660 }
1661 }
1662
1663 /// Creates debug information for a composite type, that is, anything that
1664 /// results in a LLVM struct.
1665 ///
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,
1673
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,
1684 containing_scope);
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);
1690
1691 return composite_type_metadata;
1692 }
1693
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
1703 // regression.
1704 {
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.");
1710 } else {
1711 composite_types_completed.insert(composite_type_metadata);
1712 }
1713 }
1714
1715 let member_metadata: Vec<DIDescriptor> = member_descriptions
1716 .iter()
1717 .enumerate()
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)
1723 };
1724
1725 let member_name = member_description.name.as_bytes();
1726 let member_name = CString::new(member_name).unwrap();
1727 unsafe {
1728 llvm::LLVMRustDIBuilderCreateMemberType(
1729 DIB(cx),
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)
1739 }
1740 })
1741 .collect();
1742
1743 unsafe {
1744 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1745 llvm::LLVMRustDICompositeTypeSetTypeArray(
1746 DIB(cx), composite_type_metadata, type_array);
1747 }
1748 }
1749
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);
1760
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()
1764 ).unwrap();
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), &[]);
1770
1771 llvm::LLVMRustDIBuilderCreateStructType(
1772 DIB(cx),
1773 containing_scope,
1774 name.as_ptr(),
1775 unknown_file_metadata(cx),
1776 UNKNOWN_LINE_NUMBER,
1777 bytes_to_bits(struct_size),
1778 bytes_to_bits(struct_align),
1779 DIFlags::FlagZero,
1780 ptr::null_mut(),
1781 empty_array,
1782 0,
1783 ptr::null_mut(),
1784 unique_type_id.as_ptr())
1785 };
1786
1787 return metadata_stub;
1788 }
1789
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);
1797
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()
1801 ).unwrap();
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), &[]);
1807
1808 llvm::LLVMRustDIBuilderCreateUnionType(
1809 DIB(cx),
1810 containing_scope,
1811 name.as_ptr(),
1812 unknown_file_metadata(cx),
1813 UNKNOWN_LINE_NUMBER,
1814 bytes_to_bits(union_size),
1815 bytes_to_bits(union_align),
1816 DIFlags::FlagZero,
1817 empty_array,
1818 0, // RuntimeLang
1819 unique_type_id.as_ptr())
1820 };
1821
1822 return metadata_stub;
1823 }
1824
1825 /// Creates debug information for the given global variable.
1826 ///
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,
1830 global: ValueRef) {
1831 if cx.dbg_cx().is_none() {
1832 return;
1833 }
1834
1835 let tcx = cx.tcx();
1836
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);
1840
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)
1844 } else {
1845 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1846 };
1847
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, "");
1853
1854 let var_name = CString::new(var_name).unwrap();
1855 let linkage_name = CString::new(linkage_name).unwrap();
1856
1857 let global_align = cx.align_of(variable_type);
1858
1859 unsafe {
1860 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1861 var_scope,
1862 var_name.as_ptr(),
1863 linkage_name.as_ptr(),
1864 file_metadata,
1865 line_number,
1866 type_metadata,
1867 is_local_to_unit,
1868 global,
1869 ptr::null_mut(),
1870 global_align,
1871 );
1872 }
1873 }
1874
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)
1880 -> DILexicalBlock {
1881 let file_metadata = file_metadata(ccx, &file.name, defining_crate);
1882 unsafe {
1883 llvm::LLVMRustDIBuilderCreateLexicalBlockFile(
1884 DIB(ccx),
1885 scope_metadata,
1886 file_metadata)
1887 }
1888 }
1889
1890 /// Creates debug information for the given vtable, which is for the
1891 /// given type.
1892 ///
1893 /// Adds the created metadata nodes directly to the crate's IR.
1894 pub fn create_vtable_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1895 ty: ty::Ty<'tcx>,
1896 vtable: ValueRef) {
1897 if cx.dbg_cx().is_none() {
1898 return;
1899 }
1900
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);
1904
1905 unsafe {
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), &[]);
1910
1911 let name = CString::new("vtable").unwrap();
1912
1913 // Create a new one each time. We don't want metadata caching
1914 // here, because each vtable will refer to a unique containing
1915 // type.
1916 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
1917 DIB(cx),
1918 NO_SCOPE_METADATA,
1919 name.as_ptr(),
1920 unknown_file_metadata(cx),
1921 UNKNOWN_LINE_NUMBER,
1922 bytes_to_bits(struct_size),
1923 bytes_to_bits(struct_align),
1924 DIFlags::FlagArtificial,
1925 ptr::null_mut(),
1926 empty_array,
1927 0,
1928 type_metadata,
1929 name.as_ptr()
1930 );
1931
1932 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1933 NO_SCOPE_METADATA,
1934 name.as_ptr(),
1935 // LLVM 3.9
1936 // doesn't accept
1937 // null here, so
1938 // pass the name
1939 // as the linkage
1940 // name.
1941 name.as_ptr(),
1942 unknown_file_metadata(cx),
1943 UNKNOWN_LINE_NUMBER,
1944 vtable_type,
1945 true,
1946 vtable,
1947 ptr::null_mut(),
1948 0);
1949 }
1950 }