]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/debuginfo/metadata.rs
Auto merge of #35166 - nikomatsakis:incr-comp-ice-34991-2, r=mw
[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,
18                    fn_should_be_ignored, is_node_local_to_unit};
19 use super::namespace::mangled_name_of_item;
20 use super::type_names::{compute_debuginfo_type_name, push_debuginfo_type_name};
21 use super::{declare_local, VariableKind, VariableAccess, CrateDebugContext};
22 use context::SharedCrateContext;
23 use session::Session;
24
25 use llvm::{self, ValueRef};
26 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor, DICompositeType};
27
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::pat_util;
30 use rustc::ty::subst;
31 use rustc::hir::map as hir_map;
32 use rustc::hir::{self, PatKind};
33 use {type_of, adt, machine, monomorphize};
34 use common::{self, CrateContext, FunctionContext, Block};
35 use _match::{BindingInfo, TransBindingMode};
36 use type_::Type;
37 use rustc::ty::{self, Ty};
38 use session::config::{self, FullDebugInfo};
39 use util::nodemap::FnvHashMap;
40 use util::common::path2cstr;
41
42 use libc::{c_uint, c_longlong};
43 use std::ffi::CString;
44 use std::path::Path;
45 use std::ptr;
46 use std::rc::Rc;
47 use syntax;
48 use syntax::util::interner::Interner;
49 use syntax::ast;
50 use syntax::parse::token;
51 use syntax_pos::{self, Span};
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 const FLAGS_NONE: c_uint = 0;
74
75 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
76 pub struct UniqueTypeId(ast::Name);
77
78 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
79 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
80 // faster lookup, also by Ty. The TypeMap is responsible for creating
81 // UniqueTypeIds.
82 pub struct TypeMap<'tcx> {
83     // The UniqueTypeIds created so far
84     unique_id_interner: Interner,
85     // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
86     unique_id_to_metadata: FnvHashMap<UniqueTypeId, DIType>,
87     // A map from types to debuginfo metadata. This is a N:1 mapping.
88     type_to_metadata: FnvHashMap<Ty<'tcx>, DIType>,
89     // A map from types to UniqueTypeId. This is a N:1 mapping.
90     type_to_unique_id: FnvHashMap<Ty<'tcx>, UniqueTypeId>
91 }
92
93 impl<'tcx> TypeMap<'tcx> {
94     pub fn new() -> TypeMap<'tcx> {
95         TypeMap {
96             unique_id_interner: Interner::new(),
97             type_to_metadata: FnvHashMap(),
98             unique_id_to_metadata: FnvHashMap(),
99             type_to_unique_id: FnvHashMap(),
100         }
101     }
102
103     // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
104     // the mapping already exists.
105     fn register_type_with_metadata<'a>(&mut self,
106                                        type_: Ty<'tcx>,
107                                        metadata: DIType) {
108         if self.type_to_metadata.insert(type_, metadata).is_some() {
109             bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
110         }
111     }
112
113     // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
114     // fail if the mapping already exists.
115     fn register_unique_id_with_metadata(&mut self,
116                                         unique_type_id: UniqueTypeId,
117                                         metadata: DIType) {
118         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
119             let unique_type_id_str = self.get_unique_type_id_as_string(unique_type_id);
120             bug!("Type metadata for unique id '{}' is already in the TypeMap!",
121                  &unique_type_id_str[..]);
122         }
123     }
124
125     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
126         self.type_to_metadata.get(&type_).cloned()
127     }
128
129     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
130         self.unique_id_to_metadata.get(&unique_type_id).cloned()
131     }
132
133     // Get the string representation of a UniqueTypeId. This method will fail if
134     // the id is unknown.
135     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> Rc<String> {
136         let UniqueTypeId(interner_key) = unique_type_id;
137         self.unique_id_interner.get(interner_key)
138     }
139
140     // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
141     // type has been requested before, this is just a table lookup. Otherwise an
142     // ID will be generated and stored for later lookup.
143     fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
144                                       type_: Ty<'tcx>) -> UniqueTypeId {
145
146         // basic type             -> {:name of the type:}
147         // tuple                  -> {tuple_(:param-uid:)*}
148         // struct                 -> {struct_:svh: / :node-id:_<(:param-uid:),*> }
149         // enum                   -> {enum_:svh: / :node-id:_<(:param-uid:),*> }
150         // enum variant           -> {variant_:variant-name:_:enum-uid:}
151         // reference (&)          -> {& :pointee-uid:}
152         // mut reference (&mut)   -> {&mut :pointee-uid:}
153         // ptr (*)                -> {* :pointee-uid:}
154         // mut ptr (*mut)         -> {*mut :pointee-uid:}
155         // unique ptr (box)       -> {box :pointee-uid:}
156         // @-ptr (@)              -> {@ :pointee-uid:}
157         // sized vec ([T; x])     -> {[:size:] :element-uid:}
158         // unsized vec ([T])      -> {[] :element-uid:}
159         // trait (T)              -> {trait_:svh: / :node-id:_<(:param-uid:),*> }
160         // closure                -> {<unsafe_> <once_> :store-sigil: |(:param-uid:),* <,_...>| -> \
161         //                             :return-type-uid: : (:bounds:)*}
162         // function               -> {<unsafe_> <abi_> fn( (:param-uid:)* <,_...> ) -> \
163         //                             :return-type-uid:}
164
165         match self.type_to_unique_id.get(&type_).cloned() {
166             Some(unique_type_id) => return unique_type_id,
167             None => { /* generate one */}
168         };
169
170         let mut unique_type_id = String::with_capacity(256);
171         unique_type_id.push('{');
172
173         match type_.sty {
174             ty::TyBool     |
175             ty::TyChar     |
176             ty::TyStr      |
177             ty::TyInt(_)   |
178             ty::TyUint(_)  |
179             ty::TyFloat(_) => {
180                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
181             },
182             ty::TyEnum(def, substs) => {
183                 unique_type_id.push_str("enum ");
184                 from_def_id_and_substs(self, cx, def.did, substs, &mut unique_type_id);
185             },
186             ty::TyStruct(def, substs) => {
187                 unique_type_id.push_str("struct ");
188                 from_def_id_and_substs(self, cx, def.did, substs, &mut unique_type_id);
189             },
190             ty::TyTuple(component_types) if component_types.is_empty() => {
191                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
192             },
193             ty::TyTuple(component_types) => {
194                 unique_type_id.push_str("tuple ");
195                 for &component_type in component_types {
196                     let component_type_id =
197                         self.get_unique_type_id_of_type(cx, component_type);
198                     let component_type_id =
199                         self.get_unique_type_id_as_string(component_type_id);
200                     unique_type_id.push_str(&component_type_id[..]);
201                 }
202             },
203             ty::TyBox(inner_type) => {
204                 unique_type_id.push_str("box ");
205                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
206                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
207                 unique_type_id.push_str(&inner_type_id[..]);
208             },
209             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
210                 unique_type_id.push('*');
211                 if mutbl == hir::MutMutable {
212                     unique_type_id.push_str("mut");
213                 }
214
215                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
216                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
217                 unique_type_id.push_str(&inner_type_id[..]);
218             },
219             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
220                 unique_type_id.push('&');
221                 if mutbl == hir::MutMutable {
222                     unique_type_id.push_str("mut");
223                 }
224
225                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
226                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
227                 unique_type_id.push_str(&inner_type_id[..]);
228             },
229             ty::TyArray(inner_type, len) => {
230                 unique_type_id.push_str(&format!("[{}]", len));
231
232                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
233                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
234                 unique_type_id.push_str(&inner_type_id[..]);
235             },
236             ty::TySlice(inner_type) => {
237                 unique_type_id.push_str("[]");
238
239                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
240                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
241                 unique_type_id.push_str(&inner_type_id[..]);
242             },
243             ty::TyTrait(ref trait_data) => {
244                 unique_type_id.push_str("trait ");
245
246                 let principal = cx.tcx().erase_late_bound_regions(&trait_data.principal);
247
248                 from_def_id_and_substs(self,
249                                        cx,
250                                        principal.def_id,
251                                        principal.substs,
252                                        &mut unique_type_id);
253             },
254             ty::TyFnDef(_, _, &ty::BareFnTy{ unsafety, abi, ref sig } ) |
255             ty::TyFnPtr(&ty::BareFnTy{ unsafety, abi, ref sig } ) => {
256                 if unsafety == hir::Unsafety::Unsafe {
257                     unique_type_id.push_str("unsafe ");
258                 }
259
260                 unique_type_id.push_str(abi.name());
261
262                 unique_type_id.push_str(" fn(");
263
264                 let sig = cx.tcx().erase_late_bound_regions(sig);
265                 let sig = cx.tcx().normalize_associated_type(&sig);
266
267                 for &parameter_type in &sig.inputs {
268                     let parameter_type_id =
269                         self.get_unique_type_id_of_type(cx, parameter_type);
270                     let parameter_type_id =
271                         self.get_unique_type_id_as_string(parameter_type_id);
272                     unique_type_id.push_str(&parameter_type_id[..]);
273                     unique_type_id.push(',');
274                 }
275
276                 if sig.variadic {
277                     unique_type_id.push_str("...");
278                 }
279
280                 unique_type_id.push_str(")->");
281                 match sig.output {
282                     ty::FnConverging(ret_ty) => {
283                         let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
284                         let return_type_id = self.get_unique_type_id_as_string(return_type_id);
285                         unique_type_id.push_str(&return_type_id[..]);
286                     }
287                     ty::FnDiverging => {
288                         unique_type_id.push_str("!");
289                     }
290                 }
291             },
292             ty::TyClosure(_, substs) if substs.upvar_tys.is_empty() => {
293                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
294             },
295             ty::TyClosure(_, substs) => {
296                 unique_type_id.push_str("closure ");
297                 for upvar_type in substs.upvar_tys {
298                     let upvar_type_id =
299                         self.get_unique_type_id_of_type(cx, upvar_type);
300                     let upvar_type_id =
301                         self.get_unique_type_id_as_string(upvar_type_id);
302                     unique_type_id.push_str(&upvar_type_id[..]);
303                 }
304             },
305             _ => {
306                 bug!("get_unique_type_id_of_type() - unexpected type: {:?}",
307                      type_)
308             }
309         };
310
311         unique_type_id.push('}');
312
313         // Trim to size before storing permanently
314         unique_type_id.shrink_to_fit();
315
316         let key = self.unique_id_interner.intern(unique_type_id);
317         self.type_to_unique_id.insert(type_, UniqueTypeId(key));
318
319         return UniqueTypeId(key);
320
321         fn from_def_id_and_substs<'a, 'tcx>(type_map: &mut TypeMap<'tcx>,
322                                             cx: &CrateContext<'a, 'tcx>,
323                                             def_id: DefId,
324                                             substs: &subst::Substs<'tcx>,
325                                             output: &mut String) {
326             // First, find out the 'real' def_id of the type. Items inlined from
327             // other crates have to be mapped back to their source.
328             let def_id = if let Some(node_id) = cx.tcx().map.as_local_node_id(def_id) {
329                 if cx.tcx().map.is_inlined_node_id(node_id) {
330                     // The given def_id identifies the inlined copy of a
331                     // type definition, let's take the source of the copy.
332                     cx.defid_for_inlined_node(node_id).unwrap()
333                 } else {
334                     def_id
335                 }
336             } else {
337                 def_id
338             };
339
340             // Get the crate name/disambiguator as first part of the identifier.
341             let crate_name = if def_id.is_local() {
342                 cx.tcx().crate_name.clone()
343             } else {
344                 cx.sess().cstore.original_crate_name(def_id.krate)
345             };
346             let crate_disambiguator = cx.tcx().crate_disambiguator(def_id.krate);
347
348             output.push_str(&crate_name[..]);
349             output.push_str("/");
350             output.push_str(&crate_disambiguator[..]);
351             output.push_str("/");
352             // Add the def-index as the second part
353             output.push_str(&format!("{:x}", def_id.index.as_usize()));
354
355             let tps = substs.types.get_slice(subst::TypeSpace);
356             if !tps.is_empty() {
357                 output.push('<');
358
359                 for &type_parameter in tps {
360                     let param_type_id =
361                         type_map.get_unique_type_id_of_type(cx, type_parameter);
362                     let param_type_id =
363                         type_map.get_unique_type_id_as_string(param_type_id);
364                     output.push_str(&param_type_id[..]);
365                     output.push(',');
366                 }
367
368                 output.push('>');
369             }
370         }
371     }
372
373     // Get the UniqueTypeId for an enum variant. Enum variants are not really
374     // types of their own, so they need special handling. We still need a
375     // UniqueTypeId for them, since to debuginfo they *are* real types.
376     fn get_unique_type_id_of_enum_variant<'a>(&mut self,
377                                               cx: &CrateContext<'a, 'tcx>,
378                                               enum_type: Ty<'tcx>,
379                                               variant_name: &str)
380                                               -> UniqueTypeId {
381         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
382         let enum_variant_type_id = format!("{}::{}",
383                                            &self.get_unique_type_id_as_string(enum_type_id),
384                                            variant_name);
385         let interner_key = self.unique_id_interner.intern(enum_variant_type_id);
386         UniqueTypeId(interner_key)
387     }
388 }
389
390 // A description of some recursive type. It can either be already finished (as
391 // with FinalMetadata) or it is not yet finished, but contains all information
392 // needed to generate the missing parts of the description. See the
393 // documentation section on Recursive Types at the top of this file for more
394 // information.
395 enum RecursiveTypeDescription<'tcx> {
396     UnfinishedMetadata {
397         unfinished_type: Ty<'tcx>,
398         unique_type_id: UniqueTypeId,
399         metadata_stub: DICompositeType,
400         llvm_type: Type,
401         member_description_factory: MemberDescriptionFactory<'tcx>,
402     },
403     FinalMetadata(DICompositeType)
404 }
405
406 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
407     cx: &CrateContext<'a, 'tcx>,
408     unfinished_type: Ty<'tcx>,
409     unique_type_id: UniqueTypeId,
410     metadata_stub: DICompositeType,
411     llvm_type: Type,
412     member_description_factory: MemberDescriptionFactory<'tcx>)
413  -> RecursiveTypeDescription<'tcx> {
414
415     // Insert the stub into the TypeMap in order to allow for recursive references
416     let mut type_map = debug_context(cx).type_map.borrow_mut();
417     type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
418     type_map.register_type_with_metadata(unfinished_type, metadata_stub);
419
420     UnfinishedMetadata {
421         unfinished_type: unfinished_type,
422         unique_type_id: unique_type_id,
423         metadata_stub: metadata_stub,
424         llvm_type: llvm_type,
425         member_description_factory: member_description_factory,
426     }
427 }
428
429 impl<'tcx> RecursiveTypeDescription<'tcx> {
430     // Finishes up the description of the type in question (mostly by providing
431     // descriptions of the fields of the given type) and returns the final type
432     // metadata.
433     fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
434         match *self {
435             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
436             UnfinishedMetadata {
437                 unfinished_type,
438                 unique_type_id,
439                 metadata_stub,
440                 llvm_type,
441                 ref member_description_factory,
442                 ..
443             } => {
444                 // Make sure that we have a forward declaration of the type in
445                 // the TypeMap so that recursive references are possible. This
446                 // will always be the case if the RecursiveTypeDescription has
447                 // been properly created through the
448                 // create_and_register_recursive_type_forward_declaration()
449                 // function.
450                 {
451                     let type_map = debug_context(cx).type_map.borrow();
452                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
453                        type_map.find_metadata_for_type(unfinished_type).is_none() {
454                         bug!("Forward declaration of potentially recursive type \
455                               '{:?}' was not found in TypeMap!",
456                              unfinished_type);
457                     }
458                 }
459
460                 // ... then create the member descriptions ...
461                 let member_descriptions =
462                     member_description_factory.create_member_descriptions(cx);
463
464                 // ... and attach them to the stub to complete it.
465                 set_members_of_composite_type(cx,
466                                               metadata_stub,
467                                               llvm_type,
468                                               &member_descriptions[..]);
469                 return MetadataCreationResult::new(metadata_stub, true);
470             }
471         }
472     }
473 }
474
475 // Returns from the enclosing function if the type metadata with the given
476 // unique id can be found in the type map
477 macro_rules! return_if_metadata_created_in_meantime {
478     ($cx: expr, $unique_type_id: expr) => (
479         match debug_context($cx).type_map
480                                 .borrow()
481                                 .find_metadata_for_unique_id($unique_type_id) {
482             Some(metadata) => return MetadataCreationResult::new(metadata, true),
483             None => { /* proceed normally */ }
484         }
485     )
486 }
487
488 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
489                                 unique_type_id: UniqueTypeId,
490                                 element_type: Ty<'tcx>,
491                                 len: Option<u64>,
492                                 span: Span)
493                                 -> MetadataCreationResult {
494     let element_type_metadata = type_metadata(cx, element_type, span);
495
496     return_if_metadata_created_in_meantime!(cx, unique_type_id);
497
498     let element_llvm_type = type_of::type_of(cx, element_type);
499     let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
500
501     let (array_size_in_bytes, upper_bound) = match len {
502         Some(len) => (element_type_size * len, len as c_longlong),
503         None => (0, -1)
504     };
505
506     let subrange = unsafe {
507         llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
508     };
509
510     let subscripts = create_DIArray(DIB(cx), &[subrange]);
511     let metadata = unsafe {
512         llvm::LLVMRustDIBuilderCreateArrayType(
513             DIB(cx),
514             bytes_to_bits(array_size_in_bytes),
515             bytes_to_bits(element_type_align),
516             element_type_metadata,
517             subscripts)
518     };
519
520     return MetadataCreationResult::new(metadata, false);
521 }
522
523 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
524                                 vec_type: Ty<'tcx>,
525                                 element_type: Ty<'tcx>,
526                                 unique_type_id: UniqueTypeId,
527                                 span: Span)
528                                 -> MetadataCreationResult {
529     let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
530         ty: element_type,
531         mutbl: hir::MutImmutable
532     });
533
534     let element_type_metadata = type_metadata(cx, data_ptr_type, span);
535
536     return_if_metadata_created_in_meantime!(cx, unique_type_id);
537
538     let slice_llvm_type = type_of::type_of(cx, vec_type);
539     let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
540
541     let member_llvm_types = slice_llvm_type.field_types();
542     assert!(slice_layout_is_correct(cx,
543                                     &member_llvm_types[..],
544                                     element_type));
545     let member_descriptions = [
546         MemberDescription {
547             name: "data_ptr".to_string(),
548             llvm_type: member_llvm_types[0],
549             type_metadata: element_type_metadata,
550             offset: ComputedMemberOffset,
551             flags: FLAGS_NONE
552         },
553         MemberDescription {
554             name: "length".to_string(),
555             llvm_type: member_llvm_types[1],
556             type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
557             offset: ComputedMemberOffset,
558             flags: FLAGS_NONE
559         },
560     ];
561
562     assert!(member_descriptions.len() == member_llvm_types.len());
563
564     let loc = span_start(cx, span);
565     let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
566
567     let metadata = composite_type_metadata(cx,
568                                            slice_llvm_type,
569                                            &slice_type_name[..],
570                                            unique_type_id,
571                                            &member_descriptions,
572                                            NO_SCOPE_METADATA,
573                                            file_metadata,
574                                            span);
575     return MetadataCreationResult::new(metadata, false);
576
577     fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
578                                          member_llvm_types: &[Type],
579                                          element_type: Ty<'tcx>)
580                                          -> bool {
581         member_llvm_types.len() == 2 &&
582         member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
583         member_llvm_types[1] == cx.int_type()
584     }
585 }
586
587 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
588                                       unique_type_id: UniqueTypeId,
589                                       signature: &ty::PolyFnSig<'tcx>,
590                                       span: Span)
591                                       -> MetadataCreationResult
592 {
593     let signature = cx.tcx().erase_late_bound_regions(signature);
594
595     let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
596
597     // return type
598     signature_metadata.push(match signature.output {
599         ty::FnConverging(ret_ty) => match ret_ty.sty {
600             ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
601             _ => type_metadata(cx, ret_ty, span)
602         },
603         ty::FnDiverging => diverging_type_metadata(cx)
604     });
605
606     // regular arguments
607     for &argument_type in &signature.inputs {
608         signature_metadata.push(type_metadata(cx, argument_type, span));
609     }
610
611     return_if_metadata_created_in_meantime!(cx, unique_type_id);
612
613     return MetadataCreationResult::new(
614         unsafe {
615             llvm::LLVMRustDIBuilderCreateSubroutineType(
616                 DIB(cx),
617                 unknown_file_metadata(cx),
618                 create_DIArray(DIB(cx), &signature_metadata[..]))
619         },
620         false);
621 }
622
623 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
624 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
625 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
626 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
627 // of a DST struct, there is no trait_object_type and the results of this
628 // function will be a little bit weird.
629 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
630                                     trait_type: Ty<'tcx>,
631                                     trait_object_type: Option<Ty<'tcx>>,
632                                     unique_type_id: UniqueTypeId)
633                                     -> DIType {
634     // The implementation provided here is a stub. It makes sure that the trait
635     // type is assigned the correct name, size, namespace, and source location.
636     // But it does not describe the trait's methods.
637
638     let def_id = match trait_type.sty {
639         ty::TyTrait(ref data) => data.principal_def_id(),
640         _ => {
641             bug!("debuginfo: Unexpected trait-object type in \
642                   trait_pointer_metadata(): {:?}",
643                  trait_type);
644         }
645     };
646
647     let trait_object_type = trait_object_type.unwrap_or(trait_type);
648     let trait_type_name =
649         compute_debuginfo_type_name(cx, trait_object_type, false);
650
651     let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
652
653     let trait_llvm_type = type_of::type_of(cx, trait_object_type);
654     let file_metadata = unknown_file_metadata(cx);
655
656     composite_type_metadata(cx,
657                             trait_llvm_type,
658                             &trait_type_name[..],
659                             unique_type_id,
660                             &[],
661                             containing_scope,
662                             file_metadata,
663                             syntax_pos::DUMMY_SP)
664 }
665
666 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
667                                t: Ty<'tcx>,
668                                usage_site_span: Span)
669                                -> DIType {
670     // Get the unique type id of this type.
671     let unique_type_id = {
672         let mut type_map = debug_context(cx).type_map.borrow_mut();
673         // First, try to find the type in TypeMap. If we have seen it before, we
674         // can exit early here.
675         match type_map.find_metadata_for_type(t) {
676             Some(metadata) => {
677                 return metadata;
678             },
679             None => {
680                 // The Ty is not in the TypeMap but maybe we have already seen
681                 // an equivalent type (e.g. only differing in region arguments).
682                 // In order to find out, generate the unique type id and look
683                 // that up.
684                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
685                 match type_map.find_metadata_for_unique_id(unique_type_id) {
686                     Some(metadata) => {
687                         // There is already an equivalent type in the TypeMap.
688                         // Register this Ty as an alias in the cache and
689                         // return the cached metadata.
690                         type_map.register_type_with_metadata(t, metadata);
691                         return metadata;
692                     },
693                     None => {
694                         // There really is no type metadata for this type, so
695                         // proceed by creating it.
696                         unique_type_id
697                     }
698                 }
699             }
700         }
701     };
702
703     debug!("type_metadata: {:?}", t);
704
705     let sty = &t.sty;
706     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
707         ty::TyBool     |
708         ty::TyChar     |
709         ty::TyInt(_)   |
710         ty::TyUint(_)  |
711         ty::TyFloat(_) => {
712             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
713         }
714         ty::TyTuple(ref elements) if elements.is_empty() => {
715             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
716         }
717         ty::TyEnum(def, _) => {
718             prepare_enum_metadata(cx,
719                                   t,
720                                   def.did,
721                                   unique_type_id,
722                                   usage_site_span).finalize(cx)
723         }
724         ty::TyArray(typ, len) => {
725             fixed_vec_metadata(cx, unique_type_id, typ, Some(len as u64), usage_site_span)
726         }
727         ty::TySlice(typ) => {
728             fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
729         }
730         ty::TyStr => {
731             fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
732         }
733         ty::TyTrait(..) => {
734             MetadataCreationResult::new(
735                         trait_pointer_metadata(cx, t, None, unique_type_id),
736             false)
737         }
738         ty::TyBox(ty) |
739         ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
740         ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
741             match ty.sty {
742                 ty::TySlice(typ) => {
743                     vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
744                 }
745                 ty::TyStr => {
746                     vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span)
747                 }
748                 ty::TyTrait(..) => {
749                     MetadataCreationResult::new(
750                         trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
751                         false)
752                 }
753                 _ => {
754                     let pointee_metadata = type_metadata(cx, ty, usage_site_span);
755
756                     match debug_context(cx).type_map
757                                            .borrow()
758                                            .find_metadata_for_unique_id(unique_type_id) {
759                         Some(metadata) => return metadata,
760                         None => { /* proceed normally */ }
761                     };
762
763                     MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
764                                                 false)
765                 }
766             }
767         }
768         ty::TyFnDef(_, _, ref barefnty) | ty::TyFnPtr(ref barefnty) => {
769             let fn_metadata = subroutine_type_metadata(cx,
770                                                        unique_type_id,
771                                                        &barefnty.sig,
772                                                        usage_site_span).metadata;
773             match debug_context(cx).type_map
774                                    .borrow()
775                                    .find_metadata_for_unique_id(unique_type_id) {
776                 Some(metadata) => return metadata,
777                 None => { /* proceed normally */ }
778             };
779
780             // This is actually a function pointer, so wrap it in pointer DI
781             MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
782
783         }
784         ty::TyClosure(_, ref substs) => {
785             prepare_tuple_metadata(cx,
786                                    t,
787                                    &substs.upvar_tys,
788                                    unique_type_id,
789                                    usage_site_span).finalize(cx)
790         }
791         ty::TyStruct(..) => {
792             prepare_struct_metadata(cx,
793                                     t,
794                                     unique_type_id,
795                                     usage_site_span).finalize(cx)
796         }
797         ty::TyTuple(ref elements) => {
798             prepare_tuple_metadata(cx,
799                                    t,
800                                    &elements[..],
801                                    unique_type_id,
802                                    usage_site_span).finalize(cx)
803         }
804         _ => {
805             bug!("debuginfo: unexpected type in type_metadata: {:?}", sty)
806         }
807     };
808
809     {
810         let mut type_map = debug_context(cx).type_map.borrow_mut();
811
812         if already_stored_in_typemap {
813             // Also make sure that we already have a TypeMap entry for the unique type id.
814             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
815                 Some(metadata) => metadata,
816                 None => {
817                     let unique_type_id_str =
818                         type_map.get_unique_type_id_as_string(unique_type_id);
819                     span_bug!(usage_site_span,
820                               "Expected type metadata for unique \
821                                type id '{}' to already be in \
822                                the debuginfo::TypeMap but it \
823                                was not. (Ty = {})",
824                               &unique_type_id_str[..],
825                               t);
826                 }
827             };
828
829             match type_map.find_metadata_for_type(t) {
830                 Some(metadata) => {
831                     if metadata != metadata_for_uid {
832                         let unique_type_id_str =
833                             type_map.get_unique_type_id_as_string(unique_type_id);
834                         span_bug!(usage_site_span,
835                                   "Mismatch between Ty and \
836                                    UniqueTypeId maps in \
837                                    debuginfo::TypeMap. \
838                                    UniqueTypeId={}, Ty={}",
839                                   &unique_type_id_str[..],
840                                   t);
841                     }
842                 }
843                 None => {
844                     type_map.register_type_with_metadata(t, metadata);
845                 }
846             }
847         } else {
848             type_map.register_type_with_metadata(t, metadata);
849             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
850         }
851     }
852
853     metadata
854 }
855
856 pub fn file_metadata(cx: &CrateContext, path: &str, full_path: &Option<String>) -> DIFile {
857     // FIXME (#9639): This needs to handle non-utf8 paths
858     let work_dir = cx.sess().working_dir.to_str().unwrap();
859     let file_name =
860         full_path.as_ref().map(|p| p.as_str()).unwrap_or_else(|| {
861             if path.starts_with(work_dir) {
862                 &path[work_dir.len() + 1..path.len()]
863             } else {
864                 path
865             }
866         });
867
868     file_metadata_(cx, path, file_name, &work_dir)
869 }
870
871 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
872     // Regular filenames should not be empty, so we abuse an empty name as the
873     // key for the special unknown file metadata
874     file_metadata_(cx, "", "<unknown>", "")
875
876 }
877
878 fn file_metadata_(cx: &CrateContext, key: &str, file_name: &str, work_dir: &str) -> DIFile {
879     if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(key) {
880         return *file_metadata;
881     }
882
883     debug!("file_metadata: file_name: {}, work_dir: {}", file_name, work_dir);
884
885     let file_name = CString::new(file_name).unwrap();
886     let work_dir = CString::new(work_dir).unwrap();
887     let file_metadata = unsafe {
888         llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
889                                           work_dir.as_ptr())
890     };
891
892     let mut created_files = debug_context(cx).created_files.borrow_mut();
893     created_files.insert(key.to_string(), file_metadata);
894     file_metadata
895 }
896
897 /// Finds the scope metadata node for the given AST node.
898 pub fn scope_metadata(fcx: &FunctionContext,
899                   node_id: ast::NodeId,
900                   error_reporting_span: Span)
901                -> DIScope {
902     let scope_map = &fcx.debug_context
903                         .get_ref(error_reporting_span)
904                         .scope_map;
905     match scope_map.borrow().get(&node_id).cloned() {
906         Some(scope_metadata) => scope_metadata,
907         None => {
908             let node = fcx.ccx.tcx().map.get(node_id);
909
910             span_bug!(error_reporting_span,
911                       "debuginfo: Could not find scope info for node {:?}",
912                       node);
913         }
914     }
915 }
916
917 pub fn diverging_type_metadata(cx: &CrateContext) -> DIType {
918     unsafe {
919         llvm::LLVMRustDIBuilderCreateBasicType(
920             DIB(cx),
921             "!\0".as_ptr() as *const _,
922             bytes_to_bits(0),
923             bytes_to_bits(0),
924             DW_ATE_unsigned)
925     }
926 }
927
928 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
929                                  t: Ty<'tcx>) -> DIType {
930
931     debug!("basic_type_metadata: {:?}", t);
932
933     let (name, encoding) = match t.sty {
934         ty::TyTuple(ref elements) if elements.is_empty() =>
935             ("()", DW_ATE_unsigned),
936         ty::TyBool => ("bool", DW_ATE_boolean),
937         ty::TyChar => ("char", DW_ATE_unsigned_char),
938         ty::TyInt(int_ty) => {
939             (int_ty.ty_to_string(), DW_ATE_signed)
940         },
941         ty::TyUint(uint_ty) => {
942             (uint_ty.ty_to_string(), DW_ATE_unsigned)
943         },
944         ty::TyFloat(float_ty) => {
945             (float_ty.ty_to_string(), DW_ATE_float)
946         },
947         _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
948     };
949
950     let llvm_type = type_of::type_of(cx, t);
951     let (size, align) = size_and_align_of(cx, llvm_type);
952     let name = CString::new(name).unwrap();
953     let ty_metadata = unsafe {
954         llvm::LLVMRustDIBuilderCreateBasicType(
955             DIB(cx),
956             name.as_ptr(),
957             bytes_to_bits(size),
958             bytes_to_bits(align),
959             encoding)
960     };
961
962     return ty_metadata;
963 }
964
965 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
966                                    pointer_type: Ty<'tcx>,
967                                    pointee_type_metadata: DIType)
968                                    -> DIType {
969     let pointer_llvm_type = type_of::type_of(cx, pointer_type);
970     let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
971     let name = compute_debuginfo_type_name(cx, pointer_type, false);
972     let name = CString::new(name).unwrap();
973     let ptr_metadata = unsafe {
974         llvm::LLVMRustDIBuilderCreatePointerType(
975             DIB(cx),
976             pointee_type_metadata,
977             bytes_to_bits(pointer_size),
978             bytes_to_bits(pointer_align),
979             name.as_ptr())
980     };
981     return ptr_metadata;
982 }
983
984 pub fn compile_unit_metadata(scc: &SharedCrateContext,
985                              debug_context: &CrateDebugContext,
986                              sess: &Session)
987                              -> DIDescriptor {
988     let work_dir = &sess.working_dir;
989     let compile_unit_name = match sess.local_crate_source_file {
990         None => fallback_path(scc),
991         Some(ref abs_path) => {
992             if abs_path.is_relative() {
993                 sess.warn("debuginfo: Invalid path to crate's local root source file!");
994                 fallback_path(scc)
995             } else {
996                 match abs_path.strip_prefix(work_dir) {
997                     Ok(ref p) if p.is_relative() => {
998                         if p.starts_with(Path::new("./")) {
999                             path2cstr(p)
1000                         } else {
1001                             path2cstr(&Path::new(".").join(p))
1002                         }
1003                     }
1004                     _ => fallback_path(scc)
1005                 }
1006             }
1007         }
1008     };
1009
1010     debug!("compile_unit_metadata: {:?}", compile_unit_name);
1011     let producer = format!("rustc version {}",
1012                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
1013
1014     let compile_unit_name = compile_unit_name.as_ptr();
1015     let work_dir = path2cstr(&work_dir);
1016     let producer = CString::new(producer).unwrap();
1017     let flags = "\0";
1018     let split_name = "\0";
1019     return unsafe {
1020         llvm::LLVMRustDIBuilderCreateCompileUnit(
1021             debug_context.builder,
1022             DW_LANG_RUST,
1023             compile_unit_name,
1024             work_dir.as_ptr(),
1025             producer.as_ptr(),
1026             sess.opts.optimize != config::OptLevel::No,
1027             flags.as_ptr() as *const _,
1028             0,
1029             split_name.as_ptr() as *const _)
1030     };
1031
1032     fn fallback_path(scc: &SharedCrateContext) -> CString {
1033         CString::new(scc.link_meta().crate_name.clone()).unwrap()
1034     }
1035 }
1036
1037 struct MetadataCreationResult {
1038     metadata: DIType,
1039     already_stored_in_typemap: bool
1040 }
1041
1042 impl MetadataCreationResult {
1043     fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
1044         MetadataCreationResult {
1045             metadata: metadata,
1046             already_stored_in_typemap: already_stored_in_typemap
1047         }
1048     }
1049 }
1050
1051 #[derive(Debug)]
1052 enum MemberOffset {
1053     FixedMemberOffset { bytes: usize },
1054     // For ComputedMemberOffset, the offset is read from the llvm type definition.
1055     ComputedMemberOffset
1056 }
1057
1058 // Description of a type member, which can either be a regular field (as in
1059 // structs or tuples) or an enum variant.
1060 #[derive(Debug)]
1061 struct MemberDescription {
1062     name: String,
1063     llvm_type: Type,
1064     type_metadata: DIType,
1065     offset: MemberOffset,
1066     flags: c_uint
1067 }
1068
1069 // A factory for MemberDescriptions. It produces a list of member descriptions
1070 // for some record-like type. MemberDescriptionFactories are used to defer the
1071 // creation of type member descriptions in order to break cycles arising from
1072 // recursive type definitions.
1073 enum MemberDescriptionFactory<'tcx> {
1074     StructMDF(StructMemberDescriptionFactory<'tcx>),
1075     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1076     EnumMDF(EnumMemberDescriptionFactory<'tcx>),
1077     VariantMDF(VariantMemberDescriptionFactory<'tcx>)
1078 }
1079
1080 impl<'tcx> MemberDescriptionFactory<'tcx> {
1081     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1082                                       -> Vec<MemberDescription> {
1083         match *self {
1084             StructMDF(ref this) => {
1085                 this.create_member_descriptions(cx)
1086             }
1087             TupleMDF(ref this) => {
1088                 this.create_member_descriptions(cx)
1089             }
1090             EnumMDF(ref this) => {
1091                 this.create_member_descriptions(cx)
1092             }
1093             VariantMDF(ref this) => {
1094                 this.create_member_descriptions(cx)
1095             }
1096         }
1097     }
1098 }
1099
1100 //=-----------------------------------------------------------------------------
1101 // Structs
1102 //=-----------------------------------------------------------------------------
1103
1104 // Creates MemberDescriptions for the fields of a struct
1105 struct StructMemberDescriptionFactory<'tcx> {
1106     variant: ty::VariantDef<'tcx>,
1107     substs: &'tcx subst::Substs<'tcx>,
1108     is_simd: bool,
1109     span: Span,
1110 }
1111
1112 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1113     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1114                                       -> Vec<MemberDescription> {
1115         if self.variant.kind == ty::VariantKind::Unit {
1116             return Vec::new();
1117         }
1118
1119         let field_size = if self.is_simd {
1120             let fty = monomorphize::field_ty(cx.tcx(),
1121                                              self.substs,
1122                                              &self.variant.fields[0]);
1123             Some(machine::llsize_of_alloc(
1124                 cx,
1125                 type_of::type_of(cx, fty)
1126             ) as usize)
1127         } else {
1128             None
1129         };
1130
1131         self.variant.fields.iter().enumerate().map(|(i, f)| {
1132             let name = if self.variant.kind == ty::VariantKind::Tuple {
1133                 format!("__{}", i)
1134             } else {
1135                 f.name.to_string()
1136             };
1137             let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
1138
1139             let offset = if self.is_simd {
1140                 FixedMemberOffset { bytes: i * field_size.unwrap() }
1141             } else {
1142                 ComputedMemberOffset
1143             };
1144
1145             MemberDescription {
1146                 name: name,
1147                 llvm_type: type_of::type_of(cx, fty),
1148                 type_metadata: type_metadata(cx, fty, self.span),
1149                 offset: offset,
1150                 flags: FLAGS_NONE,
1151             }
1152         }).collect()
1153     }
1154 }
1155
1156
1157 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1158                                      struct_type: Ty<'tcx>,
1159                                      unique_type_id: UniqueTypeId,
1160                                      span: Span)
1161                                      -> RecursiveTypeDescription<'tcx> {
1162     let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
1163     let struct_llvm_type = type_of::in_memory_type_of(cx, struct_type);
1164
1165     let (struct_def_id, variant, substs) = match struct_type.sty {
1166         ty::TyStruct(def, substs) => (def.did, def.struct_variant(), substs),
1167         _ => bug!("prepare_struct_metadata on a non-struct")
1168     };
1169
1170     let (containing_scope, _) = get_namespace_and_span_for_item(cx, struct_def_id);
1171
1172     let struct_metadata_stub = create_struct_stub(cx,
1173                                                   struct_llvm_type,
1174                                                   &struct_name,
1175                                                   unique_type_id,
1176                                                   containing_scope);
1177
1178     create_and_register_recursive_type_forward_declaration(
1179         cx,
1180         struct_type,
1181         unique_type_id,
1182         struct_metadata_stub,
1183         struct_llvm_type,
1184         StructMDF(StructMemberDescriptionFactory {
1185             variant: variant,
1186             substs: substs,
1187             is_simd: struct_type.is_simd(),
1188             span: span,
1189         })
1190     )
1191 }
1192
1193
1194 //=-----------------------------------------------------------------------------
1195 // Tuples
1196 //=-----------------------------------------------------------------------------
1197
1198 // Creates MemberDescriptions for the fields of a tuple
1199 struct TupleMemberDescriptionFactory<'tcx> {
1200     component_types: Vec<Ty<'tcx>>,
1201     span: Span,
1202 }
1203
1204 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1205     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1206                                       -> Vec<MemberDescription> {
1207         self.component_types
1208             .iter()
1209             .enumerate()
1210             .map(|(i, &component_type)| {
1211             MemberDescription {
1212                 name: format!("__{}", i),
1213                 llvm_type: type_of::type_of(cx, component_type),
1214                 type_metadata: type_metadata(cx, component_type, self.span),
1215                 offset: ComputedMemberOffset,
1216                 flags: FLAGS_NONE,
1217             }
1218         }).collect()
1219     }
1220 }
1221
1222 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1223                                     tuple_type: Ty<'tcx>,
1224                                     component_types: &[Ty<'tcx>],
1225                                     unique_type_id: UniqueTypeId,
1226                                     span: Span)
1227                                     -> RecursiveTypeDescription<'tcx> {
1228     let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1229     let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1230
1231     create_and_register_recursive_type_forward_declaration(
1232         cx,
1233         tuple_type,
1234         unique_type_id,
1235         create_struct_stub(cx,
1236                            tuple_llvm_type,
1237                            &tuple_name[..],
1238                            unique_type_id,
1239                            NO_SCOPE_METADATA),
1240         tuple_llvm_type,
1241         TupleMDF(TupleMemberDescriptionFactory {
1242             component_types: component_types.to_vec(),
1243             span: span,
1244         })
1245     )
1246 }
1247
1248
1249 //=-----------------------------------------------------------------------------
1250 // Enums
1251 //=-----------------------------------------------------------------------------
1252
1253 // Describes the members of an enum value: An enum is described as a union of
1254 // structs in DWARF. This MemberDescriptionFactory provides the description for
1255 // the members of this union; so for every variant of the given enum, this
1256 // factory will produce one MemberDescription (all with no name and a fixed
1257 // offset of zero bytes).
1258 struct EnumMemberDescriptionFactory<'tcx> {
1259     enum_type: Ty<'tcx>,
1260     type_rep: Rc<adt::Repr<'tcx>>,
1261     discriminant_type_metadata: Option<DIType>,
1262     containing_scope: DIScope,
1263     file_metadata: DIFile,
1264     span: Span,
1265 }
1266
1267 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1268     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1269                                       -> Vec<MemberDescription> {
1270         let adt = &self.enum_type.ty_adt_def().unwrap();
1271         match *self.type_rep {
1272             adt::General(_, ref struct_defs, _) => {
1273                 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1274                     .expect(""));
1275                 struct_defs
1276                     .iter()
1277                     .enumerate()
1278                     .map(|(i, struct_def)| {
1279                         let (variant_type_metadata,
1280                              variant_llvm_type,
1281                              member_desc_factory) =
1282                             describe_enum_variant(cx,
1283                                                   self.enum_type,
1284                                                   struct_def,
1285                                                   &adt.variants[i],
1286                                                   discriminant_info,
1287                                                   self.containing_scope,
1288                                                   self.span);
1289
1290                         let member_descriptions = member_desc_factory
1291                             .create_member_descriptions(cx);
1292
1293                         set_members_of_composite_type(cx,
1294                                                       variant_type_metadata,
1295                                                       variant_llvm_type,
1296                                                       &member_descriptions);
1297                         MemberDescription {
1298                             name: "".to_string(),
1299                             llvm_type: variant_llvm_type,
1300                             type_metadata: variant_type_metadata,
1301                             offset: FixedMemberOffset { bytes: 0 },
1302                             flags: FLAGS_NONE
1303                         }
1304                     }).collect()
1305             },
1306             adt::Univariant(ref struct_def, _) => {
1307                 assert!(adt.variants.len() <= 1);
1308
1309                 if adt.variants.is_empty() {
1310                     vec![]
1311                 } else {
1312                     let (variant_type_metadata,
1313                          variant_llvm_type,
1314                          member_description_factory) =
1315                         describe_enum_variant(cx,
1316                                               self.enum_type,
1317                                               struct_def,
1318                                               &adt.variants[0],
1319                                               NoDiscriminant,
1320                                               self.containing_scope,
1321                                               self.span);
1322
1323                     let member_descriptions =
1324                         member_description_factory.create_member_descriptions(cx);
1325
1326                     set_members_of_composite_type(cx,
1327                                                   variant_type_metadata,
1328                                                   variant_llvm_type,
1329                                                   &member_descriptions[..]);
1330                     vec![
1331                         MemberDescription {
1332                             name: "".to_string(),
1333                             llvm_type: variant_llvm_type,
1334                             type_metadata: variant_type_metadata,
1335                             offset: FixedMemberOffset { bytes: 0 },
1336                             flags: FLAGS_NONE
1337                         }
1338                     ]
1339                 }
1340             }
1341             adt::RawNullablePointer { nndiscr: non_null_variant_index, nnty, .. } => {
1342                 // As far as debuginfo is concerned, the pointer this enum
1343                 // represents is still wrapped in a struct. This is to make the
1344                 // DWARF representation of enums uniform.
1345
1346                 // First create a description of the artificial wrapper struct:
1347                 let non_null_variant = &adt.variants[non_null_variant_index.0 as usize];
1348                 let non_null_variant_name = non_null_variant.name.as_str();
1349
1350                 // The llvm type and metadata of the pointer
1351                 let non_null_llvm_type = type_of::type_of(cx, nnty);
1352                 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1353
1354                 // The type of the artificial struct wrapping the pointer
1355                 let artificial_struct_llvm_type = Type::struct_(cx,
1356                                                                 &[non_null_llvm_type],
1357                                                                 false);
1358
1359                 // For the metadata of the wrapper struct, we need to create a
1360                 // MemberDescription of the struct's single field.
1361                 let sole_struct_member_description = MemberDescription {
1362                     name: match non_null_variant.kind {
1363                         ty::VariantKind::Tuple => "__0".to_string(),
1364                         ty::VariantKind::Struct => {
1365                             non_null_variant.fields[0].name.to_string()
1366                         }
1367                         ty::VariantKind::Unit => bug!()
1368                     },
1369                     llvm_type: non_null_llvm_type,
1370                     type_metadata: non_null_type_metadata,
1371                     offset: FixedMemberOffset { bytes: 0 },
1372                     flags: FLAGS_NONE
1373                 };
1374
1375                 let unique_type_id = debug_context(cx).type_map
1376                                                       .borrow_mut()
1377                                                       .get_unique_type_id_of_enum_variant(
1378                                                           cx,
1379                                                           self.enum_type,
1380                                                           &non_null_variant_name);
1381
1382                 // Now we can create the metadata of the artificial struct
1383                 let artificial_struct_metadata =
1384                     composite_type_metadata(cx,
1385                                             artificial_struct_llvm_type,
1386                                             &non_null_variant_name,
1387                                             unique_type_id,
1388                                             &[sole_struct_member_description],
1389                                             self.containing_scope,
1390                                             self.file_metadata,
1391                                             syntax_pos::DUMMY_SP);
1392
1393                 // Encode the information about the null variant in the union
1394                 // member's name.
1395                 let null_variant_index = (1 - non_null_variant_index.0) as usize;
1396                 let null_variant_name = adt.variants[null_variant_index].name;
1397                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1398                                                 0,
1399                                                 null_variant_name);
1400
1401                 // Finally create the (singleton) list of descriptions of union
1402                 // members.
1403                 vec![
1404                     MemberDescription {
1405                         name: union_member_name,
1406                         llvm_type: artificial_struct_llvm_type,
1407                         type_metadata: artificial_struct_metadata,
1408                         offset: FixedMemberOffset { bytes: 0 },
1409                         flags: FLAGS_NONE
1410                     }
1411                 ]
1412             },
1413             adt::StructWrappedNullablePointer { nonnull: ref struct_def,
1414                                                 nndiscr,
1415                                                 ref discrfield, ..} => {
1416                 // Create a description of the non-null variant
1417                 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1418                     describe_enum_variant(cx,
1419                                           self.enum_type,
1420                                           struct_def,
1421                                           &adt.variants[nndiscr.0 as usize],
1422                                           OptimizedDiscriminant,
1423                                           self.containing_scope,
1424                                           self.span);
1425
1426                 let variant_member_descriptions =
1427                     member_description_factory.create_member_descriptions(cx);
1428
1429                 set_members_of_composite_type(cx,
1430                                               variant_type_metadata,
1431                                               variant_llvm_type,
1432                                               &variant_member_descriptions[..]);
1433
1434                 // Encode the information about the null variant in the union
1435                 // member's name.
1436                 let null_variant_index = (1 - nndiscr.0) as usize;
1437                 let null_variant_name = adt.variants[null_variant_index].name;
1438                 let discrfield = discrfield.iter()
1439                                            .skip(1)
1440                                            .map(|x| x.to_string())
1441                                            .collect::<Vec<_>>().join("$");
1442                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1443                                                 discrfield,
1444                                                 null_variant_name);
1445
1446                 // Create the (singleton) list of descriptions of union members.
1447                 vec![
1448                     MemberDescription {
1449                         name: union_member_name,
1450                         llvm_type: variant_llvm_type,
1451                         type_metadata: variant_type_metadata,
1452                         offset: FixedMemberOffset { bytes: 0 },
1453                         flags: FLAGS_NONE
1454                     }
1455                 ]
1456             },
1457             adt::CEnum(..) => span_bug!(self.span, "This should be unreachable.")
1458         }
1459     }
1460 }
1461
1462 // Creates MemberDescriptions for the fields of a single enum variant.
1463 struct VariantMemberDescriptionFactory<'tcx> {
1464     args: Vec<(String, Ty<'tcx>)>,
1465     discriminant_type_metadata: Option<DIType>,
1466     span: Span,
1467 }
1468
1469 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1470     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1471                                       -> Vec<MemberDescription> {
1472         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1473             MemberDescription {
1474                 name: name.to_string(),
1475                 llvm_type: type_of::type_of(cx, ty),
1476                 type_metadata: match self.discriminant_type_metadata {
1477                     Some(metadata) if i == 0 => metadata,
1478                     _ => type_metadata(cx, ty, self.span)
1479                 },
1480                 offset: ComputedMemberOffset,
1481                 flags: FLAGS_NONE
1482             }
1483         }).collect()
1484     }
1485 }
1486
1487 #[derive(Copy, Clone)]
1488 enum EnumDiscriminantInfo {
1489     RegularDiscriminant(DIType),
1490     OptimizedDiscriminant,
1491     NoDiscriminant
1492 }
1493
1494 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1495 // of the variant, and (3) a MemberDescriptionFactory for producing the
1496 // descriptions of the fields of the variant. This is a rudimentary version of a
1497 // full RecursiveTypeDescription.
1498 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1499                                    enum_type: Ty<'tcx>,
1500                                    struct_def: &adt::Struct<'tcx>,
1501                                    variant: ty::VariantDef<'tcx>,
1502                                    discriminant_info: EnumDiscriminantInfo,
1503                                    containing_scope: DIScope,
1504                                    span: Span)
1505                                    -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1506     let variant_llvm_type =
1507         Type::struct_(cx, &struct_def.fields
1508                                     .iter()
1509                                     .map(|&t| type_of::type_of(cx, t))
1510                                     .collect::<Vec<_>>()
1511                                     ,
1512                       struct_def.packed);
1513     // Could do some consistency checks here: size, align, field count, discr type
1514
1515     let variant_name = variant.name.as_str();
1516     let unique_type_id = debug_context(cx).type_map
1517                                           .borrow_mut()
1518                                           .get_unique_type_id_of_enum_variant(
1519                                               cx,
1520                                               enum_type,
1521                                               &variant_name);
1522
1523     let metadata_stub = create_struct_stub(cx,
1524                                            variant_llvm_type,
1525                                            &variant_name,
1526                                            unique_type_id,
1527                                            containing_scope);
1528
1529     // Get the argument names from the enum variant info
1530     let mut arg_names: Vec<_> = match variant.kind {
1531         ty::VariantKind::Unit => vec![],
1532         ty::VariantKind::Tuple => {
1533             variant.fields
1534                    .iter()
1535                    .enumerate()
1536                    .map(|(i, _)| format!("__{}", i))
1537                    .collect()
1538         }
1539         ty::VariantKind::Struct => {
1540             variant.fields
1541                    .iter()
1542                    .map(|f| f.name.to_string())
1543                    .collect()
1544         }
1545     };
1546
1547     // If this is not a univariant enum, there is also the discriminant field.
1548     match discriminant_info {
1549         RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1550         _ => { /* do nothing */ }
1551     };
1552
1553     // Build an array of (field name, field type) pairs to be captured in the factory closure.
1554     let args: Vec<(String, Ty)> = arg_names.iter()
1555         .zip(&struct_def.fields)
1556         .map(|(s, &t)| (s.to_string(), t))
1557         .collect();
1558
1559     let member_description_factory =
1560         VariantMDF(VariantMemberDescriptionFactory {
1561             args: args,
1562             discriminant_type_metadata: match discriminant_info {
1563                 RegularDiscriminant(discriminant_type_metadata) => {
1564                     Some(discriminant_type_metadata)
1565                 }
1566                 _ => None
1567             },
1568             span: span,
1569         });
1570
1571     (metadata_stub, variant_llvm_type, member_description_factory)
1572 }
1573
1574 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1575                                    enum_type: Ty<'tcx>,
1576                                    enum_def_id: DefId,
1577                                    unique_type_id: UniqueTypeId,
1578                                    span: Span)
1579                                    -> RecursiveTypeDescription<'tcx> {
1580     let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1581
1582     let (containing_scope, _) = get_namespace_and_span_for_item(cx, enum_def_id);
1583     // FIXME: This should emit actual file metadata for the enum, but we
1584     // currently can't get the necessary information when it comes to types
1585     // imported from other crates. Formerly we violated the ODR when performing
1586     // LTO because we emitted debuginfo for the same type with varying file
1587     // metadata, so as a workaround we pretend that the type comes from
1588     // <unknown>
1589     let file_metadata = unknown_file_metadata(cx);
1590
1591     let variants = &enum_type.ty_adt_def().unwrap().variants;
1592
1593     let enumerators_metadata: Vec<DIDescriptor> = variants
1594         .iter()
1595         .map(|v| {
1596             let token = v.name.as_str();
1597             let name = CString::new(token.as_bytes()).unwrap();
1598             unsafe {
1599                 llvm::LLVMRustDIBuilderCreateEnumerator(
1600                     DIB(cx),
1601                     name.as_ptr(),
1602                     v.disr_val.to_u64_unchecked())
1603             }
1604         })
1605         .collect();
1606
1607     let discriminant_type_metadata = |inttype: syntax::attr::IntType| {
1608         let disr_type_key = (enum_def_id, inttype);
1609         let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1610                                                                  .borrow()
1611                                                                  .get(&disr_type_key).cloned();
1612         match cached_discriminant_type_metadata {
1613             Some(discriminant_type_metadata) => discriminant_type_metadata,
1614             None => {
1615                 let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
1616                 let (discriminant_size, discriminant_align) =
1617                     size_and_align_of(cx, discriminant_llvm_type);
1618                 let discriminant_base_type_metadata =
1619                     type_metadata(cx,
1620                                   adt::ty_of_inttype(cx.tcx(), inttype),
1621                                   syntax_pos::DUMMY_SP);
1622                 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1623
1624                 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1625                 let discriminant_type_metadata = unsafe {
1626                     llvm::LLVMRustDIBuilderCreateEnumerationType(
1627                         DIB(cx),
1628                         containing_scope,
1629                         name.as_ptr(),
1630                         file_metadata,
1631                         UNKNOWN_LINE_NUMBER,
1632                         bytes_to_bits(discriminant_size),
1633                         bytes_to_bits(discriminant_align),
1634                         create_DIArray(DIB(cx), &enumerators_metadata),
1635                         discriminant_base_type_metadata)
1636                 };
1637
1638                 debug_context(cx).created_enum_disr_types
1639                                  .borrow_mut()
1640                                  .insert(disr_type_key, discriminant_type_metadata);
1641
1642                 discriminant_type_metadata
1643             }
1644         }
1645     };
1646
1647     let type_rep = adt::represent_type(cx, enum_type);
1648
1649     let discriminant_type_metadata = match *type_rep {
1650         adt::CEnum(inttype, _, _) => {
1651             return FinalMetadata(discriminant_type_metadata(inttype))
1652         },
1653         adt::RawNullablePointer { .. }           |
1654         adt::StructWrappedNullablePointer { .. } |
1655         adt::Univariant(..)                      => None,
1656         adt::General(inttype, _, _) => Some(discriminant_type_metadata(inttype)),
1657     };
1658
1659     let enum_llvm_type = type_of::type_of(cx, enum_type);
1660     let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1661
1662     let unique_type_id_str = debug_context(cx)
1663                              .type_map
1664                              .borrow()
1665                              .get_unique_type_id_as_string(unique_type_id);
1666
1667     let enum_name = CString::new(enum_name).unwrap();
1668     let unique_type_id_str = CString::new(unique_type_id_str.as_bytes()).unwrap();
1669     let enum_metadata = unsafe {
1670         llvm::LLVMRustDIBuilderCreateUnionType(
1671         DIB(cx),
1672         containing_scope,
1673         enum_name.as_ptr(),
1674         file_metadata,
1675         UNKNOWN_LINE_NUMBER,
1676         bytes_to_bits(enum_type_size),
1677         bytes_to_bits(enum_type_align),
1678         0, // Flags
1679         ptr::null_mut(),
1680         0, // RuntimeLang
1681         unique_type_id_str.as_ptr())
1682     };
1683
1684     return create_and_register_recursive_type_forward_declaration(
1685         cx,
1686         enum_type,
1687         unique_type_id,
1688         enum_metadata,
1689         enum_llvm_type,
1690         EnumMDF(EnumMemberDescriptionFactory {
1691             enum_type: enum_type,
1692             type_rep: type_rep.clone(),
1693             discriminant_type_metadata: discriminant_type_metadata,
1694             containing_scope: containing_scope,
1695             file_metadata: file_metadata,
1696             span: span,
1697         }),
1698     );
1699
1700     fn get_enum_discriminant_name(cx: &CrateContext,
1701                                   def_id: DefId)
1702                                   -> token::InternedString {
1703         cx.tcx().item_name(def_id).as_str()
1704     }
1705 }
1706
1707 /// Creates debug information for a composite type, that is, anything that
1708 /// results in a LLVM struct.
1709 ///
1710 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1711 fn composite_type_metadata(cx: &CrateContext,
1712                            composite_llvm_type: Type,
1713                            composite_type_name: &str,
1714                            composite_type_unique_id: UniqueTypeId,
1715                            member_descriptions: &[MemberDescription],
1716                            containing_scope: DIScope,
1717
1718                            // Ignore source location information as long as it
1719                            // can't be reconstructed for non-local crates.
1720                            _file_metadata: DIFile,
1721                            _definition_span: Span)
1722                            -> DICompositeType {
1723     // Create the (empty) struct metadata node ...
1724     let composite_type_metadata = create_struct_stub(cx,
1725                                                      composite_llvm_type,
1726                                                      composite_type_name,
1727                                                      composite_type_unique_id,
1728                                                      containing_scope);
1729     // ... and immediately create and add the member descriptions.
1730     set_members_of_composite_type(cx,
1731                                   composite_type_metadata,
1732                                   composite_llvm_type,
1733                                   member_descriptions);
1734
1735     return composite_type_metadata;
1736 }
1737
1738 fn set_members_of_composite_type(cx: &CrateContext,
1739                                  composite_type_metadata: DICompositeType,
1740                                  composite_llvm_type: Type,
1741                                  member_descriptions: &[MemberDescription]) {
1742     // In some rare cases LLVM metadata uniquing would lead to an existing type
1743     // description being used instead of a new one created in
1744     // create_struct_stub. This would cause a hard to trace assertion in
1745     // DICompositeType::SetTypeArray(). The following check makes sure that we
1746     // get a better error message if this should happen again due to some
1747     // regression.
1748     {
1749         let mut composite_types_completed =
1750             debug_context(cx).composite_types_completed.borrow_mut();
1751         if composite_types_completed.contains(&composite_type_metadata) {
1752             bug!("debuginfo::set_members_of_composite_type() - \
1753                   Already completed forward declaration re-encountered.");
1754         } else {
1755             composite_types_completed.insert(composite_type_metadata);
1756         }
1757     }
1758
1759     let member_metadata: Vec<DIDescriptor> = member_descriptions
1760         .iter()
1761         .enumerate()
1762         .map(|(i, member_description)| {
1763             let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1764             let member_offset = match member_description.offset {
1765                 FixedMemberOffset { bytes } => bytes as u64,
1766                 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1767             };
1768
1769             let member_name = member_description.name.as_bytes();
1770             let member_name = CString::new(member_name).unwrap();
1771             unsafe {
1772                 llvm::LLVMRustDIBuilderCreateMemberType(
1773                     DIB(cx),
1774                     composite_type_metadata,
1775                     member_name.as_ptr(),
1776                     unknown_file_metadata(cx),
1777                     UNKNOWN_LINE_NUMBER,
1778                     bytes_to_bits(member_size),
1779                     bytes_to_bits(member_align),
1780                     bytes_to_bits(member_offset),
1781                     member_description.flags,
1782                     member_description.type_metadata)
1783             }
1784         })
1785         .collect();
1786
1787     unsafe {
1788         let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1789         llvm::LLVMRustDICompositeTypeSetTypeArray(
1790             DIB(cx), composite_type_metadata, type_array);
1791     }
1792 }
1793
1794 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1795 // any caching, does not add any fields to the struct. This can be done later
1796 // with set_members_of_composite_type().
1797 fn create_struct_stub(cx: &CrateContext,
1798                       struct_llvm_type: Type,
1799                       struct_type_name: &str,
1800                       unique_type_id: UniqueTypeId,
1801                       containing_scope: DIScope)
1802                    -> DICompositeType {
1803     let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1804
1805     let unique_type_id_str = debug_context(cx).type_map
1806                                               .borrow()
1807                                               .get_unique_type_id_as_string(unique_type_id);
1808     let name = CString::new(struct_type_name).unwrap();
1809     let unique_type_id = CString::new(unique_type_id_str.as_bytes()).unwrap();
1810     let metadata_stub = unsafe {
1811         // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1812         // pointer will lead to hard to trace and debug LLVM assertions
1813         // later on in llvm/lib/IR/Value.cpp.
1814         let empty_array = create_DIArray(DIB(cx), &[]);
1815
1816         llvm::LLVMRustDIBuilderCreateStructType(
1817             DIB(cx),
1818             containing_scope,
1819             name.as_ptr(),
1820             unknown_file_metadata(cx),
1821             UNKNOWN_LINE_NUMBER,
1822             bytes_to_bits(struct_size),
1823             bytes_to_bits(struct_align),
1824             0,
1825             ptr::null_mut(),
1826             empty_array,
1827             0,
1828             ptr::null_mut(),
1829             unique_type_id.as_ptr())
1830     };
1831
1832     return metadata_stub;
1833 }
1834
1835 /// Creates debug information for the given global variable.
1836 ///
1837 /// Adds the created metadata nodes directly to the crate's IR.
1838 pub fn create_global_var_metadata(cx: &CrateContext,
1839                                   node_id: ast::NodeId,
1840                                   global: ValueRef) {
1841     if cx.dbg_cx().is_none() {
1842         return;
1843     }
1844
1845     // Don't create debuginfo for globals inlined from other crates. The other
1846     // crate should already contain debuginfo for it. More importantly, the
1847     // global might not even exist in un-inlined form anywhere which would lead
1848     // to a linker errors.
1849     if cx.tcx().map.is_inlined_node_id(node_id) {
1850         return;
1851     }
1852
1853     let node_def_id = cx.tcx().map.local_def_id(node_id);
1854     let (var_scope, span) = get_namespace_and_span_for_item(cx, node_def_id);
1855
1856     let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP {
1857         let loc = span_start(cx, span);
1858         (file_metadata(cx, &loc.file.name, &loc.file.abs_path), loc.line as c_uint)
1859     } else {
1860         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1861     };
1862
1863     let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1864     let variable_type = cx.tcx().node_id_to_type(node_id);
1865     let type_metadata = type_metadata(cx, variable_type, span);
1866     let var_name = cx.tcx().item_name(node_def_id).to_string();
1867     let linkage_name = mangled_name_of_item(cx, node_def_id, "");
1868
1869     let var_name = CString::new(var_name).unwrap();
1870     let linkage_name = CString::new(linkage_name).unwrap();
1871     unsafe {
1872         llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1873                                                     var_scope,
1874                                                     var_name.as_ptr(),
1875                                                     linkage_name.as_ptr(),
1876                                                     file_metadata,
1877                                                     line_number,
1878                                                     type_metadata,
1879                                                     is_local_to_unit,
1880                                                     global,
1881                                                     ptr::null_mut());
1882     }
1883 }
1884
1885 /// Creates debug information for the given local variable.
1886 ///
1887 /// This function assumes that there's a datum for each pattern component of the
1888 /// local in `bcx.fcx.lllocals`.
1889 /// Adds the created metadata nodes directly to the crate's IR.
1890 pub fn create_local_var_metadata(bcx: Block, local: &hir::Local) {
1891     if bcx.unreachable.get() ||
1892        fn_should_be_ignored(bcx.fcx) ||
1893        bcx.sess().opts.debuginfo != FullDebugInfo  {
1894         return;
1895     }
1896
1897     let locals = bcx.fcx.lllocals.borrow();
1898     pat_util::pat_bindings(&local.pat, |_, node_id, span, var_name| {
1899         let datum = match locals.get(&node_id) {
1900             Some(datum) => datum,
1901             None => {
1902                 span_bug!(span,
1903                           "no entry in lllocals table for {}",
1904                           node_id);
1905             }
1906         };
1907
1908         if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
1909             span_bug!(span, "debuginfo::create_local_var_metadata() - \
1910                              Referenced variable location is not an alloca!");
1911         }
1912
1913         let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
1914
1915         declare_local(bcx,
1916                       var_name.node,
1917                       datum.ty,
1918                       scope_metadata,
1919                       VariableAccess::DirectVariable { alloca: datum.val },
1920                       VariableKind::LocalVariable,
1921                       span);
1922     })
1923 }
1924
1925 /// Creates debug information for a variable captured in a closure.
1926 ///
1927 /// Adds the created metadata nodes directly to the crate's IR.
1928 pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1929                                                 node_id: ast::NodeId,
1930                                                 env_pointer: ValueRef,
1931                                                 env_index: usize,
1932                                                 captured_by_ref: bool,
1933                                                 span: Span) {
1934     if bcx.unreachable.get() ||
1935        fn_should_be_ignored(bcx.fcx) ||
1936        bcx.sess().opts.debuginfo != FullDebugInfo {
1937         return;
1938     }
1939
1940     let cx = bcx.ccx();
1941
1942     let ast_item = cx.tcx().map.find(node_id);
1943
1944     let variable_name = match ast_item {
1945         None => {
1946             span_bug!(span, "debuginfo::create_captured_var_metadata: node not found");
1947         }
1948         Some(hir_map::NodeLocal(pat)) => {
1949             match pat.node {
1950                 PatKind::Binding(_, ref path1, _) => {
1951                     path1.node
1952                 }
1953                 _ => {
1954                     span_bug!(span,
1955                               "debuginfo::create_captured_var_metadata() - \
1956                                Captured var-id refers to unexpected \
1957                                hir_map variant: {:?}",
1958                               ast_item);
1959                 }
1960             }
1961         }
1962         _ => {
1963             span_bug!(span,
1964                       "debuginfo::create_captured_var_metadata() - \
1965                        Captured var-id refers to unexpected \
1966                        hir_map variant: {:?}",
1967                       ast_item);
1968         }
1969     };
1970
1971     let variable_type = common::node_id_type(bcx, node_id);
1972     let scope_metadata = bcx.fcx.debug_context.get_ref(span).fn_metadata;
1973
1974     // env_pointer is the alloca containing the pointer to the environment,
1975     // so it's type is **EnvironmentType. In order to find out the type of
1976     // the environment we have to "dereference" two times.
1977     let llvm_env_data_type = common::val_ty(env_pointer).element_type()
1978                                                         .element_type();
1979     let byte_offset_of_var_in_env = machine::llelement_offset(cx,
1980                                                               llvm_env_data_type,
1981                                                               env_index);
1982
1983     let address_operations = unsafe {
1984         [llvm::LLVMRustDIBuilderCreateOpDeref(),
1985          llvm::LLVMRustDIBuilderCreateOpPlus(),
1986          byte_offset_of_var_in_env as i64,
1987          llvm::LLVMRustDIBuilderCreateOpDeref()]
1988     };
1989
1990     let address_op_count = if captured_by_ref {
1991         address_operations.len()
1992     } else {
1993         address_operations.len() - 1
1994     };
1995
1996     let variable_access = VariableAccess::IndirectVariable {
1997         alloca: env_pointer,
1998         address_operations: &address_operations[..address_op_count]
1999     };
2000
2001     declare_local(bcx,
2002                   variable_name,
2003                   variable_type,
2004                   scope_metadata,
2005                   variable_access,
2006                   VariableKind::CapturedVariable,
2007                   span);
2008 }
2009
2010 /// Creates debug information for a local variable introduced in the head of a
2011 /// match-statement arm.
2012 ///
2013 /// Adds the created metadata nodes directly to the crate's IR.
2014 pub fn create_match_binding_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2015                                                  variable_name: ast::Name,
2016                                                  binding: BindingInfo<'tcx>) {
2017     if bcx.unreachable.get() ||
2018        fn_should_be_ignored(bcx.fcx) ||
2019        bcx.sess().opts.debuginfo != FullDebugInfo {
2020         return;
2021     }
2022
2023     let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span);
2024     let aops = unsafe {
2025         [llvm::LLVMRustDIBuilderCreateOpDeref()]
2026     };
2027     // Regardless of the actual type (`T`) we're always passed the stack slot
2028     // (alloca) for the binding. For ByRef bindings that's a `T*` but for ByMove
2029     // bindings we actually have `T**`. So to get the actual variable we need to
2030     // dereference once more. For ByCopy we just use the stack slot we created
2031     // for the binding.
2032     let var_access = match binding.trmode {
2033         TransBindingMode::TrByCopy(llbinding) |
2034         TransBindingMode::TrByMoveIntoCopy(llbinding) => VariableAccess::DirectVariable {
2035             alloca: llbinding
2036         },
2037         TransBindingMode::TrByMoveRef => VariableAccess::IndirectVariable {
2038             alloca: binding.llmatch,
2039             address_operations: &aops
2040         },
2041         TransBindingMode::TrByRef => VariableAccess::DirectVariable {
2042             alloca: binding.llmatch
2043         }
2044     };
2045
2046     declare_local(bcx,
2047                   variable_name,
2048                   binding.ty,
2049                   scope_metadata,
2050                   var_access,
2051                   VariableKind::LocalVariable,
2052                   binding.span);
2053 }
2054
2055 /// Creates debug information for the given function argument.
2056 ///
2057 /// This function assumes that there's a datum for each pattern component of the
2058 /// argument in `bcx.fcx.lllocals`.
2059 /// Adds the created metadata nodes directly to the crate's IR.
2060 pub fn create_argument_metadata(bcx: Block, arg: &hir::Arg) {
2061     if bcx.unreachable.get() ||
2062        fn_should_be_ignored(bcx.fcx) ||
2063        bcx.sess().opts.debuginfo != FullDebugInfo {
2064         return;
2065     }
2066
2067     let scope_metadata = bcx
2068                          .fcx
2069                          .debug_context
2070                          .get_ref(arg.pat.span)
2071                          .fn_metadata;
2072     let locals = bcx.fcx.lllocals.borrow();
2073
2074     pat_util::pat_bindings(&arg.pat, |_, node_id, span, var_name| {
2075         let datum = match locals.get(&node_id) {
2076             Some(v) => v,
2077             None => {
2078                 span_bug!(span, "no entry in lllocals table for {}", node_id);
2079             }
2080         };
2081
2082         if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
2083             span_bug!(span, "debuginfo::create_argument_metadata() - \
2084                              Referenced variable location is not an alloca!");
2085         }
2086
2087         let argument_index = {
2088             let counter = &bcx
2089                           .fcx
2090                           .debug_context
2091                           .get_ref(span)
2092                           .argument_counter;
2093             let argument_index = counter.get();
2094             counter.set(argument_index + 1);
2095             argument_index
2096         };
2097
2098         declare_local(bcx,
2099                       var_name.node,
2100                       datum.ty,
2101                       scope_metadata,
2102                       VariableAccess::DirectVariable { alloca: datum.val },
2103                       VariableKind::ArgumentVariable(argument_index),
2104                       span);
2105     })
2106 }