]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/debuginfo/metadata.rs
ccb693aa41f4c4a5e8ac78ad33b5d6a1d86e4046
[rust.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_and_span_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 context::SharedCrateContext;
22 use session::Session;
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;
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_data_structures::ToHex;
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 session::config;
41 use util::nodemap::FxHashMap;
42 use util::common::path2cstr;
43
44 use libc::{c_uint, c_longlong};
45 use std::ffi::CString;
46 use std::path::Path;
47 use std::ptr;
48 use syntax::ast;
49 use syntax::symbol::{Interner, InternedString};
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
151         let mut type_id_hasher = TypeIdHasher::<[u8; 20]>::new(cx.tcx());
152         type_id_hasher.visit_ty(type_);
153
154         let unique_type_id = type_id_hasher.finish().to_hex();
155         let key = self.unique_id_interner.intern(&unique_type_id);
156         self.type_to_unique_id.insert(type_, UniqueTypeId(key));
157
158         return UniqueTypeId(key);
159     }
160
161     // Get the UniqueTypeId for an enum variant. Enum variants are not really
162     // types of their own, so they need special handling. We still need a
163     // UniqueTypeId for them, since to debuginfo they *are* real types.
164     fn get_unique_type_id_of_enum_variant<'a>(&mut self,
165                                               cx: &CrateContext<'a, 'tcx>,
166                                               enum_type: Ty<'tcx>,
167                                               variant_name: &str)
168                                               -> UniqueTypeId {
169         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
170         let enum_variant_type_id = format!("{}::{}",
171                                            self.get_unique_type_id_as_string(enum_type_id),
172                                            variant_name);
173         let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
174         UniqueTypeId(interner_key)
175     }
176 }
177
178 // A description of some recursive type. It can either be already finished (as
179 // with FinalMetadata) or it is not yet finished, but contains all information
180 // needed to generate the missing parts of the description. See the
181 // documentation section on Recursive Types at the top of this file for more
182 // information.
183 enum RecursiveTypeDescription<'tcx> {
184     UnfinishedMetadata {
185         unfinished_type: Ty<'tcx>,
186         unique_type_id: UniqueTypeId,
187         metadata_stub: DICompositeType,
188         llvm_type: Type,
189         member_description_factory: MemberDescriptionFactory<'tcx>,
190     },
191     FinalMetadata(DICompositeType)
192 }
193
194 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
195     cx: &CrateContext<'a, 'tcx>,
196     unfinished_type: Ty<'tcx>,
197     unique_type_id: UniqueTypeId,
198     metadata_stub: DICompositeType,
199     llvm_type: Type,
200     member_description_factory: MemberDescriptionFactory<'tcx>)
201  -> RecursiveTypeDescription<'tcx> {
202
203     // Insert the stub into the TypeMap in order to allow for recursive references
204     let mut type_map = debug_context(cx).type_map.borrow_mut();
205     type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
206     type_map.register_type_with_metadata(unfinished_type, metadata_stub);
207
208     UnfinishedMetadata {
209         unfinished_type: unfinished_type,
210         unique_type_id: unique_type_id,
211         metadata_stub: metadata_stub,
212         llvm_type: llvm_type,
213         member_description_factory: member_description_factory,
214     }
215 }
216
217 impl<'tcx> RecursiveTypeDescription<'tcx> {
218     // Finishes up the description of the type in question (mostly by providing
219     // descriptions of the fields of the given type) and returns the final type
220     // metadata.
221     fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
222         match *self {
223             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
224             UnfinishedMetadata {
225                 unfinished_type,
226                 unique_type_id,
227                 metadata_stub,
228                 llvm_type,
229                 ref member_description_factory,
230                 ..
231             } => {
232                 // Make sure that we have a forward declaration of the type in
233                 // the TypeMap so that recursive references are possible. This
234                 // will always be the case if the RecursiveTypeDescription has
235                 // been properly created through the
236                 // create_and_register_recursive_type_forward_declaration()
237                 // function.
238                 {
239                     let type_map = debug_context(cx).type_map.borrow();
240                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
241                        type_map.find_metadata_for_type(unfinished_type).is_none() {
242                         bug!("Forward declaration of potentially recursive type \
243                               '{:?}' was not found in TypeMap!",
244                              unfinished_type);
245                     }
246                 }
247
248                 // ... then create the member descriptions ...
249                 let member_descriptions =
250                     member_description_factory.create_member_descriptions(cx);
251
252                 // ... and attach them to the stub to complete it.
253                 set_members_of_composite_type(cx,
254                                               metadata_stub,
255                                               llvm_type,
256                                               &member_descriptions[..]);
257                 return MetadataCreationResult::new(metadata_stub, true);
258             }
259         }
260     }
261 }
262
263 // Returns from the enclosing function if the type metadata with the given
264 // unique id can be found in the type map
265 macro_rules! return_if_metadata_created_in_meantime {
266     ($cx: expr, $unique_type_id: expr) => (
267         match debug_context($cx).type_map
268                                 .borrow()
269                                 .find_metadata_for_unique_id($unique_type_id) {
270             Some(metadata) => return MetadataCreationResult::new(metadata, true),
271             None => { /* proceed normally */ }
272         }
273     )
274 }
275
276 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
277                                 unique_type_id: UniqueTypeId,
278                                 element_type: Ty<'tcx>,
279                                 len: Option<u64>,
280                                 span: Span)
281                                 -> MetadataCreationResult {
282     let element_type_metadata = type_metadata(cx, element_type, span);
283
284     return_if_metadata_created_in_meantime!(cx, unique_type_id);
285
286     let element_llvm_type = type_of::type_of(cx, element_type);
287     let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
288
289     let (array_size_in_bytes, upper_bound) = match len {
290         Some(len) => (element_type_size * len, len as c_longlong),
291         None => (0, -1)
292     };
293
294     let subrange = unsafe {
295         llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
296     };
297
298     let subscripts = create_DIArray(DIB(cx), &[subrange]);
299     let metadata = unsafe {
300         llvm::LLVMRustDIBuilderCreateArrayType(
301             DIB(cx),
302             bytes_to_bits(array_size_in_bytes),
303             bytes_to_bits(element_type_align),
304             element_type_metadata,
305             subscripts)
306     };
307
308     return MetadataCreationResult::new(metadata, false);
309 }
310
311 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
312                                 vec_type: Ty<'tcx>,
313                                 element_type: Ty<'tcx>,
314                                 unique_type_id: UniqueTypeId,
315                                 span: Span)
316                                 -> MetadataCreationResult {
317     let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
318         ty: element_type,
319         mutbl: hir::MutImmutable
320     });
321
322     let element_type_metadata = type_metadata(cx, data_ptr_type, span);
323
324     return_if_metadata_created_in_meantime!(cx, unique_type_id);
325
326     let slice_llvm_type = type_of::type_of(cx, vec_type);
327     let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
328
329     let member_llvm_types = slice_llvm_type.field_types();
330     assert!(slice_layout_is_correct(cx,
331                                     &member_llvm_types[..],
332                                     element_type));
333     let member_descriptions = [
334         MemberDescription {
335             name: "data_ptr".to_string(),
336             llvm_type: member_llvm_types[0],
337             type_metadata: element_type_metadata,
338             offset: ComputedMemberOffset,
339             flags: DIFlags::FlagZero,
340         },
341         MemberDescription {
342             name: "length".to_string(),
343             llvm_type: member_llvm_types[1],
344             type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
345             offset: ComputedMemberOffset,
346             flags: DIFlags::FlagZero,
347         },
348     ];
349
350     assert!(member_descriptions.len() == member_llvm_types.len());
351
352     let loc = span_start(cx, span);
353     let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
354
355     let metadata = composite_type_metadata(cx,
356                                            slice_llvm_type,
357                                            &slice_type_name[..],
358                                            unique_type_id,
359                                            &member_descriptions,
360                                            NO_SCOPE_METADATA,
361                                            file_metadata,
362                                            span);
363     return MetadataCreationResult::new(metadata, false);
364
365     fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
366                                          member_llvm_types: &[Type],
367                                          element_type: Ty<'tcx>)
368                                          -> bool {
369         member_llvm_types.len() == 2 &&
370         member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
371         member_llvm_types[1] == cx.int_type()
372     }
373 }
374
375 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
376                                       unique_type_id: UniqueTypeId,
377                                       signature: ty::PolyFnSig<'tcx>,
378                                       span: Span)
379                                       -> MetadataCreationResult
380 {
381     let signature = cx.tcx().erase_late_bound_regions_and_normalize(&signature);
382
383     let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs().len() + 1);
384
385     // return type
386     signature_metadata.push(match signature.output().sty {
387         ty::TyTuple(ref tys, _) if tys.is_empty() => ptr::null_mut(),
388         _ => type_metadata(cx, signature.output(), span)
389     });
390
391     // regular arguments
392     for &argument_type in signature.inputs() {
393         signature_metadata.push(type_metadata(cx, argument_type, span));
394     }
395
396     return_if_metadata_created_in_meantime!(cx, unique_type_id);
397
398     return MetadataCreationResult::new(
399         unsafe {
400             llvm::LLVMRustDIBuilderCreateSubroutineType(
401                 DIB(cx),
402                 unknown_file_metadata(cx),
403                 create_DIArray(DIB(cx), &signature_metadata[..]))
404         },
405         false);
406 }
407
408 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
409 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
410 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
411 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
412 // of a DST struct, there is no trait_object_type and the results of this
413 // function will be a little bit weird.
414 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
415                                     trait_type: Ty<'tcx>,
416                                     trait_object_type: Option<Ty<'tcx>>,
417                                     unique_type_id: UniqueTypeId)
418                                     -> DIType {
419     // The implementation provided here is a stub. It makes sure that the trait
420     // type is assigned the correct name, size, namespace, and source location.
421     // But it does not describe the trait's methods.
422
423     let containing_scope = match trait_type.sty {
424         ty::TyDynamic(ref data, ..) => if let Some(principal) = data.principal() {
425             let def_id = principal.def_id();
426             get_namespace_and_span_for_item(cx, def_id).0
427         } else {
428             NO_SCOPE_METADATA
429         },
430         _ => {
431             bug!("debuginfo: Unexpected trait-object type in \
432                   trait_pointer_metadata(): {:?}",
433                  trait_type);
434         }
435     };
436
437     let trait_object_type = trait_object_type.unwrap_or(trait_type);
438     let trait_type_name =
439         compute_debuginfo_type_name(cx, trait_object_type, false);
440
441     let trait_llvm_type = type_of::type_of(cx, trait_object_type);
442     let file_metadata = unknown_file_metadata(cx);
443
444     composite_type_metadata(cx,
445                             trait_llvm_type,
446                             &trait_type_name[..],
447                             unique_type_id,
448                             &[],
449                             containing_scope,
450                             file_metadata,
451                             syntax_pos::DUMMY_SP)
452 }
453
454 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
455                                t: Ty<'tcx>,
456                                usage_site_span: Span)
457                                -> DIType {
458     // Get the unique type id of this type.
459     let unique_type_id = {
460         let mut type_map = debug_context(cx).type_map.borrow_mut();
461         // First, try to find the type in TypeMap. If we have seen it before, we
462         // can exit early here.
463         match type_map.find_metadata_for_type(t) {
464             Some(metadata) => {
465                 return metadata;
466             },
467             None => {
468                 // The Ty is not in the TypeMap but maybe we have already seen
469                 // an equivalent type (e.g. only differing in region arguments).
470                 // In order to find out, generate the unique type id and look
471                 // that up.
472                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
473                 match type_map.find_metadata_for_unique_id(unique_type_id) {
474                     Some(metadata) => {
475                         // There is already an equivalent type in the TypeMap.
476                         // Register this Ty as an alias in the cache and
477                         // return the cached metadata.
478                         type_map.register_type_with_metadata(t, metadata);
479                         return metadata;
480                     },
481                     None => {
482                         // There really is no type metadata for this type, so
483                         // proceed by creating it.
484                         unique_type_id
485                     }
486                 }
487             }
488         }
489     };
490
491     debug!("type_metadata: {:?}", t);
492
493     let sty = &t.sty;
494     let ptr_metadata = |ty: Ty<'tcx>| {
495         match ty.sty {
496             ty::TySlice(typ) => {
497                 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
498             }
499             ty::TyStr => {
500                 Ok(vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span))
501             }
502             ty::TyDynamic(..) => {
503                 Ok(MetadataCreationResult::new(
504                     trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
505                     false))
506             }
507             _ => {
508                 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
509
510                 match debug_context(cx).type_map
511                                         .borrow()
512                                         .find_metadata_for_unique_id(unique_type_id) {
513                     Some(metadata) => return Err(metadata),
514                     None => { /* proceed normally */ }
515                 };
516
517                 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
518                    false))
519             }
520         }
521     };
522
523     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
524         ty::TyNever    |
525         ty::TyBool     |
526         ty::TyChar     |
527         ty::TyInt(_)   |
528         ty::TyUint(_)  |
529         ty::TyFloat(_) => {
530             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
531         }
532         ty::TyTuple(ref elements, _) if elements.is_empty() => {
533             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
534         }
535         ty::TyArray(typ, len) => {
536             fixed_vec_metadata(cx, unique_type_id, typ, Some(len as u64), usage_site_span)
537         }
538         ty::TySlice(typ) => {
539             fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
540         }
541         ty::TyStr => {
542             fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
543         }
544         ty::TyDynamic(..) => {
545             MetadataCreationResult::new(
546                         trait_pointer_metadata(cx, t, None, unique_type_id),
547             false)
548         }
549         ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
550         ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
551             match ptr_metadata(ty) {
552                 Ok(res) => res,
553                 Err(metadata) => return metadata,
554             }
555         }
556         ty::TyAdt(def, _) if def.is_box() => {
557             match ptr_metadata(t.boxed_ty()) {
558                 Ok(res) => res,
559                 Err(metadata) => return metadata,
560             }
561         }
562         ty::TyFnDef(.., sig) | ty::TyFnPtr(sig) => {
563             let fn_metadata = subroutine_type_metadata(cx,
564                                                        unique_type_id,
565                                                        sig,
566                                                        usage_site_span).metadata;
567             match debug_context(cx).type_map
568                                    .borrow()
569                                    .find_metadata_for_unique_id(unique_type_id) {
570                 Some(metadata) => return metadata,
571                 None => { /* proceed normally */ }
572             };
573
574             // This is actually a function pointer, so wrap it in pointer DI
575             MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
576
577         }
578         ty::TyClosure(def_id, substs) => {
579             let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx()).collect();
580             prepare_tuple_metadata(cx,
581                                    t,
582                                    &upvar_tys,
583                                    unique_type_id,
584                                    usage_site_span).finalize(cx)
585         }
586         ty::TyAdt(def, ..) => match def.adt_kind() {
587             AdtKind::Struct => {
588                 prepare_struct_metadata(cx,
589                                         t,
590                                         unique_type_id,
591                                         usage_site_span).finalize(cx)
592             }
593             AdtKind::Union => {
594                 prepare_union_metadata(cx,
595                                     t,
596                                     unique_type_id,
597                                     usage_site_span).finalize(cx)
598             }
599             AdtKind::Enum => {
600                 prepare_enum_metadata(cx,
601                                     t,
602                                     def.did,
603                                     unique_type_id,
604                                     usage_site_span).finalize(cx)
605             }
606         },
607         ty::TyTuple(ref elements, _) => {
608             prepare_tuple_metadata(cx,
609                                    t,
610                                    &elements[..],
611                                    unique_type_id,
612                                    usage_site_span).finalize(cx)
613         }
614         _ => {
615             bug!("debuginfo: unexpected type in type_metadata: {:?}", sty)
616         }
617     };
618
619     {
620         let mut type_map = debug_context(cx).type_map.borrow_mut();
621
622         if already_stored_in_typemap {
623             // Also make sure that we already have a TypeMap entry for the unique type id.
624             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
625                 Some(metadata) => metadata,
626                 None => {
627                     span_bug!(usage_site_span,
628                               "Expected type metadata for unique \
629                                type id '{}' to already be in \
630                                the debuginfo::TypeMap but it \
631                                was not. (Ty = {})",
632                               type_map.get_unique_type_id_as_string(unique_type_id),
633                               t);
634                 }
635             };
636
637             match type_map.find_metadata_for_type(t) {
638                 Some(metadata) => {
639                     if metadata != metadata_for_uid {
640                         span_bug!(usage_site_span,
641                                   "Mismatch between Ty and \
642                                    UniqueTypeId maps in \
643                                    debuginfo::TypeMap. \
644                                    UniqueTypeId={}, Ty={}",
645                                   type_map.get_unique_type_id_as_string(unique_type_id),
646                                   t);
647                     }
648                 }
649                 None => {
650                     type_map.register_type_with_metadata(t, metadata);
651                 }
652             }
653         } else {
654             type_map.register_type_with_metadata(t, metadata);
655             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
656         }
657     }
658
659     metadata
660 }
661
662 pub fn file_metadata(cx: &CrateContext, path: &str, full_path: &Option<String>) -> DIFile {
663     // FIXME (#9639): This needs to handle non-utf8 paths
664     let work_dir = cx.sess().working_dir.to_str().unwrap();
665     let file_name =
666         full_path.as_ref().map(|p| p.as_str()).unwrap_or_else(|| {
667             if path.starts_with(work_dir) {
668                 &path[work_dir.len() + 1..path.len()]
669             } else {
670                 path
671             }
672         });
673
674     file_metadata_(cx, path, file_name, &work_dir)
675 }
676
677 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
678     // Regular filenames should not be empty, so we abuse an empty name as the
679     // key for the special unknown file metadata
680     file_metadata_(cx, "", "<unknown>", "")
681
682 }
683
684 fn file_metadata_(cx: &CrateContext, key: &str, file_name: &str, work_dir: &str) -> DIFile {
685     if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(key) {
686         return *file_metadata;
687     }
688
689     debug!("file_metadata: file_name: {}, work_dir: {}", file_name, work_dir);
690
691     let file_name = CString::new(file_name).unwrap();
692     let work_dir = CString::new(work_dir).unwrap();
693     let file_metadata = unsafe {
694         llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
695                                           work_dir.as_ptr())
696     };
697
698     let mut created_files = debug_context(cx).created_files.borrow_mut();
699     created_files.insert(key.to_string(), file_metadata);
700     file_metadata
701 }
702
703 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
704                                  t: Ty<'tcx>) -> DIType {
705
706     debug!("basic_type_metadata: {:?}", t);
707
708     let (name, encoding) = match t.sty {
709         ty::TyNever => ("!", DW_ATE_unsigned),
710         ty::TyTuple(ref elements, _) if elements.is_empty() =>
711             ("()", DW_ATE_unsigned),
712         ty::TyBool => ("bool", DW_ATE_boolean),
713         ty::TyChar => ("char", DW_ATE_unsigned_char),
714         ty::TyInt(int_ty) => {
715             (int_ty.ty_to_string(), DW_ATE_signed)
716         },
717         ty::TyUint(uint_ty) => {
718             (uint_ty.ty_to_string(), DW_ATE_unsigned)
719         },
720         ty::TyFloat(float_ty) => {
721             (float_ty.ty_to_string(), DW_ATE_float)
722         },
723         _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
724     };
725
726     let llvm_type = type_of::type_of(cx, t);
727     let (size, align) = size_and_align_of(cx, llvm_type);
728     let name = CString::new(name).unwrap();
729     let ty_metadata = unsafe {
730         llvm::LLVMRustDIBuilderCreateBasicType(
731             DIB(cx),
732             name.as_ptr(),
733             bytes_to_bits(size),
734             bytes_to_bits(align),
735             encoding)
736     };
737
738     return ty_metadata;
739 }
740
741 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
742                                    pointer_type: Ty<'tcx>,
743                                    pointee_type_metadata: DIType)
744                                    -> DIType {
745     let pointer_llvm_type = type_of::type_of(cx, pointer_type);
746     let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
747     let name = compute_debuginfo_type_name(cx, pointer_type, false);
748     let name = CString::new(name).unwrap();
749     let ptr_metadata = unsafe {
750         llvm::LLVMRustDIBuilderCreatePointerType(
751             DIB(cx),
752             pointee_type_metadata,
753             bytes_to_bits(pointer_size),
754             bytes_to_bits(pointer_align),
755             name.as_ptr())
756     };
757     return ptr_metadata;
758 }
759
760 pub fn compile_unit_metadata(scc: &SharedCrateContext,
761                              debug_context: &CrateDebugContext,
762                              sess: &Session)
763                              -> DIDescriptor {
764     let work_dir = &sess.working_dir;
765     let compile_unit_name = match sess.local_crate_source_file {
766         None => fallback_path(scc),
767         Some(ref abs_path) => {
768             if abs_path.is_relative() {
769                 sess.warn("debuginfo: Invalid path to crate's local root source file!");
770                 fallback_path(scc)
771             } else {
772                 match abs_path.strip_prefix(work_dir) {
773                     Ok(ref p) if p.is_relative() => {
774                         if p.starts_with(Path::new("./")) {
775                             path2cstr(p)
776                         } else {
777                             path2cstr(&Path::new(".").join(p))
778                         }
779                     }
780                     _ => fallback_path(scc)
781                 }
782             }
783         }
784     };
785
786     debug!("compile_unit_metadata: {:?}", compile_unit_name);
787     let producer = format!("rustc version {}",
788                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
789
790     let compile_unit_name = compile_unit_name.as_ptr();
791     let work_dir = path2cstr(&work_dir);
792     let producer = CString::new(producer).unwrap();
793     let flags = "\0";
794     let split_name = "\0";
795
796     unsafe {
797         let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
798             debug_context.builder, compile_unit_name, work_dir.as_ptr());
799
800         return llvm::LLVMRustDIBuilderCreateCompileUnit(
801             debug_context.builder,
802             DW_LANG_RUST,
803             file_metadata,
804             producer.as_ptr(),
805             sess.opts.optimize != config::OptLevel::No,
806             flags.as_ptr() as *const _,
807             0,
808             split_name.as_ptr() as *const _)
809     };
810
811     fn fallback_path(scc: &SharedCrateContext) -> CString {
812         CString::new(scc.link_meta().crate_name.to_string()).unwrap()
813     }
814 }
815
816 struct MetadataCreationResult {
817     metadata: DIType,
818     already_stored_in_typemap: bool
819 }
820
821 impl MetadataCreationResult {
822     fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
823         MetadataCreationResult {
824             metadata: metadata,
825             already_stored_in_typemap: already_stored_in_typemap
826         }
827     }
828 }
829
830 #[derive(Debug)]
831 enum MemberOffset {
832     FixedMemberOffset { bytes: usize },
833     // For ComputedMemberOffset, the offset is read from the llvm type definition.
834     ComputedMemberOffset
835 }
836
837 // Description of a type member, which can either be a regular field (as in
838 // structs or tuples) or an enum variant.
839 #[derive(Debug)]
840 struct MemberDescription {
841     name: String,
842     llvm_type: Type,
843     type_metadata: DIType,
844     offset: MemberOffset,
845     flags: DIFlags,
846 }
847
848 // A factory for MemberDescriptions. It produces a list of member descriptions
849 // for some record-like type. MemberDescriptionFactories are used to defer the
850 // creation of type member descriptions in order to break cycles arising from
851 // recursive type definitions.
852 enum MemberDescriptionFactory<'tcx> {
853     StructMDF(StructMemberDescriptionFactory<'tcx>),
854     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
855     EnumMDF(EnumMemberDescriptionFactory<'tcx>),
856     UnionMDF(UnionMemberDescriptionFactory<'tcx>),
857     VariantMDF(VariantMemberDescriptionFactory<'tcx>)
858 }
859
860 impl<'tcx> MemberDescriptionFactory<'tcx> {
861     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
862                                       -> Vec<MemberDescription> {
863         match *self {
864             StructMDF(ref this) => {
865                 this.create_member_descriptions(cx)
866             }
867             TupleMDF(ref this) => {
868                 this.create_member_descriptions(cx)
869             }
870             EnumMDF(ref this) => {
871                 this.create_member_descriptions(cx)
872             }
873             UnionMDF(ref this) => {
874                 this.create_member_descriptions(cx)
875             }
876             VariantMDF(ref this) => {
877                 this.create_member_descriptions(cx)
878             }
879         }
880     }
881 }
882
883 //=-----------------------------------------------------------------------------
884 // Structs
885 //=-----------------------------------------------------------------------------
886
887 // Creates MemberDescriptions for the fields of a struct
888 struct StructMemberDescriptionFactory<'tcx> {
889     ty: Ty<'tcx>,
890     variant: &'tcx ty::VariantDef,
891     substs: &'tcx Substs<'tcx>,
892     span: Span,
893 }
894
895 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
896     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
897                                       -> Vec<MemberDescription> {
898         let layout = cx.layout_of(self.ty);
899
900         let tmp;
901         let offsets = match *layout {
902             layout::Univariant { ref variant, .. } => &variant.offsets,
903             layout::Vector { element, count } => {
904                 let element_size = element.size(cx).bytes();
905                 tmp = (0..count).
906                   map(|i| layout::Size::from_bytes(i*element_size))
907                   .collect::<Vec<layout::Size>>();
908                 &tmp
909             }
910             _ => bug!("{} is not a struct", self.ty)
911         };
912
913         self.variant.fields.iter().enumerate().map(|(i, f)| {
914             let name = if self.variant.ctor_kind == CtorKind::Fn {
915                 format!("__{}", i)
916             } else {
917                 f.name.to_string()
918             };
919             let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
920
921             let offset = FixedMemberOffset { bytes: offsets[i].bytes() as usize};
922
923             MemberDescription {
924                 name: name,
925                 llvm_type: type_of::in_memory_type_of(cx, fty),
926                 type_metadata: type_metadata(cx, fty, self.span),
927                 offset: offset,
928                 flags: DIFlags::FlagZero,
929             }
930         }).collect()
931     }
932 }
933
934
935 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
936                                      struct_type: Ty<'tcx>,
937                                      unique_type_id: UniqueTypeId,
938                                      span: Span)
939                                      -> RecursiveTypeDescription<'tcx> {
940     let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
941     let struct_llvm_type = type_of::in_memory_type_of(cx, struct_type);
942
943     let (struct_def_id, variant, substs) = match struct_type.sty {
944         ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
945         _ => bug!("prepare_struct_metadata on a non-ADT")
946     };
947
948     let (containing_scope, _) = get_namespace_and_span_for_item(cx, struct_def_id);
949
950     let struct_metadata_stub = create_struct_stub(cx,
951                                                   struct_llvm_type,
952                                                   &struct_name,
953                                                   unique_type_id,
954                                                   containing_scope);
955
956     create_and_register_recursive_type_forward_declaration(
957         cx,
958         struct_type,
959         unique_type_id,
960         struct_metadata_stub,
961         struct_llvm_type,
962         StructMDF(StructMemberDescriptionFactory {
963             ty: struct_type,
964             variant: variant,
965             substs: substs,
966             span: span,
967         })
968     )
969 }
970
971 //=-----------------------------------------------------------------------------
972 // Tuples
973 //=-----------------------------------------------------------------------------
974
975 // Creates MemberDescriptions for the fields of a tuple
976 struct TupleMemberDescriptionFactory<'tcx> {
977     ty: Ty<'tcx>,
978     component_types: Vec<Ty<'tcx>>,
979     span: Span,
980 }
981
982 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
983     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
984                                       -> Vec<MemberDescription> {
985         let layout = cx.layout_of(self.ty);
986         let offsets = if let layout::Univariant { ref variant, .. } = *layout {
987             &variant.offsets
988         } else {
989             bug!("{} is not a tuple", self.ty);
990         };
991
992         self.component_types
993             .iter()
994             .enumerate()
995             .map(|(i, &component_type)| {
996             MemberDescription {
997                 name: format!("__{}", i),
998                 llvm_type: type_of::type_of(cx, component_type),
999                 type_metadata: type_metadata(cx, component_type, self.span),
1000                 offset: FixedMemberOffset { bytes: offsets[i].bytes() as usize },
1001                 flags: DIFlags::FlagZero,
1002             }
1003         }).collect()
1004     }
1005 }
1006
1007 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1008                                     tuple_type: Ty<'tcx>,
1009                                     component_types: &[Ty<'tcx>],
1010                                     unique_type_id: UniqueTypeId,
1011                                     span: Span)
1012                                     -> RecursiveTypeDescription<'tcx> {
1013     let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1014     let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1015
1016     create_and_register_recursive_type_forward_declaration(
1017         cx,
1018         tuple_type,
1019         unique_type_id,
1020         create_struct_stub(cx,
1021                            tuple_llvm_type,
1022                            &tuple_name[..],
1023                            unique_type_id,
1024                            NO_SCOPE_METADATA),
1025         tuple_llvm_type,
1026         TupleMDF(TupleMemberDescriptionFactory {
1027             ty: tuple_type,
1028             component_types: component_types.to_vec(),
1029             span: span,
1030         })
1031     )
1032 }
1033
1034 //=-----------------------------------------------------------------------------
1035 // Unions
1036 //=-----------------------------------------------------------------------------
1037
1038 struct UnionMemberDescriptionFactory<'tcx> {
1039     variant: &'tcx ty::VariantDef,
1040     substs: &'tcx Substs<'tcx>,
1041     span: Span,
1042 }
1043
1044 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1045     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1046                                       -> Vec<MemberDescription> {
1047         self.variant.fields.iter().map(|field| {
1048             let fty = monomorphize::field_ty(cx.tcx(), self.substs, field);
1049             MemberDescription {
1050                 name: field.name.to_string(),
1051                 llvm_type: type_of::type_of(cx, fty),
1052                 type_metadata: type_metadata(cx, fty, self.span),
1053                 offset: FixedMemberOffset { bytes: 0 },
1054                 flags: DIFlags::FlagZero,
1055             }
1056         }).collect()
1057     }
1058 }
1059
1060 fn prepare_union_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1061                                     union_type: Ty<'tcx>,
1062                                     unique_type_id: UniqueTypeId,
1063                                     span: Span)
1064                                     -> RecursiveTypeDescription<'tcx> {
1065     let union_name = compute_debuginfo_type_name(cx, union_type, false);
1066     let union_llvm_type = type_of::in_memory_type_of(cx, union_type);
1067
1068     let (union_def_id, variant, substs) = match union_type.sty {
1069         ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
1070         _ => bug!("prepare_union_metadata on a non-ADT")
1071     };
1072
1073     let (containing_scope, _) = get_namespace_and_span_for_item(cx, union_def_id);
1074
1075     let union_metadata_stub = create_union_stub(cx,
1076                                                 union_llvm_type,
1077                                                 &union_name,
1078                                                 unique_type_id,
1079                                                 containing_scope);
1080
1081     create_and_register_recursive_type_forward_declaration(
1082         cx,
1083         union_type,
1084         unique_type_id,
1085         union_metadata_stub,
1086         union_llvm_type,
1087         UnionMDF(UnionMemberDescriptionFactory {
1088             variant: variant,
1089             substs: substs,
1090             span: span,
1091         })
1092     )
1093 }
1094
1095 //=-----------------------------------------------------------------------------
1096 // Enums
1097 //=-----------------------------------------------------------------------------
1098
1099 // Describes the members of an enum value: An enum is described as a union of
1100 // structs in DWARF. This MemberDescriptionFactory provides the description for
1101 // the members of this union; so for every variant of the given enum, this
1102 // factory will produce one MemberDescription (all with no name and a fixed
1103 // offset of zero bytes).
1104 struct EnumMemberDescriptionFactory<'tcx> {
1105     enum_type: Ty<'tcx>,
1106     type_rep: &'tcx layout::Layout,
1107     discriminant_type_metadata: Option<DIType>,
1108     containing_scope: DIScope,
1109     file_metadata: DIFile,
1110     span: Span,
1111 }
1112
1113 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1114     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1115                                       -> Vec<MemberDescription> {
1116         let adt = &self.enum_type.ty_adt_def().unwrap();
1117         let substs = match self.enum_type.sty {
1118             ty::TyAdt(def, ref s) if def.adt_kind() == AdtKind::Enum => s,
1119             _ => bug!("{} is not an enum", self.enum_type)
1120         };
1121         match *self.type_rep {
1122             layout::General { ref variants, .. } => {
1123                 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1124                     .expect(""));
1125                 variants
1126                     .iter()
1127                     .enumerate()
1128                     .map(|(i, struct_def)| {
1129                         let (variant_type_metadata,
1130                              variant_llvm_type,
1131                              member_desc_factory) =
1132                             describe_enum_variant(cx,
1133                                                   self.enum_type,
1134                                                   struct_def,
1135                                                   &adt.variants[i],
1136                                                   discriminant_info,
1137                                                   self.containing_scope,
1138                                                   self.span);
1139
1140                         let member_descriptions = member_desc_factory
1141                             .create_member_descriptions(cx);
1142
1143                         set_members_of_composite_type(cx,
1144                                                       variant_type_metadata,
1145                                                       variant_llvm_type,
1146                                                       &member_descriptions);
1147                         MemberDescription {
1148                             name: "".to_string(),
1149                             llvm_type: variant_llvm_type,
1150                             type_metadata: variant_type_metadata,
1151                             offset: FixedMemberOffset { bytes: 0 },
1152                             flags: DIFlags::FlagZero
1153                         }
1154                     }).collect()
1155             },
1156             layout::Univariant{ ref variant, .. } => {
1157                 assert!(adt.variants.len() <= 1);
1158
1159                 if adt.variants.is_empty() {
1160                     vec![]
1161                 } else {
1162                     let (variant_type_metadata,
1163                          variant_llvm_type,
1164                          member_description_factory) =
1165                         describe_enum_variant(cx,
1166                                               self.enum_type,
1167                                               variant,
1168                                               &adt.variants[0],
1169                                               NoDiscriminant,
1170                                               self.containing_scope,
1171                                               self.span);
1172
1173                     let member_descriptions =
1174                         member_description_factory.create_member_descriptions(cx);
1175
1176                     set_members_of_composite_type(cx,
1177                                                   variant_type_metadata,
1178                                                   variant_llvm_type,
1179                                                   &member_descriptions[..]);
1180                     vec![
1181                         MemberDescription {
1182                             name: "".to_string(),
1183                             llvm_type: variant_llvm_type,
1184                             type_metadata: variant_type_metadata,
1185                             offset: FixedMemberOffset { bytes: 0 },
1186                             flags: DIFlags::FlagZero
1187                         }
1188                     ]
1189                 }
1190             }
1191             layout::RawNullablePointer { nndiscr: non_null_variant_index, .. } => {
1192                 // As far as debuginfo is concerned, the pointer this enum
1193                 // represents is still wrapped in a struct. This is to make the
1194                 // DWARF representation of enums uniform.
1195
1196                 // First create a description of the artificial wrapper struct:
1197                 let non_null_variant = &adt.variants[non_null_variant_index as usize];
1198                 let non_null_variant_name = non_null_variant.name.as_str();
1199
1200                 // The llvm type and metadata of the pointer
1201                 let nnty = monomorphize::field_ty(cx.tcx(), &substs, &non_null_variant.fields[0] );
1202                 let non_null_llvm_type = type_of::type_of(cx, nnty);
1203                 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1204
1205                 // The type of the artificial struct wrapping the pointer
1206                 let artificial_struct_llvm_type = Type::struct_(cx,
1207                                                                 &[non_null_llvm_type],
1208                                                                 false);
1209
1210                 // For the metadata of the wrapper struct, we need to create a
1211                 // MemberDescription of the struct's single field.
1212                 let sole_struct_member_description = MemberDescription {
1213                     name: match non_null_variant.ctor_kind {
1214                         CtorKind::Fn => "__0".to_string(),
1215                         CtorKind::Fictive => {
1216                             non_null_variant.fields[0].name.to_string()
1217                         }
1218                         CtorKind::Const => bug!()
1219                     },
1220                     llvm_type: non_null_llvm_type,
1221                     type_metadata: non_null_type_metadata,
1222                     offset: FixedMemberOffset { bytes: 0 },
1223                     flags: DIFlags::FlagZero
1224                 };
1225
1226                 let unique_type_id = debug_context(cx).type_map
1227                                                       .borrow_mut()
1228                                                       .get_unique_type_id_of_enum_variant(
1229                                                           cx,
1230                                                           self.enum_type,
1231                                                           &non_null_variant_name);
1232
1233                 // Now we can create the metadata of the artificial struct
1234                 let artificial_struct_metadata =
1235                     composite_type_metadata(cx,
1236                                             artificial_struct_llvm_type,
1237                                             &non_null_variant_name,
1238                                             unique_type_id,
1239                                             &[sole_struct_member_description],
1240                                             self.containing_scope,
1241                                             self.file_metadata,
1242                                             syntax_pos::DUMMY_SP);
1243
1244                 // Encode the information about the null variant in the union
1245                 // member's name.
1246                 let null_variant_index = (1 - non_null_variant_index) as usize;
1247                 let null_variant_name = adt.variants[null_variant_index].name;
1248                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1249                                                 0,
1250                                                 null_variant_name);
1251
1252                 // Finally create the (singleton) list of descriptions of union
1253                 // members.
1254                 vec![
1255                     MemberDescription {
1256                         name: union_member_name,
1257                         llvm_type: artificial_struct_llvm_type,
1258                         type_metadata: artificial_struct_metadata,
1259                         offset: FixedMemberOffset { bytes: 0 },
1260                         flags: DIFlags::FlagZero
1261                     }
1262                 ]
1263             },
1264             layout::StructWrappedNullablePointer { nonnull: ref struct_def,
1265                                                 nndiscr,
1266                                                 ref discrfield_source, ..} => {
1267                 // Create a description of the non-null variant
1268                 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1269                     describe_enum_variant(cx,
1270                                           self.enum_type,
1271                                           struct_def,
1272                                           &adt.variants[nndiscr as usize],
1273                                           OptimizedDiscriminant,
1274                                           self.containing_scope,
1275                                           self.span);
1276
1277                 let variant_member_descriptions =
1278                     member_description_factory.create_member_descriptions(cx);
1279
1280                 set_members_of_composite_type(cx,
1281                                               variant_type_metadata,
1282                                               variant_llvm_type,
1283                                               &variant_member_descriptions[..]);
1284
1285                 // Encode the information about the null variant in the union
1286                 // member's name.
1287                 let null_variant_index = (1 - nndiscr) as usize;
1288                 let null_variant_name = adt.variants[null_variant_index].name;
1289                 let discrfield_source = discrfield_source.iter()
1290                                            .skip(1)
1291                                            .map(|x| x.to_string())
1292                                            .collect::<Vec<_>>().join("$");
1293                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1294                                                 discrfield_source,
1295                                                 null_variant_name);
1296
1297                 // Create the (singleton) list of descriptions of union members.
1298                 vec![
1299                     MemberDescription {
1300                         name: union_member_name,
1301                         llvm_type: variant_llvm_type,
1302                         type_metadata: variant_type_metadata,
1303                         offset: FixedMemberOffset { bytes: 0 },
1304                         flags: DIFlags::FlagZero
1305                     }
1306                 ]
1307             },
1308             layout::CEnum { .. } => span_bug!(self.span, "This should be unreachable."),
1309             ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1310         }
1311     }
1312 }
1313
1314 // Creates MemberDescriptions for the fields of a single enum variant.
1315 struct VariantMemberDescriptionFactory<'tcx> {
1316     // Cloned from the layout::Struct describing the variant.
1317     offsets: &'tcx [layout::Size],
1318     args: Vec<(String, Ty<'tcx>)>,
1319     discriminant_type_metadata: Option<DIType>,
1320     span: Span,
1321 }
1322
1323 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1324     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1325                                       -> Vec<MemberDescription> {
1326         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1327             MemberDescription {
1328                 name: name.to_string(),
1329                 llvm_type: type_of::type_of(cx, ty),
1330                 type_metadata: match self.discriminant_type_metadata {
1331                     Some(metadata) if i == 0 => metadata,
1332                     _ => type_metadata(cx, ty, self.span)
1333                 },
1334                 offset: FixedMemberOffset { bytes: self.offsets[i].bytes() as usize },
1335                 flags: DIFlags::FlagZero
1336             }
1337         }).collect()
1338     }
1339 }
1340
1341 #[derive(Copy, Clone)]
1342 enum EnumDiscriminantInfo {
1343     RegularDiscriminant(DIType),
1344     OptimizedDiscriminant,
1345     NoDiscriminant
1346 }
1347
1348 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1349 // of the variant, and (3) a MemberDescriptionFactory for producing the
1350 // descriptions of the fields of the variant. This is a rudimentary version of a
1351 // full RecursiveTypeDescription.
1352 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1353                                    enum_type: Ty<'tcx>,
1354                                    struct_def: &'tcx layout::Struct,
1355                                    variant: &'tcx ty::VariantDef,
1356                                    discriminant_info: EnumDiscriminantInfo,
1357                                    containing_scope: DIScope,
1358                                    span: Span)
1359                                    -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1360     let substs = match enum_type.sty {
1361         ty::TyAdt(def, s) if def.adt_kind() == AdtKind::Enum => s,
1362         ref t @ _ => bug!("{:#?} is not an enum", t)
1363     };
1364
1365     let maybe_discr_and_signed: Option<(layout::Integer, bool)> = match *cx.layout_of(enum_type) {
1366         layout::CEnum {discr, ..} => Some((discr, true)),
1367         layout::General{discr, ..} => Some((discr, false)),
1368         layout::Univariant { .. }
1369         | layout::RawNullablePointer { .. }
1370         | layout::StructWrappedNullablePointer { .. } => None,
1371         ref l @ _ => bug!("This should be unreachable. Type is {:#?} layout is {:#?}", enum_type, l)
1372     };
1373
1374     let mut field_tys = variant.fields.iter().map(|f| {
1375         monomorphize::field_ty(cx.tcx(), &substs, f)
1376     }).collect::<Vec<_>>();
1377
1378     if let Some((discr, signed)) = maybe_discr_and_signed {
1379         field_tys.insert(0, discr.to_ty(&cx.tcx(), signed));
1380     }
1381
1382
1383     let variant_llvm_type =
1384         Type::struct_(cx, &field_tys
1385                                     .iter()
1386                                     .map(|t| type_of::type_of(cx, t))
1387                                     .collect::<Vec<_>>()
1388                                     ,
1389                       struct_def.packed);
1390     // Could do some consistency checks here: size, align, field count, discr type
1391
1392     let variant_name = variant.name.as_str();
1393     let unique_type_id = debug_context(cx).type_map
1394                                           .borrow_mut()
1395                                           .get_unique_type_id_of_enum_variant(
1396                                               cx,
1397                                               enum_type,
1398                                               &variant_name);
1399
1400     let metadata_stub = create_struct_stub(cx,
1401                                            variant_llvm_type,
1402                                            &variant_name,
1403                                            unique_type_id,
1404                                            containing_scope);
1405
1406     // Get the argument names from the enum variant info
1407     let mut arg_names: Vec<_> = match variant.ctor_kind {
1408         CtorKind::Const => vec![],
1409         CtorKind::Fn => {
1410             variant.fields
1411                    .iter()
1412                    .enumerate()
1413                    .map(|(i, _)| format!("__{}", i))
1414                    .collect()
1415         }
1416         CtorKind::Fictive => {
1417             variant.fields
1418                    .iter()
1419                    .map(|f| f.name.to_string())
1420                    .collect()
1421         }
1422     };
1423
1424     // If this is not a univariant enum, there is also the discriminant field.
1425     match discriminant_info {
1426         RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1427         _ => { /* do nothing */ }
1428     };
1429
1430     // Build an array of (field name, field type) pairs to be captured in the factory closure.
1431     let args: Vec<(String, Ty)> = arg_names.iter()
1432         .zip(field_tys.iter())
1433         .map(|(s, &t)| (s.to_string(), t))
1434         .collect();
1435
1436     let member_description_factory =
1437         VariantMDF(VariantMemberDescriptionFactory {
1438             offsets: &struct_def.offsets[..],
1439             args: args,
1440             discriminant_type_metadata: match discriminant_info {
1441                 RegularDiscriminant(discriminant_type_metadata) => {
1442                     Some(discriminant_type_metadata)
1443                 }
1444                 _ => None
1445             },
1446             span: span,
1447         });
1448
1449     (metadata_stub, variant_llvm_type, member_description_factory)
1450 }
1451
1452 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1453                                    enum_type: Ty<'tcx>,
1454                                    enum_def_id: DefId,
1455                                    unique_type_id: UniqueTypeId,
1456                                    span: Span)
1457                                    -> RecursiveTypeDescription<'tcx> {
1458     let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1459
1460     let (containing_scope, _) = get_namespace_and_span_for_item(cx, enum_def_id);
1461     // FIXME: This should emit actual file metadata for the enum, but we
1462     // currently can't get the necessary information when it comes to types
1463     // imported from other crates. Formerly we violated the ODR when performing
1464     // LTO because we emitted debuginfo for the same type with varying file
1465     // metadata, so as a workaround we pretend that the type comes from
1466     // <unknown>
1467     let file_metadata = unknown_file_metadata(cx);
1468
1469     let def = enum_type.ty_adt_def().unwrap();
1470     let enumerators_metadata: Vec<DIDescriptor> = def.discriminants(cx.tcx())
1471         .zip(&def.variants)
1472         .map(|(discr, v)| {
1473             let token = v.name.as_str();
1474             let name = CString::new(token.as_bytes()).unwrap();
1475             unsafe {
1476                 llvm::LLVMRustDIBuilderCreateEnumerator(
1477                     DIB(cx),
1478                     name.as_ptr(),
1479                     // FIXME: what if enumeration has i128 discriminant?
1480                     discr.to_u128_unchecked() as u64)
1481             }
1482         })
1483         .collect();
1484
1485     let discriminant_type_metadata = |inttype: layout::Integer, signed: bool| {
1486         let disr_type_key = (enum_def_id, inttype);
1487         let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1488                                                                  .borrow()
1489                                                                  .get(&disr_type_key).cloned();
1490         match cached_discriminant_type_metadata {
1491             Some(discriminant_type_metadata) => discriminant_type_metadata,
1492             None => {
1493                 let discriminant_llvm_type = Type::from_integer(cx, inttype);
1494                 let (discriminant_size, discriminant_align) =
1495                     size_and_align_of(cx, discriminant_llvm_type);
1496                 let discriminant_base_type_metadata =
1497                     type_metadata(cx,
1498                                   inttype.to_ty(&cx.tcx(), signed),
1499                                   syntax_pos::DUMMY_SP);
1500                 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1501
1502                 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1503                 let discriminant_type_metadata = unsafe {
1504                     llvm::LLVMRustDIBuilderCreateEnumerationType(
1505                         DIB(cx),
1506                         containing_scope,
1507                         name.as_ptr(),
1508                         file_metadata,
1509                         UNKNOWN_LINE_NUMBER,
1510                         bytes_to_bits(discriminant_size),
1511                         bytes_to_bits(discriminant_align),
1512                         create_DIArray(DIB(cx), &enumerators_metadata),
1513                         discriminant_base_type_metadata)
1514                 };
1515
1516                 debug_context(cx).created_enum_disr_types
1517                                  .borrow_mut()
1518                                  .insert(disr_type_key, discriminant_type_metadata);
1519
1520                 discriminant_type_metadata
1521             }
1522         }
1523     };
1524
1525     let type_rep = cx.layout_of(enum_type);
1526
1527     let discriminant_type_metadata = match *type_rep {
1528         layout::CEnum { discr, signed, .. } => {
1529             return FinalMetadata(discriminant_type_metadata(discr, signed))
1530         },
1531         layout::RawNullablePointer { .. }           |
1532         layout::StructWrappedNullablePointer { .. } |
1533         layout::Univariant { .. }                      => None,
1534         layout::General { discr, .. } => Some(discriminant_type_metadata(discr, false)),
1535         ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1536     };
1537
1538     let enum_llvm_type = type_of::type_of(cx, enum_type);
1539     let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1540
1541     let enum_name = CString::new(enum_name).unwrap();
1542     let unique_type_id_str = CString::new(
1543         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1544     ).unwrap();
1545     let enum_metadata = unsafe {
1546         llvm::LLVMRustDIBuilderCreateUnionType(
1547         DIB(cx),
1548         containing_scope,
1549         enum_name.as_ptr(),
1550         file_metadata,
1551         UNKNOWN_LINE_NUMBER,
1552         bytes_to_bits(enum_type_size),
1553         bytes_to_bits(enum_type_align),
1554         DIFlags::FlagZero,
1555         ptr::null_mut(),
1556         0, // RuntimeLang
1557         unique_type_id_str.as_ptr())
1558     };
1559
1560     return create_and_register_recursive_type_forward_declaration(
1561         cx,
1562         enum_type,
1563         unique_type_id,
1564         enum_metadata,
1565         enum_llvm_type,
1566         EnumMDF(EnumMemberDescriptionFactory {
1567             enum_type: enum_type,
1568             type_rep: type_rep.layout,
1569             discriminant_type_metadata: discriminant_type_metadata,
1570             containing_scope: containing_scope,
1571             file_metadata: file_metadata,
1572             span: span,
1573         }),
1574     );
1575
1576     fn get_enum_discriminant_name(cx: &CrateContext,
1577                                   def_id: DefId)
1578                                   -> InternedString {
1579         cx.tcx().item_name(def_id).as_str()
1580     }
1581 }
1582
1583 /// Creates debug information for a composite type, that is, anything that
1584 /// results in a LLVM struct.
1585 ///
1586 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1587 fn composite_type_metadata(cx: &CrateContext,
1588                            composite_llvm_type: Type,
1589                            composite_type_name: &str,
1590                            composite_type_unique_id: UniqueTypeId,
1591                            member_descriptions: &[MemberDescription],
1592                            containing_scope: DIScope,
1593
1594                            // Ignore source location information as long as it
1595                            // can't be reconstructed for non-local crates.
1596                            _file_metadata: DIFile,
1597                            _definition_span: Span)
1598                            -> DICompositeType {
1599     // Create the (empty) struct metadata node ...
1600     let composite_type_metadata = create_struct_stub(cx,
1601                                                      composite_llvm_type,
1602                                                      composite_type_name,
1603                                                      composite_type_unique_id,
1604                                                      containing_scope);
1605     // ... and immediately create and add the member descriptions.
1606     set_members_of_composite_type(cx,
1607                                   composite_type_metadata,
1608                                   composite_llvm_type,
1609                                   member_descriptions);
1610
1611     return composite_type_metadata;
1612 }
1613
1614 fn set_members_of_composite_type(cx: &CrateContext,
1615                                  composite_type_metadata: DICompositeType,
1616                                  composite_llvm_type: Type,
1617                                  member_descriptions: &[MemberDescription]) {
1618     // In some rare cases LLVM metadata uniquing would lead to an existing type
1619     // description being used instead of a new one created in
1620     // create_struct_stub. This would cause a hard to trace assertion in
1621     // DICompositeType::SetTypeArray(). The following check makes sure that we
1622     // get a better error message if this should happen again due to some
1623     // regression.
1624     {
1625         let mut composite_types_completed =
1626             debug_context(cx).composite_types_completed.borrow_mut();
1627         if composite_types_completed.contains(&composite_type_metadata) {
1628             bug!("debuginfo::set_members_of_composite_type() - \
1629                   Already completed forward declaration re-encountered.");
1630         } else {
1631             composite_types_completed.insert(composite_type_metadata);
1632         }
1633     }
1634
1635     let member_metadata: Vec<DIDescriptor> = member_descriptions
1636         .iter()
1637         .enumerate()
1638         .map(|(i, member_description)| {
1639             let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1640             let member_offset = match member_description.offset {
1641                 FixedMemberOffset { bytes } => bytes as u64,
1642                 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1643             };
1644
1645             let member_name = member_description.name.as_bytes();
1646             let member_name = CString::new(member_name).unwrap();
1647             unsafe {
1648                 llvm::LLVMRustDIBuilderCreateMemberType(
1649                     DIB(cx),
1650                     composite_type_metadata,
1651                     member_name.as_ptr(),
1652                     unknown_file_metadata(cx),
1653                     UNKNOWN_LINE_NUMBER,
1654                     bytes_to_bits(member_size),
1655                     bytes_to_bits(member_align),
1656                     bytes_to_bits(member_offset),
1657                     member_description.flags,
1658                     member_description.type_metadata)
1659             }
1660         })
1661         .collect();
1662
1663     unsafe {
1664         let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1665         llvm::LLVMRustDICompositeTypeSetTypeArray(
1666             DIB(cx), composite_type_metadata, type_array);
1667     }
1668 }
1669
1670 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1671 // any caching, does not add any fields to the struct. This can be done later
1672 // with set_members_of_composite_type().
1673 fn create_struct_stub(cx: &CrateContext,
1674                       struct_llvm_type: Type,
1675                       struct_type_name: &str,
1676                       unique_type_id: UniqueTypeId,
1677                       containing_scope: DIScope)
1678                    -> DICompositeType {
1679     let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1680
1681     let name = CString::new(struct_type_name).unwrap();
1682     let unique_type_id = CString::new(
1683         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1684     ).unwrap();
1685     let metadata_stub = unsafe {
1686         // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1687         // pointer will lead to hard to trace and debug LLVM assertions
1688         // later on in llvm/lib/IR/Value.cpp.
1689         let empty_array = create_DIArray(DIB(cx), &[]);
1690
1691         llvm::LLVMRustDIBuilderCreateStructType(
1692             DIB(cx),
1693             containing_scope,
1694             name.as_ptr(),
1695             unknown_file_metadata(cx),
1696             UNKNOWN_LINE_NUMBER,
1697             bytes_to_bits(struct_size),
1698             bytes_to_bits(struct_align),
1699             DIFlags::FlagZero,
1700             ptr::null_mut(),
1701             empty_array,
1702             0,
1703             ptr::null_mut(),
1704             unique_type_id.as_ptr())
1705     };
1706
1707     return metadata_stub;
1708 }
1709
1710 fn create_union_stub(cx: &CrateContext,
1711                      union_llvm_type: Type,
1712                      union_type_name: &str,
1713                      unique_type_id: UniqueTypeId,
1714                      containing_scope: DIScope)
1715                    -> DICompositeType {
1716     let (union_size, union_align) = size_and_align_of(cx, union_llvm_type);
1717
1718     let name = CString::new(union_type_name).unwrap();
1719     let unique_type_id = CString::new(
1720         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1721     ).unwrap();
1722     let metadata_stub = unsafe {
1723         // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
1724         // pointer will lead to hard to trace and debug LLVM assertions
1725         // later on in llvm/lib/IR/Value.cpp.
1726         let empty_array = create_DIArray(DIB(cx), &[]);
1727
1728         llvm::LLVMRustDIBuilderCreateUnionType(
1729             DIB(cx),
1730             containing_scope,
1731             name.as_ptr(),
1732             unknown_file_metadata(cx),
1733             UNKNOWN_LINE_NUMBER,
1734             bytes_to_bits(union_size),
1735             bytes_to_bits(union_align),
1736             DIFlags::FlagZero,
1737             empty_array,
1738             0, // RuntimeLang
1739             unique_type_id.as_ptr())
1740     };
1741
1742     return metadata_stub;
1743 }
1744
1745 /// Creates debug information for the given global variable.
1746 ///
1747 /// Adds the created metadata nodes directly to the crate's IR.
1748 pub fn create_global_var_metadata(cx: &CrateContext,
1749                                   node_id: ast::NodeId,
1750                                   global: ValueRef) {
1751     if cx.dbg_cx().is_none() {
1752         return;
1753     }
1754
1755     let tcx = cx.tcx();
1756
1757     let node_def_id = tcx.hir.local_def_id(node_id);
1758     let (var_scope, span) = get_namespace_and_span_for_item(cx, node_def_id);
1759
1760     let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP {
1761         let loc = span_start(cx, span);
1762         (file_metadata(cx, &loc.file.name, &loc.file.abs_path), loc.line as c_uint)
1763     } else {
1764         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1765     };
1766
1767     let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1768     let variable_type = common::def_ty(cx.shared(), node_def_id, Substs::empty());
1769     let type_metadata = type_metadata(cx, variable_type, span);
1770     let var_name = tcx.item_name(node_def_id).to_string();
1771     let linkage_name = mangled_name_of_item(cx, node_def_id, "");
1772
1773     let var_name = CString::new(var_name).unwrap();
1774     let linkage_name = CString::new(linkage_name).unwrap();
1775
1776     let global_align = cx.align_of(variable_type);
1777
1778     unsafe {
1779         llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1780                                                     var_scope,
1781                                                     var_name.as_ptr(),
1782                                                     linkage_name.as_ptr(),
1783                                                     file_metadata,
1784                                                     line_number,
1785                                                     type_metadata,
1786                                                     is_local_to_unit,
1787                                                     global,
1788                                                     ptr::null_mut(),
1789                                                     global_align,
1790         );
1791     }
1792 }
1793
1794 // Creates an "extension" of an existing DIScope into another file.
1795 pub fn extend_scope_to_file(ccx: &CrateContext,
1796                             scope_metadata: DIScope,
1797                             file: &syntax_pos::FileMap)
1798                             -> DILexicalBlock {
1799     let file_metadata = file_metadata(ccx, &file.name, &file.abs_path);
1800     unsafe {
1801         llvm::LLVMRustDIBuilderCreateLexicalBlockFile(
1802             DIB(ccx),
1803             scope_metadata,
1804             file_metadata)
1805     }
1806 }