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