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